FlatCAMApp.py 523 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644
  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 ctypes
  20. import tkinter as tk
  21. from PyQt5 import QtPrintSupport
  22. from contextlib import contextmanager
  23. import gc
  24. from xml.dom.minidom import parseString as parse_xml_string
  25. from multiprocessing.connection import Listener, Client
  26. from multiprocessing import Pool
  27. import socket
  28. from array import array
  29. # #######################################
  30. # # Imports part of FlatCAM ##
  31. # #######################################
  32. from ObjectCollection import *
  33. from FlatCAMObj import *
  34. from flatcamGUI.PlotCanvas import *
  35. from flatcamGUI.PlotCanvasLegacy import *
  36. from flatcamGUI.FlatCAMGUI import *
  37. from FlatCAMCommon import LoudDict
  38. from FlatCAMPostProc import load_postprocessors
  39. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  40. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  41. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  42. from FlatCAMProcess import *
  43. from FlatCAMWorkerStack import WorkerStack
  44. from flatcamGUI.VisPyVisuals import Color
  45. from vispy.gloo.util import _screenshot
  46. from vispy.io import write_png
  47. from flatcamTools import *
  48. import tclCommands
  49. import gettext
  50. import FlatCAMTranslation as fcTranslate
  51. import builtins
  52. if sys.platform == 'win32':
  53. import winreg
  54. fcTranslate.apply_language('strings')
  55. if '_' not in builtins.__dict__:
  56. _ = gettext.gettext
  57. # ########################################
  58. # # App ###
  59. # ########################################
  60. class App(QtCore.QObject):
  61. """
  62. The main application class. The constructor starts the GUI.
  63. """
  64. # Get Cmd Line Options
  65. cmd_line_shellfile = ''
  66. cmd_line_shellvar = ''
  67. cmd_line_headless = None
  68. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  69. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  70. "FlatCam.py --headless=1"
  71. try:
  72. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  73. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  74. "shellvar=",
  75. "headless=",
  76. "multiprocessing-fork="])
  77. except getopt.GetoptError:
  78. print(cmd_line_help)
  79. sys.exit(2)
  80. for opt, arg in cmd_line_options:
  81. if opt == '-h':
  82. print(cmd_line_help)
  83. sys.exit()
  84. elif opt == '--shellfile':
  85. cmd_line_shellfile = arg
  86. elif opt == '--shellvar':
  87. cmd_line_shellvar = arg
  88. elif opt == '--headless':
  89. try:
  90. cmd_line_headless = eval(arg)
  91. except NameError:
  92. pass
  93. # ## Logging ###
  94. log = logging.getLogger('base')
  95. log.setLevel(logging.DEBUG)
  96. # log.setLevel(logging.WARNING)
  97. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  98. handler = logging.StreamHandler()
  99. handler.setFormatter(formatter)
  100. log.addHandler(handler)
  101. # ##########################################################################
  102. # ################## Version and VERSION DATE ##############################
  103. # ##########################################################################
  104. version = 8.97
  105. version_date = "2019/09/27"
  106. beta = True
  107. engine = '3D'
  108. # current date now
  109. date = str(datetime.today()).rpartition('.')[0]
  110. date = ''.join(c for c in date if c not in ':-')
  111. date = date.replace(' ', '_')
  112. # URL for update checks and statistics
  113. version_url = "http://flatcam.org/version"
  114. # App URL
  115. app_url = "http://flatcam.org"
  116. # Manual URL
  117. manual_url = "http://flatcam.org/manual/index.html"
  118. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  119. gerber_spec_url ="https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  120. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  121. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  122. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  123. # this variable will hold the project status
  124. # if True it will mean that the project was modified and not saved
  125. should_we_save = False
  126. # flag is True if saving action has been triggered
  127. save_in_progress = False
  128. # ###########################################################################
  129. # ############################# Signals ################################
  130. # ###########################################################################
  131. # Inform the user
  132. # Handled by:
  133. # * App.info() --> Print on the status bar
  134. inform = QtCore.pyqtSignal(str)
  135. app_quit = QtCore.pyqtSignal()
  136. # General purpose background task
  137. worker_task = QtCore.pyqtSignal(dict)
  138. # File opened
  139. # Handled by:
  140. # * register_folder()
  141. # * register_recent()
  142. # Note: Setting the parameters to unicode does not seem
  143. # to have an effect. Then are received as Qstring
  144. # anyway.
  145. # File type and filename
  146. file_opened = QtCore.pyqtSignal(str, str)
  147. # File type and filename
  148. file_saved = QtCore.pyqtSignal(str, str)
  149. # Percentage of progress
  150. progress = QtCore.pyqtSignal(int)
  151. plots_updated = QtCore.pyqtSignal()
  152. # Emitted by new_object() and passes the new object as argument, plot flag.
  153. # on_object_created() adds the object to the collection, plots on appropriate flag
  154. # and emits new_object_available.
  155. object_created = QtCore.pyqtSignal(object, bool, bool)
  156. # Emitted when a object has been changed (like scaled, mirrored)
  157. object_changed = QtCore.pyqtSignal(object)
  158. # Emitted after object has been plotted.
  159. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  160. object_plotted = QtCore.pyqtSignal(object)
  161. # Emitted when a new object has been added or deleted from/to the collection
  162. object_status_changed = QtCore.pyqtSignal(object, str)
  163. message = QtCore.pyqtSignal(str, str, str)
  164. # Emmited when shell command is finished(one command only)
  165. shell_command_finished = QtCore.pyqtSignal(object)
  166. # Emitted when multiprocess pool has been recreated
  167. pool_recreated = QtCore.pyqtSignal(object)
  168. # Emitted when an unhandled exception happens
  169. # in the worker task.
  170. thread_exception = QtCore.pyqtSignal(object)
  171. # used to signal that there are arguments for the app
  172. args_at_startup = QtCore.pyqtSignal(list)
  173. # a reusable signal to replot a list of objects
  174. # should be disconnected after use so it can be reused
  175. replot_signal = pyqtSignal(list)
  176. def __init__(self, user_defaults=True, post_gui=None):
  177. """
  178. Starts the application.
  179. :return: app
  180. :rtype: App
  181. """
  182. App.log.info("FlatCAM Starting...")
  183. self.main_thread = QtWidgets.QApplication.instance().thread()
  184. # ############################################################################
  185. # # ################# OS-specific ############################################
  186. # ############################################################################
  187. portable = False
  188. # Folder for user settings.
  189. if sys.platform == 'win32':
  190. # #########################################################################
  191. # Setup the listening thread for another instance launching with args #####
  192. # #########################################################################
  193. # make sure the thread is stored by using a self. otherwise it's garbage collected
  194. self.th = QtCore.QThread()
  195. self.th.start(priority=QtCore.QThread.LowestPriority)
  196. self.new_launch = ArgsThread()
  197. self.new_launch.open_signal[list].connect(self.on_startup_args)
  198. self.new_launch.moveToThread(self.th)
  199. self.new_launch.start.emit()
  200. from win32com.shell import shell, shellcon
  201. if platform.architecture()[0] == '32bit':
  202. App.log.debug("Win32!")
  203. else:
  204. App.log.debug("Win64!")
  205. # #########################################################################
  206. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  207. # #########################################################################
  208. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  209. try:
  210. with open(config_file, 'r'):
  211. pass
  212. except FileNotFoundError:
  213. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  214. try:
  215. with open(config_file, 'r') as f:
  216. try:
  217. for line in f:
  218. param = str(line).replace('\n', '').rpartition('=')
  219. if param[0] == 'portable':
  220. try:
  221. portable = eval(param[2])
  222. except NameError:
  223. portable = False
  224. if param[0] == 'headless':
  225. if param[2].lower() == 'true':
  226. self.cmd_line_headless = 1
  227. else:
  228. self.cmd_line_headless = None
  229. except Exception as e:
  230. log.debug('App.__init__() -->%s' % str(e))
  231. return
  232. except FileNotFoundError as e:
  233. log.debug(str(e))
  234. pass
  235. if portable is False:
  236. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  237. else:
  238. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  239. self.os = 'windows'
  240. else: # Linux/Unix/MacOS
  241. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  242. self.os = 'unix'
  243. # ##########################################################################
  244. # ################## Setup folders and files ###############################
  245. # ##########################################################################
  246. if not os.path.exists(self.data_path):
  247. os.makedirs(self.data_path)
  248. App.log.debug('Created data folder: ' + self.data_path)
  249. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  250. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  251. self.postprocessorpaths = os.path.join(self.data_path, 'postprocessors')
  252. if not os.path.exists(self.postprocessorpaths):
  253. os.makedirs(self.postprocessorpaths)
  254. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  255. # create current_defaults.FlatConfig file if there is none
  256. try:
  257. f = open(self.data_path + '/current_defaults.FlatConfig')
  258. f.close()
  259. except IOError:
  260. App.log.debug('Creating empty current_defaults.FlatConfig')
  261. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  262. json.dump({}, f)
  263. f.close()
  264. # create factory_defaults.FlatConfig file if there is none
  265. try:
  266. f = open(self.data_path + '/factory_defaults.FlatConfig')
  267. f.close()
  268. except IOError:
  269. App.log.debug('Creating empty factory_defaults.FlatConfig')
  270. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  271. json.dump({}, f)
  272. f.close()
  273. # create a recent files json file if there is none
  274. try:
  275. f = open(self.data_path + '/recent.json')
  276. f.close()
  277. except IOError:
  278. App.log.debug('Creating empty recent.json')
  279. f = open(self.data_path + '/recent.json', 'w')
  280. json.dump([], f)
  281. f.close()
  282. # create a recent projects json file if there is none
  283. try:
  284. fp = open(self.data_path + '/recent_projects.json')
  285. fp.close()
  286. except IOError:
  287. App.log.debug('Creating empty recent_projects.json')
  288. fp = open(self.data_path + '/recent_projects.json', 'w')
  289. json.dump([], fp)
  290. fp.close()
  291. # Application directory. CHDIR to it. Otherwise, trying to load
  292. # GUI icons will fail as their path is relative.
  293. # This will fail under cx_freeze ...
  294. self.app_home = os.path.dirname(os.path.realpath(__file__))
  295. App.log.debug("Application path is " + self.app_home)
  296. App.log.debug("Started in " + os.getcwd())
  297. # cx_freeze workaround
  298. if os.path.isfile(self.app_home):
  299. self.app_home = os.path.dirname(self.app_home)
  300. os.chdir(self.app_home)
  301. # #############################################################################
  302. # ##################### CREATE MULTIPROCESSING POOL ###########################
  303. # #############################################################################
  304. self.pool = Pool()
  305. # ##########################################################################
  306. # ################## Setting the Splash Screen #############################
  307. # ##########################################################################
  308. settings = QSettings("Open Source", "FlatCAM")
  309. if settings.contains("splash_screen"):
  310. show_splash = settings.value("splash_screen")
  311. else:
  312. settings.setValue('splash_screen', 1)
  313. # This will write the setting to the platform specific storage.
  314. del settings
  315. show_splash = 1
  316. if show_splash and self.cmd_line_headless != 1:
  317. splash_pix = QtGui.QPixmap('share/splash.png')
  318. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  319. # self.splash.setMask(splash_pix.mask())
  320. # move splashscreen to the current monitor
  321. desktop = QtWidgets.QApplication.desktop()
  322. screen = desktop.screenNumber(QtGui.QCursor.pos())
  323. current_screen_center = desktop.availableGeometry(screen).center()
  324. self.splash.move(current_screen_center - self.splash.rect().center())
  325. self.splash.show()
  326. self.splash.showMessage(_("FlatCAM is initializing ..."),
  327. alignment=Qt.AlignBottom | Qt.AlignLeft,
  328. color=QtGui.QColor("gray"))
  329. else:
  330. show_splash = 0
  331. # #############################################################################
  332. # ##################### Initialize GUI ########################################
  333. # #############################################################################
  334. # FlatCAM colors used in plotting
  335. self.FC_light_green = '#BBF268BF'
  336. self.FC_dark_green = '#006E20BF'
  337. self.FC_light_blue = '#a5a5ffbf'
  338. self.FC_dark_blue = '#0000ffbf'
  339. QtCore.QObject.__init__(self)
  340. self.ui = FlatCAMGUI(self.version, self.beta, self)
  341. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  342. self.ui.final_save.connect(self.final_save)
  343. # #############################################################################
  344. # ############################## Data #########################################
  345. # #############################################################################
  346. self.recent = []
  347. self.recent_projects = []
  348. self.clipboard = QtWidgets.QApplication.clipboard()
  349. self.project_filename = None
  350. self.toggle_units_ignore = False
  351. # self.defaults_form = PreferencesUI()
  352. # when adding entries here read the comments in the method found bellow named:
  353. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  354. self.defaults_form_fields = {
  355. # General App
  356. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  357. "global_graphic_engine": self.ui.general_defaults_form.general_app_group.ge_radio,
  358. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  359. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  360. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  361. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  362. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  363. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  364. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  365. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  366. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  367. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  368. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  369. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  370. # General GUI Preferences
  371. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  372. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  373. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  374. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  375. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  376. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  377. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  378. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  379. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  380. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  381. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  382. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  383. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  384. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  385. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  386. "global_activity_icon": self.ui.general_defaults_form.general_gui_group.activity_combo,
  387. # General GUI Settings
  388. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  389. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  390. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  391. "global_systray_icon": self.ui.general_defaults_form.general_gui_set_group.systray_cb,
  392. "global_shell_at_startup": self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb,
  393. "global_project_at_startup": self.ui.general_defaults_form.general_gui_set_group.project_startup_cb,
  394. "global_project_autohide": self.ui.general_defaults_form.general_gui_set_group.project_autohide_cb,
  395. "global_toggle_tooltips": self.ui.general_defaults_form.general_gui_set_group.toggle_tooltips_cb,
  396. "global_delete_confirmation": self.ui.general_defaults_form.general_gui_set_group.delete_conf_cb,
  397. # Gerber General
  398. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  399. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  400. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  401. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  402. # Gerber Options
  403. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  404. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  405. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  406. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  407. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  408. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  409. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  410. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  411. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  412. # Gerber Advanced Options
  413. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  414. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  415. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  416. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  417. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  418. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  419. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  420. # Gerber Export
  421. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  422. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  423. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  424. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  425. # Gerber Editor
  426. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  427. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  428. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  429. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  430. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  431. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  432. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  433. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  434. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  435. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  436. "gerber_editor_circ_angle":
  437. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  438. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  439. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  440. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  441. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  442. # Excellon General
  443. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  444. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  445. "excellon_format_upper_in":
  446. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  447. "excellon_format_lower_in":
  448. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  449. "excellon_format_upper_mm":
  450. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  451. "excellon_format_lower_mm":
  452. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  453. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  454. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  455. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  456. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  457. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  458. # Excellon Options
  459. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  460. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  461. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.eendz_entry,
  462. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  463. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  464. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  465. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  466. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  467. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  468. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  469. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  470. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  471. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  472. # Excellon Advanced Options
  473. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  474. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  475. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  476. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  477. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  478. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  479. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  480. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  481. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  482. # Excellon Export
  483. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  484. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  485. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  486. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  487. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  488. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  489. # Excellon Editor
  490. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  491. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  492. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  493. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  494. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  495. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  496. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  497. "excellon_editor_circ_angle":
  498. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  499. # Excellon Slots
  500. "excellon_editor_slot_direction":
  501. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  502. "excellon_editor_slot_angle":
  503. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  504. "excellon_editor_slot_length":
  505. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  506. # Excellon Slots
  507. "excellon_editor_slot_array_size":
  508. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  509. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  510. "excellon_editor_slot_lin_pitch":
  511. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  512. "excellon_editor_slot_lin_angle":
  513. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  514. "excellon_editor_slot_circ_dir":
  515. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  516. "excellon_editor_slot_circ_angle":
  517. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  518. # Geometry General
  519. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  520. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  521. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  522. # Geometry Options
  523. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  524. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  525. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  526. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  527. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  528. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  529. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  530. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  531. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  532. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  533. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.gendz_entry,
  534. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  535. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  536. # Geometry Advanced Options
  537. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  538. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  539. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  540. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  541. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  542. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  543. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  544. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  545. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  546. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  547. # Geometry Editor
  548. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  549. "geometry_editor_milling_type": self.ui.geometry_defaults_form.geometry_editor_group.milling_type_radio,
  550. # CNCJob General
  551. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  552. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  553. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  554. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  555. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  556. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  557. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  558. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  559. # CNC Job Options
  560. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  561. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  562. # CNC Job Advanced Options
  563. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  564. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  565. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  566. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  567. # NCC Tool
  568. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  569. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  570. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  571. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  572. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  573. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  574. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  575. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  576. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  577. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  578. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  579. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  580. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  581. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  582. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  583. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  584. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  585. # CutOut Tool
  586. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  587. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  588. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  589. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  590. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  591. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  592. # Paint Area Tool
  593. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  594. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  595. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  596. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  597. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  598. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  599. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  600. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  601. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  602. # 2-sided Tool
  603. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  604. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  605. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  606. # Film Tool
  607. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  608. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  609. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  610. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  611. # Panelize Tool
  612. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  613. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  614. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  615. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  616. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  617. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  618. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  619. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  620. # Calculators Tool
  621. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  622. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  623. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  624. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  625. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  626. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  627. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  628. # Transformations Tool
  629. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  630. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  631. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  632. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  633. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  634. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  635. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  636. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  637. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  638. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  639. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  640. # SolderPaste Dispensing Tool
  641. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  642. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  643. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  644. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  645. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  646. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  647. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  648. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  649. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  650. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  651. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  652. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  653. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  654. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  655. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  656. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  657. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  658. # Utilities
  659. # File associations
  660. "fa_excellon": self.ui.util_defaults_form.fa_excellon_group.exc_list_text,
  661. "fa_gcode": self.ui.util_defaults_form.fa_gcode_group.gco_list_text,
  662. # "fa_geometry": self.ui.util_defaults_form.fa_geometry_group.close_paths_cb,
  663. "fa_gerber": self.ui.util_defaults_form.fa_gerber_group.grb_list_text,
  664. "util_autocomplete_keywords": self.ui.util_defaults_form.kw_group.kw_list_text,
  665. }
  666. # ############################
  667. # ### LOAD POSTPROCESSORS ####
  668. # ############################
  669. self.postprocessors = load_postprocessors(self)
  670. for name in list(self.postprocessors.keys()):
  671. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  672. if name.partition('_')[0] == 'Paste':
  673. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  674. continue
  675. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  676. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  677. if name == 'hpgl':
  678. continue
  679. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  680. # ############################
  681. # ### LOAD LANGUAGES ####
  682. # ############################
  683. self.languages = fcTranslate.load_languages()
  684. for name in sorted(self.languages.values()):
  685. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  686. # #################################################################################
  687. # #################### DEFAULTS - PREFERENCES STORAGE #############################
  688. # #################################################################################
  689. self.defaults = LoudDict()
  690. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  691. self.defaults.update({
  692. # Global APP Preferences
  693. "first_run": True,
  694. "units": "IN",
  695. "global_serial": 0,
  696. "global_stats": {},
  697. "global_tabs_detachable": True,
  698. "global_graphic_engine": '3D',
  699. "global_app_level": 'b',
  700. "global_portable": False,
  701. "global_language": 'English',
  702. "global_version_check": True,
  703. "global_send_stats": True,
  704. "global_pan_button": '2',
  705. "global_mselect_key": 'Control',
  706. "global_project_at_startup": False,
  707. "global_systray_icon": True,
  708. "global_project_autohide": True,
  709. "global_toggle_tooltips": True,
  710. "global_worker_number": 2,
  711. "global_tolerance": 0.005,
  712. "global_open_style": True,
  713. "global_delete_confirmation": True,
  714. "global_compression_level": 3,
  715. "global_save_compressed": True,
  716. # Global GUI Preferences
  717. "global_gridx": 0.0393701,
  718. "global_gridy": 0.0393701,
  719. "global_snap_max": 0.001968504,
  720. "global_workspace": False,
  721. "global_workspaceT": "A4P",
  722. "global_grid_context_menu": {
  723. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  724. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  725. },
  726. "global_plot_fill": '#BBF268BF',
  727. "global_plot_line": '#006E20BF',
  728. "global_sel_fill": '#a5a5ffbf',
  729. "global_sel_line": '#0000ffbf',
  730. "global_alt_sel_fill": '#BBF268BF',
  731. "global_alt_sel_line": '#006E20BF',
  732. "global_draw_color": '#FF0000',
  733. "global_sel_draw_color": '#0000FF',
  734. "global_proj_item_color": '#000000',
  735. "global_proj_item_dis_color": '#b7b7cb',
  736. "global_activity_icon": 'Ball green',
  737. "global_toolbar_view": 511,
  738. "global_background_timeout": 300000, # Default value is 5 minutes
  739. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  740. # (python trace only for unknown errors),
  741. # 1 = show trace(show trace always),
  742. # 2 = (For the future).
  743. # Persistence
  744. "global_last_folder": None,
  745. "global_last_save_folder": None,
  746. # Default window geometry
  747. "global_def_win_x": 100,
  748. "global_def_win_y": 100,
  749. "global_def_win_w": 1024,
  750. "global_def_win_h": 650,
  751. "global_def_notebook_width": 1,
  752. # Constants...
  753. "global_defaults_save_period_ms": 20000, # Time between default saves.
  754. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  755. "global_shell_at_startup": False, # Show the shell at startup.
  756. "global_recent_limit": 10, # Max. items in recent list.
  757. "fit_key": 'V',
  758. "zoom_out_key": '-',
  759. "zoom_in_key": '=',
  760. "grid_toggle_key": 'G',
  761. "global_zoom_ratio": 1.5,
  762. "global_point_clipboard_format": "(%.4f, %.4f)",
  763. "global_zdownrate": None,
  764. # General GUI Settings
  765. "global_hover": False,
  766. "global_selection_shape": True,
  767. "global_layout": "compact",
  768. # Gerber General
  769. "gerber_plot": True,
  770. "gerber_solid": True,
  771. "gerber_multicolored": False,
  772. "gerber_circle_steps": 128,
  773. "gerber_use_buffer_for_union": True,
  774. # Gerber Options
  775. "gerber_isotooldia": 0.00787402,
  776. "gerber_isopasses": 1,
  777. "gerber_isooverlap": 0.00393701,
  778. "gerber_milling_type": "cl",
  779. "gerber_combine_passes": False,
  780. "gerber_noncoppermargin": 0.00393701,
  781. "gerber_noncopperrounded": False,
  782. "gerber_bboxmargin": 0.00393701,
  783. "gerber_bboxrounded": False,
  784. # Gerber Advanced Options
  785. "gerber_aperture_display": False,
  786. "gerber_aperture_scale_factor": 1.0,
  787. "gerber_aperture_buffer_factor": 0.0,
  788. "gerber_follow": False,
  789. "gerber_buffering": "full",
  790. "gerber_simplification": False,
  791. "gerber_simp_tolerance": 0.0005,
  792. # Gerber Export
  793. "gerber_exp_units": 'IN',
  794. "gerber_exp_integer": 2,
  795. "gerber_exp_decimals": 4,
  796. "gerber_exp_zeros": 'L',
  797. # Gerber Editor
  798. "gerber_editor_sel_limit": 30,
  799. "gerber_editor_newcode": 10,
  800. "gerber_editor_newsize": 0.8,
  801. "gerber_editor_newtype": 'C',
  802. "gerber_editor_newdim": "0.5, 0.5",
  803. "gerber_editor_array_size": 5,
  804. "gerber_editor_lin_axis": 'X',
  805. "gerber_editor_lin_pitch": 1,
  806. "gerber_editor_lin_angle": 0.0,
  807. "gerber_editor_circ_dir": 'CW',
  808. "gerber_editor_circ_angle": 0.0,
  809. "gerber_editor_scale_f": 1.0,
  810. "gerber_editor_buff_f": 0.1,
  811. "gerber_editor_ma_low": 0.0,
  812. "gerber_editor_ma_high": 1.0,
  813. # Excellon General
  814. "excellon_plot": True,
  815. "excellon_solid": True,
  816. "excellon_format_upper_in": 2,
  817. "excellon_format_lower_in": 4,
  818. "excellon_format_upper_mm": 3,
  819. "excellon_format_lower_mm": 3,
  820. "excellon_zeros": "L",
  821. "excellon_units": "INCH",
  822. "excellon_update": True,
  823. "excellon_optimization_type": 'B',
  824. "excellon_search_time": 3,
  825. # Excellon Options
  826. "excellon_drillz": -0.0590551,
  827. "excellon_travelz": 0.0787402,
  828. "excellon_endz": 0.5,
  829. "excellon_feedrate": 3.14961,
  830. "excellon_spindlespeed": None,
  831. "excellon_dwell": False,
  832. "excellon_dwelltime": 1,
  833. "excellon_toolchange": False,
  834. "excellon_toolchangez": 0.5,
  835. "excellon_ppname_e": 'default',
  836. "excellon_tooldia": 0.0314961,
  837. "excellon_slot_tooldia": 0.0708661,
  838. "excellon_gcode_type": "drills",
  839. # Excellon Advanced Options
  840. "excellon_offset": 0.0,
  841. "excellon_toolchangexy": "0.0, 0.0",
  842. "excellon_startz": None,
  843. "excellon_feedrate_rapid": 31.4961,
  844. "excellon_z_pdepth": -0.02,
  845. "excellon_feedrate_probe": 3.14961,
  846. "excellon_spindledir": 'CW',
  847. "excellon_f_plunge": False,
  848. "excellon_f_retract": False,
  849. # Excellon Export
  850. "excellon_exp_units": 'INCH',
  851. "excellon_exp_format": 'ndec',
  852. "excellon_exp_integer": 2,
  853. "excellon_exp_decimals": 4,
  854. "excellon_exp_zeros": 'LZ',
  855. "excellon_exp_slot_type": 'routing',
  856. # Excellon Editor
  857. "excellon_editor_sel_limit": 30,
  858. "excellon_editor_newdia": 0.039,
  859. "excellon_editor_array_size": 5,
  860. "excellon_editor_lin_dir": 'X',
  861. "excellon_editor_lin_pitch": 0.1,
  862. "excellon_editor_lin_angle": 0.0,
  863. "excellon_editor_circ_dir": 'CW',
  864. "excellon_editor_circ_angle": 12,
  865. # Excellon Slots
  866. "excellon_editor_slot_direction": 'X',
  867. "excellon_editor_slot_angle": 0.0,
  868. "excellon_editor_slot_length": 5.0,
  869. # Excellon Slot Array
  870. "excellon_editor_slot_array_size": 5,
  871. "excellon_editor_slot_lin_dir": 'X',
  872. "excellon_editor_slot_lin_pitch": 0.1,
  873. "excellon_editor_slot_lin_angle": 0.0,
  874. "excellon_editor_slot_circ_dir": 'CW',
  875. "excellon_editor_slot_circ_angle": 0.0,
  876. # Geometry General
  877. "geometry_plot": True,
  878. "geometry_circle_steps": 128,
  879. "geometry_cnctooldia": "0.0944882",
  880. # Geometry Options
  881. "geometry_cutz": -0.0944882,
  882. "geometry_vtipdia": 0.1,
  883. "geometry_vtipangle": 30,
  884. "geometry_multidepth": False,
  885. "geometry_depthperpass": 0.0314961,
  886. "geometry_travelz": 0.0787402,
  887. "geometry_toolchange": False,
  888. "geometry_toolchangez": 0.5,
  889. "geometry_endz": 0.5,
  890. "geometry_feedrate": 3.14961,
  891. "geometry_feedrate_z": 3.14961,
  892. "geometry_spindlespeed": None,
  893. "geometry_dwell": False,
  894. "geometry_dwelltime": 1,
  895. "geometry_ppname_g": 'default',
  896. # Geometry Advanced Options
  897. "geometry_toolchangexy": "0.0, 0.0",
  898. "geometry_startz": None,
  899. "geometry_feedrate_rapid": 3.14961,
  900. "geometry_extracut": False,
  901. "geometry_z_pdepth": -0.02,
  902. "geometry_f_plunge": False,
  903. "geometry_spindledir": 'CW',
  904. "geometry_feedrate_probe": 3.14961,
  905. "geometry_segx": 0.0,
  906. "geometry_segy": 0.0,
  907. # Geometry Editor
  908. "geometry_editor_sel_limit": 30,
  909. "geometry_editor_milling_type": "cl",
  910. # CNC Job General
  911. "cncjob_plot": True,
  912. "cncjob_plot_kind": 'all',
  913. "cncjob_annotation": True,
  914. "cncjob_tooldia": 0.0393701,
  915. "cncjob_coords_type": "G90",
  916. "cncjob_coords_decimals": 4,
  917. "cncjob_fr_decimals": 2,
  918. "cncjob_steps_per_circle": 128,
  919. # CNC Job Options
  920. "cncjob_prepend": "",
  921. "cncjob_append": "",
  922. # CNC Job Advanced Options
  923. "cncjob_toolchange_macro": "",
  924. "cncjob_toolchange_macro_enable": False,
  925. "cncjob_annotation_fontsize": 9,
  926. "cncjob_annotation_fontcolor": '#990000',
  927. # NCC Tool
  928. "tools_ncctools": "0.0393701, 0.019685",
  929. "tools_nccorder": 'rev',
  930. "tools_nccoverlap": 0.015748,
  931. "tools_nccmargin": 0.0393701,
  932. "tools_nccmethod": "seed",
  933. "tools_nccconnect": True,
  934. "tools_ncccontour": True,
  935. "tools_nccrest": False,
  936. "tools_ncc_offset_choice": False,
  937. "tools_ncc_offset_value": 0.0000,
  938. "tools_nccref": 'itself',
  939. "tools_ncc_plotting": 'normal',
  940. "tools_nccmilling_type": 'cl',
  941. "tools_ncctool_type": 'V',
  942. "tools_ncccutz": -0.001968504,
  943. "tools_ncctipdia": 0.00393701,
  944. "tools_ncctipangle": 30,
  945. # Cutout Tool
  946. "tools_cutouttooldia": 0.0944882,
  947. "tools_cutoutkind": "single",
  948. "tools_cutoutmargin": 0.00393701,
  949. "tools_cutoutgapsize": 0.15748,
  950. "tools_gaps_ff": "4",
  951. "tools_cutout_convexshape": False,
  952. # Paint Tool
  953. "tools_painttooldia": 0.023622,
  954. "tools_paintorder": 'rev',
  955. "tools_paintoverlap": 0.015748,
  956. "tools_paintmargin": 0.0,
  957. "tools_paintmethod": "seed",
  958. "tools_selectmethod": "all",
  959. "tools_pathconnect": True,
  960. "tools_paintcontour": True,
  961. "tools_paint_plotting": 'normal',
  962. # 2-Sided Tool
  963. "tools_2sided_mirror_axis": "X",
  964. "tools_2sided_axis_loc": "point",
  965. "tools_2sided_drilldia": 0.11811,
  966. # Film Tool
  967. "tools_film_type": 'neg',
  968. "tools_film_boundary": 0.0393701,
  969. "tools_film_scale": 0,
  970. "tools_film_color": '#000000',
  971. # Panel Tool
  972. "tools_panelize_spacing_columns": 0,
  973. "tools_panelize_spacing_rows": 0,
  974. "tools_panelize_columns": 1,
  975. "tools_panelize_rows": 1,
  976. "tools_panelize_constrain": False,
  977. "tools_panelize_constrainx": 0.0,
  978. "tools_panelize_constrainy": 0.0,
  979. "tools_panelize_panel_type": 'gerber',
  980. # Calculators Tool
  981. "tools_calc_vshape_tip_dia": 0.007874,
  982. "tools_calc_vshape_tip_angle": 30,
  983. "tools_calc_vshape_cut_z": 0.000787,
  984. "tools_calc_electro_length": 10.0,
  985. "tools_calc_electro_width": 10.0,
  986. "tools_calc_electro_cdensity": 13.0,
  987. "tools_calc_electro_growth": 10.0,
  988. # Transform Tool
  989. "tools_transform_rotate": 90,
  990. "tools_transform_skew_x": 0.0,
  991. "tools_transform_skew_y": 0.0,
  992. "tools_transform_scale_x": 1.0,
  993. "tools_transform_scale_y": 1.0,
  994. "tools_transform_scale_link": True,
  995. "tools_transform_scale_reference": True,
  996. "tools_transform_offset_x": 0.0,
  997. "tools_transform_offset_y": 0.0,
  998. "tools_transform_mirror_reference": False,
  999. "tools_transform_mirror_point": (0, 0),
  1000. # SolderPaste Tool
  1001. "tools_solderpaste_tools": "0.0393701, 0.011811",
  1002. "tools_solderpaste_new": 0.011811,
  1003. "tools_solderpaste_z_start": 0.00019685039,
  1004. "tools_solderpaste_z_dispense": 0.00393701,
  1005. "tools_solderpaste_z_stop": 0.00019685039,
  1006. "tools_solderpaste_z_travel": 0.00393701,
  1007. "tools_solderpaste_z_toolchange": 0.0393701,
  1008. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  1009. "tools_solderpaste_frxy": 3.0,
  1010. "tools_solderpaste_frz": 3.0,
  1011. "tools_solderpaste_frz_dispense": 0.0393701,
  1012. "tools_solderpaste_speedfwd": 20,
  1013. "tools_solderpaste_dwellfwd": 1,
  1014. "tools_solderpaste_speedrev": 10,
  1015. "tools_solderpaste_dwellrev": 1,
  1016. "tools_solderpaste_pp": 'Paste_1',
  1017. # Subtract Tool
  1018. "tools_sub_close_paths": True,
  1019. # Utilities
  1020. # file associations
  1021. "fa_excellon": 'drd, drl, exc, ncd, tap, xln',
  1022. "fa_gcode": 'cnc, din, dnc, ecs, eia, fan, fgc, fnc, gc, gcd, gcode, h, hnc, i, min, mpf, mpr, nc, ncc, '
  1023. 'ncg, ncp, out, plt, ply, rol, sbp, tap, xpi',
  1024. "fa_gerber": 'art, bot, bsm, cmp, crc, crs, dim, g4, gb0, gb1, gb2, gb3, gb5, gb6, gb7, gb8, gb9, gbd, '
  1025. 'gbl, gbo, gbp, gbr, gbs, gdo, ger, gko, gm1, gm2, gm3, grb, gtl, gto, gtp, gts, ly15, ly2, '
  1026. 'mil, pho, plc, pls, smb, smt, sol, spb, spt, ssb, sst, stc, sts, top, tsm',
  1027. # Keyword list
  1028. "util_autocomplete_keywords": 'Desktop, Documents, FlatConfig, FlatPrj, Marius, My Documents, Paste_1, '
  1029. 'Repetier, Roland_MDX_20, Users, Toolchange_Custom, Toolchange_Probe_MACH3, '
  1030. 'Toolchange_manual, Users, all, angle_x, angle_y, axis, auto, axisoffset, '
  1031. 'box, center_x, center_y, columns, combine, connect, contour, default, '
  1032. 'depthperpass, dia, diatol, dist, drilled_dias, drillz, dwell, dwelltime, '
  1033. 'feedrate_z, grbl_11, grbl_laser, gridoffsety, gridx, gridy, has_offset, '
  1034. 'holes, hpgl, iso_type, line_xyz, margin, marlin, method, milled_dias, '
  1035. 'minoffset, multidepth, name, offset, opt_type, order, outname, overlap, '
  1036. 'passes, postamble, pp, ppname_e, ppname_g, preamble, radius, ref, rest, '
  1037. 'rows, shellvar_, scale_factor, spacing_columns, spacing_rows, spindlespeed, '
  1038. 'toolchange_xy, use_threads, value, x, x0, x1, y, y0, y1, z_cut, z_move'
  1039. ,
  1040. })
  1041. # ############################################################
  1042. # ############### Load defaults from file ####################
  1043. # ############################################################
  1044. if user_defaults:
  1045. self.load_defaults(filename='current_defaults')
  1046. # #############################################################
  1047. # ############## APPLY APP LANGUAGE ###########################
  1048. # #############################################################
  1049. ret_val = fcTranslate.apply_language('strings')
  1050. if ret_val == "no language":
  1051. self.inform.emit('[ERROR] %s' %
  1052. _("Could not find the Language files. The App strings are missing."))
  1053. log.debug("Could not find the Language files. The App strings are missing.")
  1054. else:
  1055. # make the current language the current selection on the language combobox
  1056. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1057. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1058. # ##############################################################
  1059. # ################# CREATE UNIQUE SERIAL NUMBER ################
  1060. # ##############################################################
  1061. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1062. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1063. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  1064. self.save_defaults(silent=True, first_time=True)
  1065. self.propagate_defaults(silent=True)
  1066. self.restore_main_win_geom()
  1067. # def auto_save_defaults():
  1068. # try:
  1069. # self.save_defaults(silent=True)
  1070. # self.propagate_defaults(silent=True)
  1071. # finally:
  1072. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1073. # the following lines activates automatic defaults save
  1074. # if user_defaults:
  1075. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1076. # self.options_form = PreferencesUI()
  1077. self.options_form_fields = {
  1078. "units": self.ui.general_options_form.general_app_group.units_radio,
  1079. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  1080. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  1081. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  1082. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  1083. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  1084. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  1085. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  1086. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  1087. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  1088. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  1089. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  1090. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  1091. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  1092. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  1093. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  1094. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  1095. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  1096. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  1097. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  1098. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  1099. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  1100. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  1101. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  1102. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  1103. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  1104. "excellon_endz": self.ui.excellon_options_form.excellon_opt_group.eendz_entry,
  1105. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  1106. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  1107. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  1108. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  1109. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  1110. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  1111. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  1112. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  1113. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1114. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  1115. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  1116. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  1117. "excellon_spindledir": self.ui.excellon_options_form.excellon_adv_opt_group.spindledir_radio,
  1118. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  1119. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  1120. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  1121. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  1122. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  1123. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  1124. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  1125. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  1126. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  1127. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  1128. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  1129. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  1130. "geometry_endz": self.ui.geometry_options_form.geometry_opt_group.gendz_entry,
  1131. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  1132. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  1133. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  1134. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  1135. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1136. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  1137. "geometry_spindledir": self.ui.geometry_options_form.geometry_adv_opt_group.spindledir_radio,
  1138. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  1139. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  1140. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  1141. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  1142. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  1143. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  1144. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  1145. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  1146. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  1147. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  1148. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  1149. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  1150. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  1151. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  1152. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  1153. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  1154. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  1155. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  1156. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  1157. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  1158. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  1159. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  1160. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  1161. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  1162. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  1163. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  1164. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  1165. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  1166. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  1167. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  1168. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  1169. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  1170. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  1171. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  1172. }
  1173. for name in list(self.postprocessors.keys()):
  1174. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1175. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1176. self.options = LoudDict()
  1177. self.options.set_change_callback(self.on_options_dict_change)
  1178. self.options.update({
  1179. "units": "IN",
  1180. "global_gridx": 1.0,
  1181. "global_gridy": 1.0,
  1182. "global_snap_max": 0.05,
  1183. "global_background_timeout": 300000, # Default value is 5 minutes
  1184. "global_verbose_error_level": 0, # Shell verbosity:
  1185. # 0 = default(python trace only for unknown errors),
  1186. # 1 = show trace(show trace allways), 2 = (For the future).
  1187. "gerber_plot": True,
  1188. "gerber_solid": True,
  1189. "gerber_multicolored": False,
  1190. "gerber_isotooldia": 0.016,
  1191. "gerber_isopasses": 1,
  1192. "gerber_isooverlap": 0.15,
  1193. "gerber_combine_passes": True,
  1194. "gerber_noncoppermargin": 0.0,
  1195. "gerber_noncopperrounded": False,
  1196. "gerber_bboxmargin": 0.0,
  1197. "gerber_bboxrounded": False,
  1198. "excellon_plot": True,
  1199. "excellon_solid": False,
  1200. "excellon_format_upper_in": 2,
  1201. "excellon_format_lower_in": 4,
  1202. "excellon_format_upper_mm": 3,
  1203. "excellon_format_lower_mm": 3,
  1204. "excellon_units": 'INCH',
  1205. "excellon_optimization_type": 'B',
  1206. "excellon_search_time": 3,
  1207. "excellon_zeros": "L",
  1208. "excellon_drillz": -0.1,
  1209. "excellon_travelz": 0.1,
  1210. "excellon_feedrate": 3.0,
  1211. "excellon_feedrate_rapid": 3.0,
  1212. "excellon_spindlespeed": None,
  1213. "excellon_spindledir": 'CW',
  1214. "excellon_dwell": True,
  1215. "excellon_dwelltime": 1000,
  1216. "excellon_toolchange": False,
  1217. "excellon_toolchangez": 1.0,
  1218. "excellon_toolchangexy": "0.0, 0.0",
  1219. "excellon_tooldia": 0.016,
  1220. "excellon_ppname_e": 'default',
  1221. "excellon_f_plunge": False,
  1222. "excellon_startz": None,
  1223. "excellon_endz": 2.0,
  1224. "geometry_plot": True,
  1225. "geometry_segx": 0.0,
  1226. "geometry_segy": 0.0,
  1227. "geometry_cutz": -0.002,
  1228. "geometry_vtipdia": 0.1,
  1229. "geometry_vtipangle": 30,
  1230. "geometry_travelz": 0.1,
  1231. "geometry_feedrate": 3.0,
  1232. "geometry_feedrate_z": 3.0,
  1233. "geometry_feedrate_rapid": 3.0,
  1234. "geometry_spindlespeed": None,
  1235. "geometry_spindledir": 'CW',
  1236. "geometry_dwell": True,
  1237. "geometry_dwelltime": 1000,
  1238. "geometry_cnctooldia": 0.016,
  1239. "geometry_toolchange": False,
  1240. "geometry_toolchangez": 2.0,
  1241. "geometry_toolchangexy": "0.0, 0.0",
  1242. "geometry_startz": None,
  1243. "geometry_endz": 2.0,
  1244. "geometry_ppname_g": "default",
  1245. "geometry_f_plunge": False,
  1246. "geometry_depthperpass": 0.002,
  1247. "geometry_multidepth": False,
  1248. "geometry_extracut": False,
  1249. "cncjob_plot": True,
  1250. "cncjob_tooldia": 0.016,
  1251. "cncjob_prepend": "",
  1252. "cncjob_append": "",
  1253. "tools_ncctools": "1.0, 0.5",
  1254. "tools_nccoverlap": 0.4,
  1255. "tools_nccmargin": 1,
  1256. "tools_cutouttooldia": 0.07,
  1257. "tools_cutoutmargin": 0.1,
  1258. "tools_cutoutgapsize": 0.15,
  1259. "tools_gaps_ff": "8",
  1260. "tools_painttooldia": 0.07,
  1261. "tools_paintoverlap": 0.15,
  1262. "tools_paintmargin": 0.0,
  1263. "tools_paintmethod": "seed",
  1264. "tools_selectmethod": "single",
  1265. "tools_pathconnect": True,
  1266. "tools_paintcontour": True,
  1267. "tools_2sided_mirror_axis": "X",
  1268. "tools_2sided_axis_loc": 'point',
  1269. "tools_2sided_drilldia": 1,
  1270. "tools_film_type": 'neg',
  1271. "tools_film_boundary": 1,
  1272. "tools_film_scale": 0,
  1273. "tools_panelize_spacing_columns": 0,
  1274. "tools_panelize_spacing_rows": 0,
  1275. "tools_panelize_columns": 1,
  1276. "tools_panelize_rows": 1,
  1277. "tools_panelize_constrain": False,
  1278. "tools_panelize_constrainx": 0.0,
  1279. "tools_panelize_constrainy": 0.0
  1280. })
  1281. self.options.update(self.defaults) # Copy app defaults to project options
  1282. self.gen_form = None
  1283. self.ger_form = None
  1284. self.exc_form = None
  1285. self.geo_form = None
  1286. self.cnc_form = None
  1287. self.tools_form = None
  1288. self.fa_form = None
  1289. self.on_options_combo_change(0) # Will show the initial form
  1290. # ################################
  1291. # ### Initialize the color box's color in Preferences -> Global -> Color
  1292. # Init Plot Colors
  1293. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  1294. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  1295. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  1296. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  1297. int(self.defaults['global_plot_fill'][7:9], 16))
  1298. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  1299. int(self.defaults['global_plot_fill'][7:9], 16))
  1300. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  1301. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  1302. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  1303. # Init Left-Right Selection colors
  1304. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  1305. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  1306. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  1307. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1308. int(self.defaults['global_sel_fill'][7:9], 16))
  1309. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1310. int(self.defaults['global_sel_fill'][7:9], 16))
  1311. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1312. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1313. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  1314. # Init Right-Left Selection colors
  1315. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1316. self.defaults['global_alt_sel_fill'])
  1317. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1318. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  1319. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1320. int(self.defaults['global_sel_fill'][7:9], 16))
  1321. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1322. int(self.defaults['global_sel_fill'][7:9], 16))
  1323. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1324. self.defaults['global_alt_sel_line'])
  1325. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1326. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  1327. # Init Draw color and Selection Draw Color
  1328. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1329. self.defaults['global_draw_color'])
  1330. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1331. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1332. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1333. self.defaults['global_sel_draw_color'])
  1334. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1335. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1336. # Init Project Items color
  1337. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1338. self.defaults['global_proj_item_color'])
  1339. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1340. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1341. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1342. self.defaults['global_proj_item_dis_color'])
  1343. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1344. "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1345. # Init the Annotation CNC Job color
  1346. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  1347. self.defaults['cncjob_annotation_fontcolor'])
  1348. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  1349. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  1350. # Init the Tool Film color
  1351. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  1352. self.defaults['tools_film_color'])
  1353. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  1354. "background-color:%s" % str(self.defaults['tools_film_color'])[:7])
  1355. # ### End of Data ####
  1356. # ##############################################
  1357. # ######### SETUP OBJECT COLLECTION ############
  1358. # ##############################################
  1359. self.collection = ObjectCollection(self)
  1360. self.ui.project_tab_layout.addWidget(self.collection.view)
  1361. # ### Adjust tabs width ## ##
  1362. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1363. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1364. self.collection.view.setMinimumWidth(290)
  1365. self.log.debug("Finished creating Object Collection.")
  1366. # ###############################################
  1367. # ############# SETUP Plot Area #################
  1368. # ###############################################
  1369. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  1370. if self.defaults["global_graphic_engine"] == '3D':
  1371. self.is_legacy = False
  1372. else:
  1373. self.is_legacy = True
  1374. # Matplotlib axis
  1375. self.axes = None
  1376. if show_splash:
  1377. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1378. "Canvas initialization started."),
  1379. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1380. color=QtGui.QColor("gray"))
  1381. start_plot_time = time.time() # debug
  1382. self.plotcanvas = None
  1383. self.app_cursor = None
  1384. self.hover_shapes = None
  1385. self.on_plotcanvas_setup()
  1386. end_plot_time = time.time()
  1387. self.used_time = end_plot_time - start_plot_time
  1388. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1389. if show_splash:
  1390. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1391. "Canvas initialization started.\n"
  1392. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1393. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1394. color=QtGui.QColor("gray"))
  1395. self.ui.splitter.setStretchFactor(1, 2)
  1396. # #################################################################
  1397. # ####################### SYS TRAY ################################
  1398. # #################################################################
  1399. if self.defaults["global_systray_icon"]:
  1400. self.parent_w = QtWidgets.QWidget()
  1401. if self.cmd_line_headless == 1:
  1402. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1403. headless=True,
  1404. parent=self.parent_w)
  1405. else:
  1406. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1407. parent=self.parent_w)
  1408. # ###############################################
  1409. # ############# Worker SETUP ####################
  1410. # ###############################################
  1411. if self.defaults["global_worker_number"]:
  1412. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1413. else:
  1414. self.workers = WorkerStack(workers_number=2)
  1415. self.worker_task.connect(self.workers.add_task)
  1416. self.log.debug("Finished creating Workers crew.")
  1417. # ################################################
  1418. # ############### Activity Monitor ###############
  1419. # ################################################
  1420. if self.defaults["global_activity_icon"] == "Ball green":
  1421. icon = 'share/active_2_static.png'
  1422. movie = "share/active_2.gif"
  1423. elif self.defaults["global_activity_icon"] == "Ball black":
  1424. icon = 'share/active_static.png'
  1425. movie = "share/active.gif"
  1426. elif self.defaults["global_activity_icon"] == "Arrow green":
  1427. icon = 'share/active_3_static.png'
  1428. movie = "share/active_3.gif"
  1429. elif self.defaults["global_activity_icon"] == "Eclipse green":
  1430. icon = 'share/active_4_static.png'
  1431. movie = "share/active_4.gif"
  1432. else:
  1433. icon = 'share/active_static.png'
  1434. movie = "share/active.gif"
  1435. self.activity_view = FlatCAMActivityView(icon=icon, movie=movie)
  1436. self.ui.infobar.addWidget(self.activity_view)
  1437. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  1438. # ################################################
  1439. # ############### Signal handling ################
  1440. # ################################################
  1441. # ############# Custom signals ##################
  1442. # signal for displaying messages in status bar
  1443. self.inform.connect(self.info)
  1444. # signal to be called when the app is quiting
  1445. self.app_quit.connect(self.quit_application)
  1446. self.message.connect(self.message_dialog)
  1447. self.progress.connect(self.set_progress_bar)
  1448. # signals that are emitted when object state changes
  1449. self.object_created.connect(self.on_object_created)
  1450. self.object_changed.connect(self.on_object_changed)
  1451. self.object_plotted.connect(self.on_object_plotted)
  1452. self.plots_updated.connect(self.on_plots_updated)
  1453. # signals emitted when file state change
  1454. self.file_opened.connect(self.register_recent)
  1455. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1456. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1457. # ############# Standard signals ###################
  1458. # ### Menu
  1459. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1460. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1461. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1462. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1463. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1464. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1465. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1466. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1467. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1468. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1469. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1470. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1471. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1472. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1473. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1474. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1475. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1476. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1477. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1478. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1479. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1480. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1481. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1482. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1483. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1484. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1485. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1486. self.ui.menufile_exit.triggered.connect(self.final_save)
  1487. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1488. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1489. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1490. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1491. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1492. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1493. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1494. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1495. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1496. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1497. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1498. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1499. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1500. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1501. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1502. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1503. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1504. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1505. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1506. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1507. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1508. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1509. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1510. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1511. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1512. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1513. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1514. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1515. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1516. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1517. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1518. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1519. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1520. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1521. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1522. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1523. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1524. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1525. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1526. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1527. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1528. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1529. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1530. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1531. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1532. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1533. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1534. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1535. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1536. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1537. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1538. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1539. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1540. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1541. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1542. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1543. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1544. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1545. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1546. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1547. # ToolBar signals
  1548. self.connect_toolbar_signals()
  1549. # Notebook signals
  1550. # make the right click on the notebook tab connect to a function
  1551. self.ui.notebook.setupContextMenu()
  1552. self.ui.notebook.addContextMenu(
  1553. _("Detachable Tabs"), self.on_notebook_tab_rmb_click,
  1554. initial_checked=self.defaults["global_tabs_detachable"])
  1555. # activate initial state
  1556. self.on_notebook_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1557. # Context Menu
  1558. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1559. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1560. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1561. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1562. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1563. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1564. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1565. self.ui.clearplot.triggered.connect(self.clear_plots)
  1566. self.ui.replot.triggered.connect(self.plot_all)
  1567. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1568. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1569. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1570. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1571. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1572. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1573. # Preferences Plot Area TAB
  1574. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1575. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1576. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1577. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1578. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1579. # ##############################
  1580. # ### GUI PREFERENCES SIGNALS ##
  1581. # ##############################
  1582. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(
  1583. lambda: fcTranslate.restart_program(app=self)
  1584. )
  1585. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1586. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1587. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1588. )
  1589. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1590. lambda: self.on_toggle_units(no_pref=False))
  1591. # ###############################################################
  1592. # ################### GUI COLORS SIGNALS ########################
  1593. # ###############################################################
  1594. # Setting plot colors signals
  1595. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1596. self.on_pf_color_entry)
  1597. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1598. self.on_pf_color_button)
  1599. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1600. self.on_pf_color_spinner)
  1601. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1602. self.on_pf_color_slider)
  1603. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1604. self.on_pl_color_entry)
  1605. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1606. self.on_pl_color_button)
  1607. # Setting selection (left - right) colors signals
  1608. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1609. self.on_sf_color_entry)
  1610. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1611. self.on_sf_color_button)
  1612. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1613. self.on_sf_color_spinner)
  1614. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1615. self.on_sf_color_slider)
  1616. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1617. self.on_sl_color_entry)
  1618. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1619. self.on_sl_color_button)
  1620. # Setting selection (right - left) colors signals
  1621. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1622. self.on_alt_sf_color_entry)
  1623. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1624. self.on_alt_sf_color_button)
  1625. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1626. self.on_alt_sf_color_spinner)
  1627. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1628. self.on_alt_sf_color_slider)
  1629. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1630. self.on_alt_sl_color_entry)
  1631. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1632. self.on_alt_sl_color_button)
  1633. # Setting Editor Draw colors signals
  1634. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1635. self.on_draw_color_entry)
  1636. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1637. self.on_draw_color_button)
  1638. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1639. self.on_sel_draw_color_entry)
  1640. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1641. self.on_sel_draw_color_button)
  1642. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1643. self.on_proj_color_entry)
  1644. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1645. self.on_proj_color_button)
  1646. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1647. self.on_proj_color_dis_entry)
  1648. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1649. self.on_proj_color_dis_button)
  1650. # ########## workspace setting signals ###########
  1651. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1652. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1653. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1654. # ########## CNC Job related signals #############
  1655. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1656. self.on_cnc_custom_parameters)
  1657. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.editingFinished.connect(
  1658. self.on_annotation_fontcolor_entry)
  1659. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.clicked.connect(
  1660. self.on_annotation_fontcolor_button)
  1661. # ########## Tools related signals #############
  1662. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1663. self.on_film_color_entry)
  1664. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1665. self.on_film_color_button)
  1666. # ########## Modify G-CODE Plot Area TAB ###########
  1667. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1668. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1669. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1670. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1671. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1672. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1673. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1674. self.ui.button_copy_all.clicked.connect(self.handleCopyAll)
  1675. # portability changed signal
  1676. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1677. # Object list
  1678. self.collection.view.activated.connect(self.on_row_activated)
  1679. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1680. self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1681. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1682. # Export Excellon parameters.
  1683. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1684. self.on_update_exc_export
  1685. )
  1686. # call it once to make sure it is updated at startup
  1687. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1688. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1689. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1690. self.on_excellon_defaults_button)
  1691. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1692. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1693. self.on_excellon_options_button)
  1694. # when there are arguments at application startup this get launched
  1695. self.args_at_startup[list].connect(self.on_startup_args)
  1696. # ##############################################################
  1697. # ############### FILE ASSOCIATIONS SIGNALS ####################
  1698. # ##############################################################
  1699. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1700. lambda: self.restore_extensions(ext_type='excellon'))
  1701. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1702. lambda: self.restore_extensions(ext_type='gcode'))
  1703. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1704. lambda: self.restore_extensions(ext_type='gerber'))
  1705. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1706. lambda: self.delete_all_extensions(ext_type='excellon'))
  1707. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1708. lambda: self.delete_all_extensions(ext_type='gcode'))
  1709. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1710. lambda: self.delete_all_extensions(ext_type='gerber'))
  1711. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1712. lambda: self.add_extension(ext_type='excellon'))
  1713. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1714. lambda: self.add_extension(ext_type='gcode'))
  1715. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1716. lambda: self.add_extension(ext_type='gerber'))
  1717. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1718. lambda: self.del_extension(ext_type='excellon'))
  1719. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1720. lambda: self.del_extension(ext_type='gcode'))
  1721. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1722. lambda: self.del_extension(ext_type='gerber'))
  1723. # connect the 'Apply' buttons from the Preferences/File Associations
  1724. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1725. lambda: self.on_register_files(obj_type='excellon'))
  1726. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1727. lambda: self.on_register_files(obj_type='gcode'))
  1728. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1729. lambda: self.on_register_files(obj_type='gerber'))
  1730. # ##############################################################
  1731. # ###################### KEYWORDS SIGNALS ######################
  1732. # ##############################################################
  1733. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1734. lambda: self.restore_extensions(ext_type='keyword'))
  1735. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1736. lambda: self.delete_all_extensions(ext_type='keyword'))
  1737. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1738. lambda: self.add_extension(ext_type='keyword'))
  1739. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1740. lambda: self.del_extension(ext_type='keyword'))
  1741. # splash screen button signal
  1742. self.ui.general_defaults_form.general_gui_set_group.splash_cb.stateChanged.connect(self.on_splash_changed)
  1743. # connect the abort_all_tasks related slots to the related signals
  1744. self.proc_container.idle_flag.connect(self.app_is_idle)
  1745. # #####################################################################################
  1746. # ########### FINISHED CONNECTING SIGNALS #############################################
  1747. # #####################################################################################
  1748. self.log.debug("Finished connecting Signals.")
  1749. # #####################################################################################
  1750. # ########################## Other setups #############################################
  1751. # #####################################################################################
  1752. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  1753. # depending on from where those tools are called different actions can be done
  1754. self.call_source = 'app'
  1755. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1756. self.tool_tab_locked = False
  1757. # decide if to show or hide the Notebook side of the screen at startup
  1758. if self.defaults["global_project_at_startup"] is True:
  1759. self.ui.splitter.setSizes([1, 1])
  1760. else:
  1761. self.ui.splitter.setSizes([0, 1])
  1762. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1763. self.setup_obj_classes()
  1764. self.setup_recent_items()
  1765. self.setup_component_editor()
  1766. # this does not work in Legacy Mode
  1767. if self.is_legacy is True:
  1768. self.ui.general_defaults_form.general_gui_group.workspace_cb.setDisabled(True)
  1769. self.ui.general_defaults_form.general_gui_group.workspace_type_lbl.setDisabled(True)
  1770. self.ui.general_defaults_form.general_gui_group.wk_cb.setDisabled(True)
  1771. # #####################################################################################
  1772. # ######################### Auto-complete KEYWORDS ####################################
  1773. # #####################################################################################
  1774. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1775. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1776. 'delete', 'drillcncjob', 'export_gcode', 'export_svg', 'ext', 'exteriors', 'follow',
  1777. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1778. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1779. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1780. 'mirror', 'ncc',
  1781. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1782. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'origin',
  1783. 'paint', 'pan', 'panel', 'panelize', 'plot_all', 'plot_objects', 'quit_flatcam',
  1784. 'save', 'save_project',
  1785. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_sys',
  1786. 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1787. 'version', 'write_gcode'
  1788. ]
  1789. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'Marius', 'My Documents', 'Paste_1',
  1790. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  1791. 'Toolchange_manual', 'Users', 'all', 'angle_x', 'angle_y', 'auto', 'axis', 'axisoffset',
  1792. 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect', 'contour', 'default',
  1793. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dwell',
  1794. 'dwelltime', 'feedrate_z', 'grbl_11', 'grbl_laser', 'gridoffsety', 'gridx', 'gridy',
  1795. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  1796. 'milled_dias', 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order',
  1797. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  1798. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  1799. 'spacing_columns',
  1800. 'spacing_rows', 'spindlespeed', 'toolchange_xy', 'use_threads', 'value', 'x',
  1801. 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1802. ]
  1803. self.tcl_keywords = [
  1804. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1805. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1806. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1807. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1808. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1809. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1810. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1811. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1812. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1813. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1814. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1815. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1816. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1817. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1818. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1819. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1820. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1821. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1822. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1823. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1824. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1825. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1826. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1827. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1828. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1829. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1830. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1831. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1832. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1833. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1834. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1835. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1836. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1837. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1838. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1839. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1840. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1841. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1842. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1843. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1844. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1845. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1846. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1847. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1848. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1849. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1850. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1851. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1852. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1853. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1854. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1855. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1856. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1857. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1858. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1859. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1860. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1861. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1862. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1863. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1864. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1865. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1866. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1867. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1868. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1869. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1870. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1871. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1872. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1873. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1874. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1875. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1876. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1877. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1878. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1879. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1880. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1881. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1882. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1883. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1884. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1885. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1886. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1887. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1888. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1889. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1890. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1891. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1892. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1893. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1894. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1895. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1896. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1897. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1898. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1899. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1900. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1901. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1902. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1903. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1904. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1905. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1906. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1907. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1908. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1909. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1910. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1911. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1912. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1913. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1914. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1915. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1916. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1917. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1918. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1919. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1920. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1921. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1922. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1923. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1924. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1925. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1926. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1927. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1928. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1929. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1930. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1931. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1932. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1933. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1934. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1935. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1936. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1937. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1938. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1939. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1940. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1941. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1942. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1943. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1944. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1945. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1946. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1947. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1948. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1949. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1950. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1951. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1952. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1953. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1954. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1955. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1956. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1957. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1958. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1959. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1960. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1961. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1962. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1963. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1964. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1965. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1966. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1967. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1968. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1969. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1970. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1971. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1972. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1973. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1974. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1975. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1976. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1977. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1978. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1979. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1980. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1981. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1982. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1983. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1984. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1985. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1986. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1987. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1988. ]
  1989. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1990. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1991. # ####################################################################################
  1992. # ####################### Shell SETUP ################################################
  1993. # ####################################################################################
  1994. self.shell = FCShell(self, version=self.version)
  1995. self.shell._edit.set_model_data(self.myKeywords)
  1996. self.ui.code_editor.set_model_data(self.myKeywords)
  1997. self.shell.setWindowIcon(self.ui.app_icon)
  1998. self.shell.setWindowTitle("FlatCAM Shell")
  1999. self.shell.resize(*self.defaults["global_shell_shape"])
  2000. self.shell.append_output("FlatCAM %s - " % self.version)
  2001. self.shell.append_output(_("Open Source Software - Type help to get started\n\n"))
  2002. self.init_tcl()
  2003. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  2004. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  2005. self.ui.shell_dock.setWidget(self.shell)
  2006. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  2007. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  2008. QtWidgets.QDockWidget.DockWidgetFloatable |
  2009. QtWidgets.QDockWidget.DockWidgetClosable)
  2010. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  2011. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  2012. if self.defaults["global_shell_at_startup"]:
  2013. self.ui.shell_dock.show()
  2014. else:
  2015. self.ui.shell_dock.hide()
  2016. # ##################################################################################
  2017. # ###################### Tools and Plugins #########################################
  2018. # ##################################################################################
  2019. self.dblsidedtool = None
  2020. self.measurement_tool = None
  2021. self.panelize_tool = None
  2022. self.film_tool = None
  2023. self.paste_tool = None
  2024. self.calculator_tool = None
  2025. self.sub_tool = None
  2026. self.move_tool = None
  2027. self.cutout_tool = None
  2028. self.ncclear_tool = None
  2029. self.paint_tool = None
  2030. self.transform_tool = None
  2031. self.properties_tool = None
  2032. self.pdf_tool = None
  2033. self.image_tool = None
  2034. self.pcb_wizard_tool = None
  2035. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  2036. self.install_tools()
  2037. # ### System Font Parsing ###
  2038. # self.f_parse = ParseFont(self)
  2039. # self.parse_system_fonts()
  2040. # #####################################################################################
  2041. # ######################## Check for updates ##########################################
  2042. # #####################################################################################
  2043. # Separate thread (Not worker)
  2044. # Check for updates on startup but only if the user consent and the app is not in Beta version
  2045. if (self.beta is False or self.beta is None) and \
  2046. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  2047. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  2048. self.thr2 = QtCore.QThread()
  2049. self.worker_task.emit({'fcn': self.version_check,
  2050. 'params': []})
  2051. self.thr2.start(QtCore.QThread.LowPriority)
  2052. # #####################################################################################
  2053. # ######################### Register files with FlatCAM; #############################
  2054. # ######################### It works only for Windows for now ########################
  2055. # #####################################################################################
  2056. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  2057. self.on_register_files()
  2058. # #####################################################################################
  2059. # ###################### Variables for global usage ###################################
  2060. # #####################################################################################
  2061. # coordinates for relative position display
  2062. self.rel_point1 = (0, 0)
  2063. self.rel_point2 = (0, 0)
  2064. # variable to store coordinates
  2065. self.pos = (0, 0)
  2066. self.pos_jump = (0, 0)
  2067. # variable to store mouse coordinates
  2068. self.mouse = [0, 0]
  2069. # decide if we have a double click or single click
  2070. self.doubleclick = False
  2071. # variable to store if a command is active (then the var is not None) and which one it is
  2072. self.command_active = None
  2073. # variable to store the status of moving selection action
  2074. # None value means that it's not an selection action
  2075. # True value = a selection from left to right
  2076. # False value = a selection from right to left
  2077. self.selection_type = None
  2078. # List to store the objects that are currently loaded in FlatCAM
  2079. # This list is updated on each object creation or object delete
  2080. self.all_objects_list = list()
  2081. # List to store the objects that are selected
  2082. self.sel_objects_list = list()
  2083. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  2084. self.key_modifiers = None
  2085. # Variable to hold the status of the axis
  2086. self.toggle_axis = True
  2087. # Variable to store the status of the fullscreen event
  2088. self.toggle_fscreen = False
  2089. # Variable to store the status of the code editor
  2090. self.toggle_codeeditor = False
  2091. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  2092. self.click_noproject = False
  2093. self.cursor = None
  2094. # Variable to store the GCODE that was edited
  2095. self.gcode_edited = ""
  2096. # reference for the self.ui.code_editor
  2097. self.reference_code_editor = None
  2098. self.script_code = ''
  2099. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  2100. self.preferences_changed_flag = False
  2101. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  2102. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  2103. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'pho',
  2104. 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top', 'tsm']
  2105. self.exc_list = ['drd', 'drl', 'exc', 'ncd', 'tap', 'txt', 'xln']
  2106. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  2107. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ncp', 'out', 'plt', 'ply', 'rol', 'sbp',
  2108. 'tap', 'xpi']
  2109. self.svg_list = ['svg']
  2110. self.dxf_list = ['dxf']
  2111. self.pdf_list = ['pdf']
  2112. self.prj_list = ['flatprj']
  2113. self.conf_list = ['flatconfig']
  2114. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  2115. # flag for polygons not cleared
  2116. self.poly_not_cleared = False
  2117. # VisPy visuals
  2118. self.isHovering = False
  2119. self.notHovering = True
  2120. # Window geometry
  2121. self.x_pos = None
  2122. self.y_pos = None
  2123. self.width = None
  2124. self.height = None
  2125. # Event signals disconnect id holders
  2126. self.mp = None
  2127. self.mm = None
  2128. self.mr = None
  2129. self.mp_zc = None
  2130. # when True, the app has to return from any thread
  2131. self.abort_flag = False
  2132. # set the value used in the Windows Title
  2133. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  2134. # ###############################################################################
  2135. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  2136. # ############# It's done only once after install ###############
  2137. # ###############################################################################
  2138. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  2139. fac_def_from_file = factory_file.read()
  2140. factory_defaults = json.loads(fac_def_from_file)
  2141. # if the file contain an empty dictionary then save the factory defaults into the file
  2142. if not factory_defaults:
  2143. self.save_factory_defaults(silent=False)
  2144. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  2145. initial_lay = 'compact'
  2146. self.on_layout(lay=initial_lay)
  2147. # Set the combobox in Preferences to the current layout
  2148. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  2149. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  2150. factory_file.close()
  2151. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  2152. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  2153. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  2154. # after the first run, this object should be False
  2155. self.defaults["first_run"] = False
  2156. # ###############################################################################
  2157. # ################# ADDING FlatCAM EDITORS section ##############################
  2158. # ###############################################################################
  2159. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2160. # at the first launch of the App , the editors will not be functional.
  2161. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  2162. self.exc_editor = FlatCAMExcEditor(self)
  2163. self.grb_editor = FlatCAMGrbEditor(self)
  2164. self.log.debug("Finished adding FlatCAM Editor's.")
  2165. self.set_ui_title(name=_("New Project - Not saved"))
  2166. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2167. current_platform = platform.architecture()[0]
  2168. if current_platform != '64bit':
  2169. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2170. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2171. # ###############################################################################
  2172. # ####################### Finished the CONSTRUCTOR ##############################
  2173. # ###############################################################################
  2174. App.log.debug("END of constructor. Releasing control.")
  2175. # #####################################################################################
  2176. # ########################## SHOW GUI #################################################
  2177. # #####################################################################################
  2178. # if the app is not started as headless, show it
  2179. if self.cmd_line_headless != 1:
  2180. # finish the splash
  2181. self.splash.finish(self.ui)
  2182. settings = QSettings("Open Source", "FlatCAM")
  2183. if settings.contains("maximized_gui"):
  2184. maximized_ui = settings.value('maximized_gui', type=bool)
  2185. if maximized_ui is True:
  2186. self.ui.showMaximized()
  2187. else:
  2188. self.ui.show()
  2189. else:
  2190. self.ui.show()
  2191. if self.defaults["global_systray_icon"]:
  2192. self.trayIcon.show()
  2193. else:
  2194. log.warning("******************* RUNNING HEADLESS *******************")
  2195. # #####################################################################################
  2196. # ########################## START-UP ARGUMENTS #######################################
  2197. # #####################################################################################
  2198. # test if the program was started with a script as parameter
  2199. if self.cmd_line_shellvar:
  2200. try:
  2201. cnt = 0
  2202. command_tcl = 0
  2203. for i in self.cmd_line_shellvar.split(','):
  2204. if i is not None:
  2205. try:
  2206. command_tcl = eval(i)
  2207. except:
  2208. command_tcl = i
  2209. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  2210. cnt += 1
  2211. # if there are Windows paths then replace the path separator with a Unix like one
  2212. if sys.platform == 'win32':
  2213. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  2214. self.shell._sysShell.exec_command(command_tcl_formatted, no_echo=True)
  2215. except Exception as ext:
  2216. print("ERROR: ", ext)
  2217. sys.exit(2)
  2218. if self.cmd_line_shellfile:
  2219. try:
  2220. if self.ui.shell_dock.isHidden():
  2221. self.ui.shell_dock.show()
  2222. with open(self.cmd_line_shellfile, "r") as myfile:
  2223. if show_splash:
  2224. self.splash.showMessage('%s: %ssec\n%s' % (
  2225. _("Canvas initialization started.\n"
  2226. "Canvas initialization finished in"), '%.2f' % self.used_time,
  2227. _("Executing Tcl Script ...")),
  2228. alignment=Qt.AlignBottom | Qt.AlignLeft,
  2229. color=QtGui.QColor("gray"))
  2230. cmd_line_shellfile_text = myfile.read()
  2231. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  2232. except Exception as ext:
  2233. print("ERROR: ", ext)
  2234. sys.exit(2)
  2235. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2236. # the path/file_name must be enclosed in quotes if it contain spaces
  2237. if App.args:
  2238. self.args_at_startup.emit(App.args)
  2239. @staticmethod
  2240. def copy_and_overwrite(from_path, to_path):
  2241. """
  2242. From here:
  2243. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2244. :param from_path: source path
  2245. :param to_path: destination path
  2246. :return: None
  2247. """
  2248. if os.path.exists(to_path):
  2249. shutil.rmtree(to_path)
  2250. try:
  2251. shutil.copytree(from_path, to_path)
  2252. except FileNotFoundError:
  2253. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2254. shutil.copytree(from_new_path, to_path)
  2255. def on_startup_args(self, args, silent=False):
  2256. """
  2257. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2258. :param args: a list containing the application args at startup
  2259. :return: None
  2260. """
  2261. if args is not None:
  2262. args_to_process = args
  2263. else:
  2264. args_to_process = App.args
  2265. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2266. for argument in args_to_process:
  2267. if '.FlatPrj'.lower() in argument.lower():
  2268. try:
  2269. project_name = str(argument)
  2270. if project_name == "":
  2271. if silent is False:
  2272. self.inform.emit(_("Open cancelled."))
  2273. else:
  2274. # self.open_project(project_name)
  2275. run_from_arg = True
  2276. # self.worker_task.emit({'fcn': self.open_project,
  2277. # 'params': [project_name, run_from_arg]})
  2278. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2279. except Exception as e:
  2280. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2281. elif '.FlatConfig'.lower() in argument.lower():
  2282. try:
  2283. file_name = str(argument)
  2284. if file_name == "":
  2285. if silent is False:
  2286. self.inform.emit(_("Open Config file failed."))
  2287. else:
  2288. run_from_arg = True
  2289. # self.worker_task.emit({'fcn': self.open_config_file,
  2290. # 'params': [file_name, run_from_arg]})
  2291. self.open_config_file(file_name, run_from_arg=run_from_arg)
  2292. except Exception as e:
  2293. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2294. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  2295. try:
  2296. file_name = str(argument)
  2297. if file_name == "":
  2298. if silent is False:
  2299. self.inform.emit(_("Open Script file failed."))
  2300. else:
  2301. if silent is False:
  2302. self.on_fileopenscript(name=file_name)
  2303. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  2304. self.on_filerunscript(name=file_name)
  2305. except Exception as e:
  2306. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2307. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  2308. log.debug("App.on_startup_args() --> Quit event.")
  2309. sys.exit()
  2310. elif 'save'.lower() in argument.lower():
  2311. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  2312. self.save_defaults()
  2313. else:
  2314. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2315. proc_arg = argument.lower()
  2316. for ext in exc_list:
  2317. proc_ext = ext.replace(' ', '')
  2318. proc_ext = '.%s' % proc_ext
  2319. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2320. file_name = str(argument)
  2321. if file_name == "":
  2322. if silent is False:
  2323. self.inform.emit(_("Open Excellon file failed."))
  2324. else:
  2325. self.on_fileopenexcellon(name=file_name)
  2326. return
  2327. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2328. for ext in gco_list:
  2329. proc_ext = ext.replace(' ', '')
  2330. proc_ext = '.%s' % proc_ext
  2331. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2332. print(proc_ext, proc_arg)
  2333. file_name = str(argument)
  2334. if file_name == "":
  2335. if silent is False:
  2336. self.inform.emit(_("Open GCode file failed."))
  2337. else:
  2338. self.on_fileopengcode(name=file_name)
  2339. return
  2340. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2341. for ext in grb_list:
  2342. proc_ext = ext.replace(' ', '')
  2343. proc_ext = '.%s' % proc_ext
  2344. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2345. file_name = str(argument)
  2346. if file_name == "":
  2347. if silent is False:
  2348. self.inform.emit(_("Open Gerber file failed."))
  2349. else:
  2350. self.on_fileopengerber(name=file_name)
  2351. return
  2352. # if it reached here without already returning then the app was registered with a file that it does not
  2353. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  2354. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  2355. for arg in args_to_process:
  2356. if 'FlatCAM.exe' in arg:
  2357. continue
  2358. else:
  2359. sys.exit(2)
  2360. def set_ui_title(self, name):
  2361. """
  2362. Sets the title of the main window.
  2363. :param name: String that store the project path and project name
  2364. :return: None
  2365. """
  2366. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  2367. (self.version,
  2368. ('BETA' if self.beta else ''),
  2369. platform.architecture()[0],
  2370. self.engine,
  2371. name)
  2372. )
  2373. def defaults_read_form(self):
  2374. """
  2375. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2376. :return: None
  2377. """
  2378. for option in self.defaults_form_fields:
  2379. try:
  2380. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2381. except Exception as e:
  2382. log.debug("App.defaults_read_form() --> %s" % str(e))
  2383. def defaults_write_form(self, factor=None, fl_units=None):
  2384. """
  2385. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2386. self.defaults dictionary.
  2387. :param factor: will apply a factor to the values that written in the GUI elements
  2388. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2389. :return: None
  2390. """
  2391. for option in self.defaults:
  2392. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2393. # try:
  2394. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2395. # except KeyError:
  2396. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2397. # # TODO: Rethink this?
  2398. # pass
  2399. def defaults_write_form_field(self, field, factor=None, units=None):
  2400. """
  2401. Basically it is the worker in the self.defaults_write_form()
  2402. :param field: the GUI element in Preferences GUI to be updated
  2403. :param factor: factor to be applied to the field parameter
  2404. :param units: current FLatCAM measuring units
  2405. :return: None, it updates GUI elements
  2406. """
  2407. try:
  2408. if factor is None:
  2409. if units is None:
  2410. self.defaults_form_fields[field].set_value(self.defaults[field])
  2411. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2412. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=6)
  2413. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2414. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=4)
  2415. else:
  2416. if units is None:
  2417. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2418. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2419. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=6)
  2420. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2421. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=4)
  2422. except KeyError:
  2423. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2424. # TODO: Rethink this?
  2425. pass
  2426. except AttributeError:
  2427. log.debug(field)
  2428. def clear_pool(self):
  2429. """
  2430. Clear the multiprocessing pool and calls garbage collector.
  2431. :return: None
  2432. """
  2433. self.pool.close()
  2434. self.pool = Pool()
  2435. self.pool_recreated.emit(self.pool)
  2436. gc.collect()
  2437. def install_tools(self):
  2438. """
  2439. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2440. Instantiation of the Tools classes.
  2441. The order that the tools are installed is important as they can depend on each other install position.
  2442. :return: None
  2443. """
  2444. self.dblsidedtool = DblSidedTool(self)
  2445. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2446. self.measurement_tool = Measurement(self)
  2447. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  2448. self.panelize_tool = Panelize(self)
  2449. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  2450. self.film_tool = Film(self)
  2451. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2452. self.paste_tool = SolderPaste(self)
  2453. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2454. self.calculator_tool = ToolCalculator(self)
  2455. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'), separator=True)
  2456. self.sub_tool = ToolSub(self)
  2457. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2458. self.move_tool = ToolMove(self)
  2459. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2460. before=self.ui.menueditorigin)
  2461. self.cutout_tool = CutOut(self)
  2462. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2463. before=self.measurement_tool.menuAction)
  2464. self.ncclear_tool = NonCopperClear(self)
  2465. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2466. before=self.measurement_tool.menuAction, separator=True)
  2467. self.paint_tool = ToolPaint(self)
  2468. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2469. before=self.measurement_tool.menuAction, separator=True)
  2470. self.transform_tool = ToolTransform(self)
  2471. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2472. self.properties_tool = Properties(self)
  2473. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2474. self.pdf_tool = ToolPDF(self)
  2475. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2476. separator=True)
  2477. self.image_tool = ToolImage(self)
  2478. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2479. separator=True)
  2480. self.pcb_wizard_tool = PcbWizard(self)
  2481. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2482. self.log.debug("Tools are installed.")
  2483. def remove_tools(self):
  2484. """
  2485. Will remove all the actions in the Tool menu.
  2486. :return: None
  2487. """
  2488. for act in self.ui.menutool.actions():
  2489. self.ui.menutool.removeAction(act)
  2490. def init_tools(self):
  2491. """
  2492. Initialize the Tool tab in the notebook side of the central widget.
  2493. Remove the actions in the Tools menu.
  2494. Instantiate again the FlatCAM tools (plugins).
  2495. All this is required when changing the layout: standard, compact etc.
  2496. :return: None
  2497. """
  2498. log.debug("init_tools()")
  2499. # delete the data currently in the Tools Tab and the Tab itself
  2500. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2501. if widget is not None:
  2502. widget.deleteLater()
  2503. self.ui.notebook.removeTab(2)
  2504. # rebuild the Tools Tab
  2505. self.ui.tool_tab = QtWidgets.QWidget()
  2506. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2507. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2508. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2509. self.ui.tool_scroll_area = VerticalScrollArea()
  2510. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2511. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2512. # first remove all of them
  2513. self.remove_tools()
  2514. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2515. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2516. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2517. # third install all of them
  2518. self.install_tools()
  2519. self.log.debug("Tools are initialized.")
  2520. # def parse_system_fonts(self):
  2521. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2522. # 'params': []})
  2523. def connect_toolbar_signals(self):
  2524. """
  2525. Reconnect the signals to the actions in the toolbar.
  2526. This has to be done each time after the FlatCAM tools are removed/installed.
  2527. :return: None
  2528. """
  2529. # Toolbar
  2530. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2531. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2532. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2533. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2534. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2535. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2536. self.ui.replot_btn.triggered.connect(self.plot_all)
  2537. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2538. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2539. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2540. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2541. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2542. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2543. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2544. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2545. self.ui.delete_btn.triggered.connect(self.on_delete)
  2546. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2547. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2548. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2549. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2550. # Tools Toolbar Signals
  2551. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2552. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2553. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2554. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2555. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2556. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2557. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2558. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2559. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2560. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2561. def object2editor(self):
  2562. """
  2563. Send the current Geometry or Excellon object (if any) into the it's editor.
  2564. :return: None
  2565. """
  2566. self.report_usage("object2editor()")
  2567. edited_object = self.collection.get_active()
  2568. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2569. isinstance(edited_object, FlatCAMExcellon):
  2570. pass
  2571. else:
  2572. self.inform.emit('[WARNING_NOTCL] %s' %
  2573. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2574. return
  2575. if isinstance(edited_object, FlatCAMGeometry):
  2576. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2577. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2578. # we set the notebook to hidden
  2579. self.ui.splitter.setSizes([0, 1])
  2580. if edited_object.multigeo is True:
  2581. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  2582. if len(edited_tools) > 1:
  2583. self.inform.emit('[WARNING_NOTCL] %s' %
  2584. _("Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  2585. "is not possible.\n"
  2586. "Edit only one geometry at a time."))
  2587. # determine the tool dia of the selected tool
  2588. selected_tooldia = float(edited_object.ui.geo_tools_table.item((edited_tools[0] - 1), 1).text())
  2589. # now find the key in the edited_object.tools that has this tooldia
  2590. multi_tool = 1
  2591. for tool in edited_object.tools:
  2592. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2593. multi_tool = tool
  2594. break
  2595. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2596. else:
  2597. self.geo_editor.edit_fcgeometry(edited_object)
  2598. # set call source to the Editor we go into
  2599. self.call_source = 'geo_editor'
  2600. elif isinstance(edited_object, FlatCAMExcellon):
  2601. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2602. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2603. if self.ui.splitter.sizes()[0] == 0:
  2604. self.ui.splitter.setSizes([1, 1])
  2605. self.exc_editor.edit_fcexcellon(edited_object)
  2606. # set call source to the Editor we go into
  2607. self.call_source = 'exc_editor'
  2608. elif isinstance(edited_object, FlatCAMGerber):
  2609. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2610. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2611. if self.ui.splitter.sizes()[0] == 0:
  2612. self.ui.splitter.setSizes([1, 1])
  2613. self.grb_editor.edit_fcgerber(edited_object)
  2614. # set call source to the Editor we go into
  2615. self.call_source = 'grb_editor'
  2616. # make sure that we can't select another object while in Editor Mode:
  2617. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2618. self.ui.project_frame.setDisabled(True)
  2619. # delete any selection shape that might be active as they are not relevant in Editor
  2620. self.delete_selection_shape()
  2621. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2622. self.ui.plot_tab_area.protectTab(0)
  2623. self.inform.emit('[WARNING_NOTCL] %s' %
  2624. _("Editor is activated ..."))
  2625. self.should_we_save = True
  2626. def editor2object(self, cleanup=None):
  2627. """
  2628. Transfers the Geometry or Excellon from it's editor to the current object.
  2629. :return: None
  2630. """
  2631. self.report_usage("editor2object()")
  2632. # do not update a geometry or excellon object unless it comes out of an editor
  2633. if self.call_source != 'app':
  2634. edited_obj = self.collection.get_active()
  2635. if cleanup is None:
  2636. msgbox = QtWidgets.QMessageBox()
  2637. msgbox.setText(_("Do you want to save the edited object?"))
  2638. msgbox.setWindowTitle(_("Close Editor"))
  2639. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2640. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2641. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2642. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2643. msgbox.setDefaultButton(bt_yes)
  2644. msgbox.exec_()
  2645. response = msgbox.clickedButton()
  2646. if response == bt_yes:
  2647. # clean the Tools Tab
  2648. self.ui.tool_scroll_area.takeWidget()
  2649. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2650. self.ui.notebook.setTabText(2, "Tool")
  2651. if isinstance(edited_obj, FlatCAMGeometry):
  2652. obj_type = "Geometry"
  2653. if cleanup is None:
  2654. self.geo_editor.update_fcgeometry(edited_obj)
  2655. self.geo_editor.update_options(edited_obj)
  2656. self.geo_editor.deactivate()
  2657. # update the geo object options so it is including the bounding box values
  2658. try:
  2659. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2660. edited_obj.options['xmin'] = xmin
  2661. edited_obj.options['ymin'] = ymin
  2662. edited_obj.options['xmax'] = xmax
  2663. edited_obj.options['ymax'] = ymax
  2664. except AttributeError as e:
  2665. self.inform.emit('[WARNING] %s' %
  2666. _("Object empty after edit."))
  2667. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2668. elif isinstance(edited_obj, FlatCAMGerber):
  2669. obj_type = "Gerber"
  2670. if cleanup is None:
  2671. self.grb_editor.update_fcgerber()
  2672. self.grb_editor.update_options(edited_obj)
  2673. self.grb_editor.deactivate_grb_editor()
  2674. # delete the old object (the source object) if it was an empty one
  2675. if len(edited_obj.solid_geometry) == 0:
  2676. old_name = edited_obj.options['name']
  2677. self.collection.set_active(old_name)
  2678. self.collection.delete_active()
  2679. # restore GUI to the Selected TAB
  2680. # Remove anything else in the GUI
  2681. self.ui.selected_scroll_area.takeWidget()
  2682. # Switch notebook to Selected page
  2683. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2684. elif isinstance(edited_obj, FlatCAMExcellon):
  2685. obj_type = "Excellon"
  2686. if cleanup is None:
  2687. self.exc_editor.update_fcexcellon(edited_obj)
  2688. self.exc_editor.update_options(edited_obj)
  2689. self.exc_editor.deactivate()
  2690. # delete the old object (the source object) if it was an empty one
  2691. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  2692. old_name = edited_obj.options['name']
  2693. self.collection.set_active(old_name)
  2694. self.collection.delete_active()
  2695. # restore GUI to the Selected TAB
  2696. # Remove anything else in the GUI
  2697. self.ui.tool_scroll_area.takeWidget()
  2698. # Switch notebook to Selected page
  2699. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2700. else:
  2701. self.inform.emit('[WARNING_NOTCL] %s' %
  2702. _("Select a Gerber, Geometry or Excellon Object to update."))
  2703. return
  2704. self.inform.emit('[selected] %s %s' %
  2705. (obj_type, _("is updated, returning to App...")))
  2706. elif response == bt_no:
  2707. # clean the Tools Tab
  2708. self.ui.tool_scroll_area.takeWidget()
  2709. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2710. self.ui.notebook.setTabText(2, "Tool")
  2711. if isinstance(edited_obj, FlatCAMGeometry):
  2712. self.geo_editor.deactivate()
  2713. elif isinstance(edited_obj, FlatCAMGerber):
  2714. self.grb_editor.deactivate_grb_editor()
  2715. elif isinstance(edited_obj, FlatCAMExcellon):
  2716. self.exc_editor.deactivate()
  2717. # set focus on the project tab
  2718. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  2719. else:
  2720. self.inform.emit('[WARNING_NOTCL] %s' %
  2721. _("Select a Gerber, Geometry or Excellon Object to update."))
  2722. return
  2723. elif response == bt_cancel:
  2724. return
  2725. else:
  2726. if isinstance(edited_obj, FlatCAMGeometry):
  2727. self.geo_editor.deactivate()
  2728. elif isinstance(edited_obj, FlatCAMGerber):
  2729. self.grb_editor.deactivate_grb_editor()
  2730. elif isinstance(edited_obj, FlatCAMExcellon):
  2731. self.exc_editor.deactivate()
  2732. else:
  2733. self.inform.emit('[WARNING_NOTCL] %s' %
  2734. _("Select a Gerber, Geometry or Excellon Object to update."))
  2735. return
  2736. # if notebook is hidden we show it
  2737. if self.ui.splitter.sizes()[0] == 0:
  2738. self.ui.splitter.setSizes([1, 1])
  2739. # restore the call_source to app
  2740. self.call_source = 'app'
  2741. edited_obj.plot()
  2742. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2743. self.ui.plot_tab_area.protectTab(0)
  2744. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2745. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2746. self.ui.project_frame.setDisabled(False)
  2747. def get_last_folder(self):
  2748. """
  2749. Get the folder path from where the last file was opened.
  2750. :return: String, last opened folder path
  2751. """
  2752. return self.defaults["global_last_folder"]
  2753. def get_last_save_folder(self):
  2754. """
  2755. Get the folder path from where the last file was saved.
  2756. :return: String, last saved folder path
  2757. """
  2758. loc = self.defaults["global_last_save_folder"]
  2759. if loc is None:
  2760. loc = self.defaults["global_last_folder"]
  2761. if loc is None:
  2762. loc = os.path.dirname(__file__)
  2763. return loc
  2764. def report_usage(self, resource):
  2765. """
  2766. Increments usage counter for the given resource
  2767. in self.defaults['global_stats'].
  2768. :param resource: Name of the resource.
  2769. :return: None
  2770. """
  2771. if resource in self.defaults['global_stats']:
  2772. self.defaults['global_stats'][resource] += 1
  2773. else:
  2774. self.defaults['global_stats'][resource] = 1
  2775. def init_tcl(self):
  2776. """
  2777. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2778. :return: None
  2779. """
  2780. if hasattr(self, 'tcl'):
  2781. # self.tcl = None
  2782. # TODO we need to clean non default variables and procedures here
  2783. # new object cannot be used here as it will not remember values created for next passes,
  2784. # because tcl was execudted in old instance of TCL
  2785. pass
  2786. else:
  2787. self.tcl = tk.Tcl()
  2788. self.setup_shell()
  2789. self.log.debug("TCL Shell has been initialized.")
  2790. # TODO: This shouldn't be here.
  2791. class TclErrorException(Exception):
  2792. """
  2793. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2794. """
  2795. pass
  2796. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2797. """
  2798. Shows a message on the FlatCAM Shell
  2799. :param msg: Message to display.
  2800. :param show: Opens the shell.
  2801. :param error: Shows the message as an error.
  2802. :param warning: Shows the message as an warning.
  2803. :param success: Shows the message as an success.
  2804. :param selected: Indicate that something was selected on canvas
  2805. :return: None
  2806. """
  2807. if show:
  2808. self.ui.shell_dock.show()
  2809. try:
  2810. if error:
  2811. self.shell.append_error(msg + "\n")
  2812. elif warning:
  2813. self.shell.append_warning(msg + "\n")
  2814. elif success:
  2815. self.shell.append_success(msg + "\n")
  2816. elif selected:
  2817. self.shell.append_selected(msg + "\n")
  2818. else:
  2819. self.shell.append_output(msg + "\n")
  2820. except AttributeError:
  2821. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2822. def raise_tcl_unknown_error(self, unknownException):
  2823. """
  2824. Raise exception if is different type than TclErrorException
  2825. this is here mainly to show unknown errors inside TCL shell console.
  2826. :param unknownException:
  2827. :return:
  2828. """
  2829. if not isinstance(unknownException, self.TclErrorException):
  2830. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2831. else:
  2832. raise unknownException
  2833. def display_tcl_error(self, error, error_info=None):
  2834. """
  2835. Escape bracket [ with '\' otherwise there is error
  2836. "ERROR: missing close-bracket" instead of real error
  2837. :param error: it may be text or exception
  2838. :param error_info: Some informations about the error
  2839. :return: None
  2840. """
  2841. if isinstance(error, Exception):
  2842. exc_type, exc_value, exc_traceback = error_info
  2843. if not isinstance(error, self.TclErrorException):
  2844. show_trace = 1
  2845. else:
  2846. show_trace = int(self.defaults['global_verbose_error_level'])
  2847. if show_trace > 0:
  2848. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2849. trc_formated = []
  2850. for a in reversed(trc):
  2851. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2852. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2853. else:
  2854. text = "%s" % error
  2855. else:
  2856. text = error
  2857. text = text.replace('[', '\\[').replace('"', '\\"')
  2858. self.tcl.eval('return -code error "%s"' % text)
  2859. def raise_tcl_error(self, text):
  2860. """
  2861. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2862. :param text: text of error
  2863. :return: raise exception
  2864. """
  2865. self.display_tcl_error(text)
  2866. raise self.TclErrorException(text)
  2867. def exec_command(self, text, no_echo=False):
  2868. """
  2869. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2870. Also handles execution in separated threads
  2871. :param text: FlatCAM TclCommand with parameters
  2872. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2873. will create crashes of the _Expandable_Edit widget
  2874. :return: output if there was any
  2875. """
  2876. self.report_usage('exec_command')
  2877. result = self.exec_command_test(text, False, no_echo=no_echo)
  2878. # MS: added this method call so the geometry is updated once the TCL command is executed
  2879. # if no_plot is None:
  2880. # self.plot_all()
  2881. return result
  2882. def exec_command_test(self, text, reraise=True, no_echo=False):
  2883. """
  2884. Same as exec_command(...) with additional control over exceptions.
  2885. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2886. :param text: Input command
  2887. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2888. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2889. will create crashes of the _Expandable_Edit widget
  2890. :return: Output from the command
  2891. """
  2892. tcl_command_string = str(text)
  2893. try:
  2894. if no_echo is False:
  2895. self.shell.open_proccessing() # Disables input box.
  2896. result = self.tcl.eval(str(tcl_command_string))
  2897. if result != 'None' and no_echo is False:
  2898. self.shell.append_output(result + '\n')
  2899. except tk.TclError as e:
  2900. # This will display more precise answer if something in TCL shell fails
  2901. result = self.tcl.eval("set errorInfo")
  2902. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2903. if no_echo is False:
  2904. self.shell.append_error('ERROR: ' + result + '\n')
  2905. # Show error in console and just return or in test raise exception
  2906. if reraise:
  2907. raise e
  2908. finally:
  2909. if no_echo is False:
  2910. self.shell.close_proccessing()
  2911. pass
  2912. return result
  2913. # """
  2914. # Code below is unsused. Saved for later.
  2915. # """
  2916. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2917. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2918. # self.log.debug(parts)
  2919. # try:
  2920. # if parts[0] not in commands:
  2921. # self.shell.append_error("Unknown command\n")
  2922. # return
  2923. #
  2924. # #import inspect
  2925. # #inspect.getargspec(someMethod)
  2926. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2927. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2928. # self.shell.append_error(
  2929. # "Command %s takes %d arguments. %d given.\n" %
  2930. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2931. # )
  2932. # return
  2933. #
  2934. # cmdfcn = commands[parts[0]]["fcn"]
  2935. # cmdconv = commands[parts[0]]["converters"]
  2936. # if len(parts) - 1 > 0:
  2937. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2938. # else:
  2939. # retval = cmdfcn()
  2940. # retfcn = commands[parts[0]]["retfcn"]
  2941. # if retval and retfcn(retval):
  2942. # self.shell.append_output(retfcn(retval) + "\n")
  2943. #
  2944. # except Exception as e:
  2945. # #self.shell.append_error(''.join(traceback.format_exc()))
  2946. # #self.shell.append_error("?\n")
  2947. # self.shell.append_error(str(e) + "\n")
  2948. def info(self, msg):
  2949. """
  2950. Informs the user. Normally on the status bar, optionally
  2951. also on the shell.
  2952. :param msg: Text to write.
  2953. :return: None
  2954. """
  2955. # Type of message in brackets at the beginning of the message.
  2956. match = re.search("\[([^\]]+)\](.*)", msg)
  2957. if match:
  2958. level = match.group(1)
  2959. msg_ = match.group(2)
  2960. self.ui.fcinfo.set_status(str(msg_), level=level)
  2961. if level.lower() == "error":
  2962. self.shell_message(msg, error=True, show=True)
  2963. elif level.lower() == "warning":
  2964. self.shell_message(msg, warning=True, show=True)
  2965. elif level.lower() == "error_notcl":
  2966. self.shell_message(msg, error=True, show=False)
  2967. elif level.lower() == "warning_notcl":
  2968. self.shell_message(msg, warning=True, show=False)
  2969. elif level.lower() == "success":
  2970. self.shell_message(msg, success=True, show=False)
  2971. elif level.lower() == "selected":
  2972. self.shell_message(msg, selected=True, show=False)
  2973. else:
  2974. self.shell_message(msg, show=False)
  2975. else:
  2976. self.ui.fcinfo.set_status(str(msg), level="info")
  2977. # make sure that if the message is to clear the infobar with a space
  2978. # is not printed over and over on the shell
  2979. if msg != '':
  2980. self.shell_message(msg)
  2981. def restore_toolbar_view(self):
  2982. """
  2983. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  2984. was saved in the defaults dictionary.
  2985. :return: None
  2986. """
  2987. tb = self.defaults["global_toolbar_view"]
  2988. if tb & 1:
  2989. self.ui.toolbarfile.setVisible(True)
  2990. else:
  2991. self.ui.toolbarfile.setVisible(False)
  2992. if tb & 2:
  2993. self.ui.toolbargeo.setVisible(True)
  2994. else:
  2995. self.ui.toolbargeo.setVisible(False)
  2996. if tb & 4:
  2997. self.ui.toolbarview.setVisible(True)
  2998. else:
  2999. self.ui.toolbarview.setVisible(False)
  3000. if tb & 8:
  3001. self.ui.toolbartools.setVisible(True)
  3002. else:
  3003. self.ui.toolbartools.setVisible(False)
  3004. if tb & 16:
  3005. self.ui.exc_edit_toolbar.setVisible(True)
  3006. else:
  3007. self.ui.exc_edit_toolbar.setVisible(False)
  3008. if tb & 32:
  3009. self.ui.geo_edit_toolbar.setVisible(True)
  3010. else:
  3011. self.ui.geo_edit_toolbar.setVisible(False)
  3012. if tb & 64:
  3013. self.ui.grb_edit_toolbar.setVisible(True)
  3014. else:
  3015. self.ui.grb_edit_toolbar.setVisible(False)
  3016. if tb & 128:
  3017. self.ui.snap_toolbar.setVisible(True)
  3018. else:
  3019. self.ui.snap_toolbar.setVisible(False)
  3020. if tb & 256:
  3021. self.ui.toolbarshell.setVisible(True)
  3022. else:
  3023. self.ui.toolbarshell.setVisible(False)
  3024. def load_defaults(self, filename):
  3025. """
  3026. Loads the aplication's default settings from current_defaults.FlatConfig into
  3027. ``self.defaults``.
  3028. :return: None
  3029. """
  3030. try:
  3031. f = open(self.data_path + "/" + filename + ".FlatConfig")
  3032. options = f.read()
  3033. f.close()
  3034. except IOError:
  3035. self.log.error("Could not load defaults file.")
  3036. self.inform.emit('[ERROR] %s' %
  3037. _("Could not load defaults file."))
  3038. # in case the defaults file can't be loaded, show all toolbars
  3039. self.defaults["global_toolbar_view"] = 511
  3040. return
  3041. try:
  3042. defaults = json.loads(options)
  3043. except:
  3044. # in case the defaults file can't be loaded, show all toolbars
  3045. self.defaults["global_toolbar_view"] = 511
  3046. e = sys.exc_info()[0]
  3047. App.log.error(str(e))
  3048. self.inform.emit('[ERROR] %s' %
  3049. _("Failed to parse defaults file."))
  3050. return
  3051. self.defaults.update(defaults)
  3052. log.debug("FlatCAM defaults loaded from: %s" % filename)
  3053. # restore the toolbar view
  3054. self.restore_toolbar_view()
  3055. def on_import_preferences(self):
  3056. """
  3057. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  3058. ``self.defaults``.
  3059. :return: None
  3060. """
  3061. self.report_usage("on_import_preferences")
  3062. App.log.debug("on_import_preferences()")
  3063. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  3064. try:
  3065. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3066. directory=self.data_path,
  3067. filter=filter_)
  3068. except TypeError:
  3069. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3070. filter=filter_)
  3071. filename = str(filename)
  3072. if filename == "":
  3073. self.inform.emit('[WARNING_NOTCL] %s' %
  3074. _("FlatCAM preferences import cancelled."))
  3075. else:
  3076. try:
  3077. f = open(filename)
  3078. options = f.read()
  3079. f.close()
  3080. except IOError:
  3081. self.log.error("Could not load defaults file.")
  3082. self.inform.emit('[ERROR_NOTCL] %s' %
  3083. _("Could not load defaults file."))
  3084. return
  3085. try:
  3086. defaults_from_file = json.loads(options)
  3087. except Exception as e:
  3088. e = sys.exc_info()[0]
  3089. App.log.error(str(e))
  3090. self.inform.emit('[ERROR_NOTCL] %s' %
  3091. _("Failed to parse defaults file."))
  3092. return
  3093. self.defaults.update(defaults_from_file)
  3094. self.on_preferences_edited()
  3095. self.inform.emit('[success] %s: %s' %
  3096. (_("Imported Defaults from"), filename))
  3097. def on_export_preferences(self):
  3098. """
  3099. Save the defaults dictionary to a file.
  3100. :return: None
  3101. """
  3102. self.report_usage("on_export_preferences")
  3103. App.log.debug("on_export_preferences()")
  3104. defaults_file_content = None
  3105. self.date = str(datetime.today()).rpartition('.')[0]
  3106. self.date = ''.join(c for c in self.date if c not in ':-')
  3107. self.date = self.date.replace(' ', '_')
  3108. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  3109. try:
  3110. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  3111. caption=_("Export FlatCAM Preferences"),
  3112. directory=self.data_path + '/preferences_' + self.date,
  3113. filter=filter__
  3114. )
  3115. except TypeError:
  3116. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  3117. filter=filter__)
  3118. filename = str(filename)
  3119. defaults_from_file = {}
  3120. if filename == "":
  3121. self.inform.emit('[WARNING_NOTCL] %s' %
  3122. _("FlatCAM preferences export cancelled."))
  3123. return
  3124. else:
  3125. try:
  3126. f = open(filename, 'w')
  3127. defaults_file_content = f.read()
  3128. f.close()
  3129. except PermissionError:
  3130. self.inform.emit('[WARNING] %s' %
  3131. _("Permission denied, saving not possible.\n"
  3132. "Most likely another app is holding the file open and not accessible."))
  3133. return
  3134. except IOError:
  3135. App.log.debug('Creating a new preferences file ...')
  3136. f = open(filename, 'w')
  3137. json.dump({}, f)
  3138. f.close()
  3139. except:
  3140. e = sys.exc_info()[0]
  3141. App.log.error("Could not load defaults file.")
  3142. App.log.error(str(e))
  3143. self.inform.emit('[ERROR_NOTCL] %s' %
  3144. _("Could not load preferences file."))
  3145. return
  3146. try:
  3147. defaults_from_file = json.loads(defaults_file_content)
  3148. except:
  3149. App.log.warning("Trying to read an empty Preferences file. Continue.")
  3150. # Update options
  3151. self.defaults_read_form()
  3152. defaults_from_file.update(self.defaults)
  3153. self.propagate_defaults(silent=True)
  3154. # Save update options
  3155. try:
  3156. f = open(filename, "w")
  3157. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  3158. f.close()
  3159. except:
  3160. self.inform.emit('[ERROR_NOTCL] %s' %
  3161. _("Failed to write defaults to file."))
  3162. return
  3163. if self.defaults["global_open_style"] is False:
  3164. self.file_opened.emit("preferences", filename)
  3165. self.file_saved.emit("preferences", filename)
  3166. self.inform.emit('[success] %s: %s' %
  3167. (_("Exported preferences to"), filename))
  3168. def on_preferences_open_folder(self):
  3169. """
  3170. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  3171. :return: None
  3172. """
  3173. self.report_usage("on_preferences_open_folder()")
  3174. if sys.platform == 'win32':
  3175. subprocess.Popen('explorer %s' % self.data_path)
  3176. elif sys.platform == 'darwin':
  3177. os.system('open "%s"' % self.data_path)
  3178. else:
  3179. subprocess.Popen(['xdg-open', self.data_path])
  3180. self.inform.emit('[success] %s' %
  3181. _("FlatCAM Preferences Folder opened."))
  3182. def save_geometry(self, x, y, width, height, notebook_width):
  3183. """
  3184. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  3185. launch of the application.
  3186. :param x: X position of the main window
  3187. :param y: Y position of the main window
  3188. :param width: width of the main window
  3189. :param height: height of the main window
  3190. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  3191. :return: None
  3192. """
  3193. self.defaults["global_def_win_x"] = x
  3194. self.defaults["global_def_win_y"] = y
  3195. self.defaults["global_def_win_w"] = width
  3196. self.defaults["global_def_win_h"] = height
  3197. self.defaults["global_def_notebook_width"] = notebook_width
  3198. self.save_defaults()
  3199. def restore_main_win_geom(self):
  3200. try:
  3201. self.ui.setGeometry(self.defaults["global_def_win_x"],
  3202. self.defaults["global_def_win_y"],
  3203. self.defaults["global_def_win_w"],
  3204. self.defaults["global_def_win_h"])
  3205. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  3206. except KeyError as e:
  3207. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  3208. def message_dialog(self, title, message, kind="info"):
  3209. """
  3210. Builds and show a custom QMessageBox to be used in FlatCAM.
  3211. :param title: title of the QMessageBox
  3212. :param message: message to be displayed
  3213. :param kind: type of QMessageBox; will display a specific icon.
  3214. :return:
  3215. """
  3216. icon = {"info": QtWidgets.QMessageBox.Information,
  3217. "warning": QtWidgets.QMessageBox.Warning,
  3218. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3219. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  3220. dlg.setText(message)
  3221. dlg.exec_()
  3222. def register_recent(self, kind, filename):
  3223. """
  3224. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  3225. dictionary.
  3226. :param kind: type of file that was opened
  3227. :param filename: the path and file name for the file that was opened
  3228. :return:
  3229. """
  3230. self.log.debug("register_recent()")
  3231. self.log.debug(" %s" % kind)
  3232. self.log.debug(" %s" % filename)
  3233. record = {'kind': str(kind), 'filename': str(filename)}
  3234. if record in self.recent:
  3235. return
  3236. if record in self.recent_projects:
  3237. return
  3238. if record['kind'] == 'project':
  3239. self.recent_projects.insert(0, record)
  3240. else:
  3241. self.recent.insert(0, record)
  3242. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3243. self.recent.pop()
  3244. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3245. self.recent_projects.pop()
  3246. try:
  3247. f = open(self.data_path + '/recent.json', 'w')
  3248. except IOError:
  3249. App.log.error("Failed to open recent items file for writing.")
  3250. self.inform.emit('[ERROR_NOTCL] %s' %
  3251. _('Failed to open recent files file for writing.'))
  3252. return
  3253. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3254. f.close()
  3255. try:
  3256. fp = open(self.data_path + '/recent_projects.json', 'w')
  3257. except IOError:
  3258. App.log.error("Failed to open recent items file for writing.")
  3259. self.inform.emit('[ERROR_NOTCL] %s' %
  3260. _('Failed to open recent projects file for writing.'))
  3261. return
  3262. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3263. fp.close()
  3264. # Re-build the recent items menu
  3265. self.setup_recent_items()
  3266. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3267. """
  3268. Creates a new specialized FlatCAMObj and attaches it to the application,
  3269. this is, updates the GUI accordingly, any other records and plots it.
  3270. This method is thread-safe.
  3271. Notes:
  3272. * If the name is in use, the self.collection will modify it
  3273. when appending it to the collection. There is no need to handle
  3274. name conflicts here.
  3275. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3276. :type kind: str
  3277. :param name: Name for the object.
  3278. :type name: str
  3279. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3280. The function is called with 2 parameters: the new object and the App instance.
  3281. :type initialize: function
  3282. :param active:
  3283. :param fit:
  3284. :param plot: If to plot the resulting object
  3285. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3286. self.colleaction
  3287. :return: None
  3288. :rtype: None
  3289. """
  3290. App.log.debug("new_object()")
  3291. obj_plot = plot
  3292. obj_autoselected = autoselected
  3293. t0 = time.time() # Debug
  3294. # ## Create object
  3295. classdict = {
  3296. "gerber": FlatCAMGerber,
  3297. "excellon": FlatCAMExcellon,
  3298. "cncjob": FlatCAMCNCjob,
  3299. "geometry": FlatCAMGeometry
  3300. }
  3301. App.log.debug("Calling object constructor...")
  3302. obj = classdict[kind](name)
  3303. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3304. # Set options from "Project options" form
  3305. self.options_read_form()
  3306. # IMPORTANT
  3307. # The key names in defaults and options dictionary's are not random:
  3308. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3309. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  3310. # the options from project options form into the self.options. After that, below, depending on the type of
  3311. # object that is created, it will strip the name of the object and the underline (if the original key was
  3312. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3313. # "toolchange"
  3314. for option in self.options:
  3315. if option.find(kind + "_") == 0:
  3316. oname = option[len(kind) + 1:]
  3317. obj.options[oname] = self.options[option]
  3318. obj.isHovering = False
  3319. obj.notHovering = True
  3320. # Initialize as per user request
  3321. # User must take care to implement initialize
  3322. # in a thread-safe way as is is likely that we
  3323. # have been invoked in a separate thread.
  3324. t1 = time.time()
  3325. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3326. try:
  3327. return_value = initialize(obj, self)
  3328. except Exception as e:
  3329. msg = '[ERROR_NOTCL] %s' % \
  3330. _("An internal error has ocurred. See shell.\n")
  3331. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3332. msg += traceback.format_exc()
  3333. self.inform.emit(msg)
  3334. # if str(e) == "Empty Geometry":
  3335. # self.inform.emit("[ERROR_NOTCL] )
  3336. # else:
  3337. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  3338. return "fail"
  3339. t2 = time.time()
  3340. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3341. if return_value == 'fail':
  3342. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3343. return "fail"
  3344. # Check units and convert if necessary
  3345. # This condition CAN be true because initialize() can change obj.units
  3346. if self.options["units"].upper() != obj.units.upper():
  3347. self.inform.emit('%s: %s' %
  3348. (_("Converting units to "), self.options["units"]))
  3349. obj.convert_units(self.options["units"])
  3350. t3 = time.time()
  3351. self.log.debug("%f seconds converting units." % (t3 - t2))
  3352. # Create the bounding box for the object and then add the results to the obj.options
  3353. try:
  3354. xmin, ymin, xmax, ymax = obj.bounds()
  3355. obj.options['xmin'] = xmin
  3356. obj.options['ymin'] = ymin
  3357. obj.options['xmax'] = xmax
  3358. obj.options['ymax'] = ymax
  3359. except Exception as e:
  3360. log.warning("The object has no bounds properties. %s" % str(e))
  3361. return "fail"
  3362. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3363. # Move the object to the main thread and let the app know that it is available.
  3364. obj.moveToThread(self.main_thread)
  3365. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3366. return obj
  3367. def new_excellon_object(self):
  3368. """
  3369. Creates a new, blank Excellon object.
  3370. :return: None
  3371. """
  3372. self.report_usage("new_excellon_object()")
  3373. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3374. def new_geometry_object(self):
  3375. """
  3376. Creates a new, blank and single-tool Geometry object.
  3377. :return: None
  3378. """
  3379. self.report_usage("new_geometry_object()")
  3380. def initialize(obj, self):
  3381. obj.multitool = False
  3382. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3383. def new_gerber_object(self):
  3384. """
  3385. Creates a new, blank Gerber object.
  3386. :return: None
  3387. """
  3388. self.report_usage("new_gerber_object()")
  3389. def initialize(grb_obj, self):
  3390. grb_obj.multitool = False
  3391. grb_obj.source_file = []
  3392. grb_obj.multigeo = False
  3393. grb_obj.follow = False
  3394. grb_obj.apertures = {}
  3395. grb_obj.solid_geometry = []
  3396. try:
  3397. grb_obj.options['xmin'] = 0
  3398. grb_obj.options['ymin'] = 0
  3399. grb_obj.options['xmax'] = 0
  3400. grb_obj.options['ymax'] = 0
  3401. except KeyError:
  3402. pass
  3403. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3404. def on_object_created(self, obj, plot, autoselect):
  3405. """
  3406. Event callback for object creation.
  3407. It will add the new object to the collection. After that it will plot the object in a threaded way
  3408. :param obj: The newly created FlatCAM object.
  3409. :param plot: if the newly create object t obe plotted
  3410. :param autoselect: if the newly created object to be autoselected after creation
  3411. :return: None
  3412. """
  3413. t0 = time.time() # DEBUG
  3414. self.log.debug("on_object_created()")
  3415. # The Collection might change the name if there is a collision
  3416. self.collection.append(obj)
  3417. # after adding the object to the collection always update the list of objects that are in the collection
  3418. self.all_objects_list = self.collection.get_list()
  3419. # self.inform.emit('[selected] %s created & selected: %s' %
  3420. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3421. if obj.kind == 'gerber':
  3422. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3423. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3424. elif obj.kind == 'excellon':
  3425. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3426. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3427. elif obj.kind == 'cncjob':
  3428. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3429. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3430. elif obj.kind == 'geometry':
  3431. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3432. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3433. # update the SHELL auto-completer model with the name of the new object
  3434. self.myKeywords.append(obj.options['name'])
  3435. self.shell._edit.set_model_data(self.myKeywords)
  3436. self.ui.code_editor.set_model_data(self.myKeywords)
  3437. if autoselect:
  3438. # select the just opened object but deselect the previous ones
  3439. self.collection.set_all_inactive()
  3440. self.collection.set_active(obj.options["name"])
  3441. else:
  3442. self.collection.set_all_inactive()
  3443. # here it is done the object plotting
  3444. def worker_task(t_obj):
  3445. with self.proc_container.new(_("Plotting")):
  3446. if isinstance(t_obj, FlatCAMCNCjob):
  3447. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3448. else:
  3449. t_obj.plot()
  3450. t1 = time.time() # DEBUG
  3451. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3452. self.object_plotted.emit(t_obj)
  3453. # Send to worker
  3454. # self.worker.add_task(worker_task, [self])
  3455. if plot is True:
  3456. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3457. def on_object_changed(self, obj):
  3458. """
  3459. Called whenever the geometry of the object was changed in some way.
  3460. This require the update of it's bounding values so it can be the selected on canvas.
  3461. Update the bounding box data from obj.options
  3462. :param obj: the object that was changed
  3463. :return: None
  3464. """
  3465. xmin, ymin, xmax, ymax = obj.bounds()
  3466. obj.options['xmin'] = xmin
  3467. obj.options['ymin'] = ymin
  3468. obj.options['xmax'] = xmax
  3469. obj.options['ymax'] = ymax
  3470. log.debug("Object changed, updating the bounding box data on self.options")
  3471. # delete the old selection shape
  3472. self.delete_selection_shape()
  3473. self.should_we_save = True
  3474. def on_object_plotted(self, obj):
  3475. """
  3476. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3477. :param obj: object to be fit into view
  3478. :return: None
  3479. """
  3480. self.on_zoom_fit(None)
  3481. def options_read_form(self):
  3482. """
  3483. Same as it's equivalent from the defaults.
  3484. self.options use to store the preferences per project. No longer used.
  3485. :return: None
  3486. """
  3487. for option in self.options_form_fields:
  3488. self.options[option] = self.options_form_fields[option].get_value()
  3489. def options_write_form(self):
  3490. """
  3491. Same as it's equivalent from the defaults.
  3492. self.options use to store the preferences per project. No longer used.
  3493. :return: None
  3494. """
  3495. for option in self.options:
  3496. self.options_write_form_field(option)
  3497. def options_write_form_field(self, field):
  3498. """
  3499. Same as it's equivalent from the defaults.
  3500. self.options use to store the preferences per project. No longer used.
  3501. :return: None
  3502. """
  3503. try:
  3504. self.options_form_fields[field].set_value(self.options[field])
  3505. except KeyError:
  3506. # Changed from error to debug. This allows to have data stored
  3507. # which is not user-editable.
  3508. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  3509. pass
  3510. def on_about(self):
  3511. """
  3512. Displays the "about" dialog found in the Menu --> Help.
  3513. :return: None
  3514. """
  3515. self.report_usage("on_about")
  3516. version = self.version
  3517. version_date = self.version_date
  3518. beta = self.beta
  3519. class AboutDialog(QtWidgets.QDialog):
  3520. def __init__(self, parent=None):
  3521. QtWidgets.QDialog.__init__(self, parent)
  3522. # Icon and title
  3523. self.setWindowIcon(parent.app_icon)
  3524. self.setWindowTitle(_("About FlatCAM"))
  3525. self.resize(600, 200)
  3526. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3527. # self.setStyleSheet(
  3528. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3529. # "background-attachment: fixed"
  3530. # )
  3531. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3532. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3533. # palette = QtGui.QPalette()
  3534. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3535. # self.setPalette(palette)
  3536. logo = QtWidgets.QLabel()
  3537. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3538. title = QtWidgets.QLabel(
  3539. "<font size=8><B>FlatCAM</B></font><BR>"
  3540. "{title}<BR>"
  3541. "<BR>"
  3542. "<BR>"
  3543. # "<B>{devel}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3544. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3545. # "<b>{down}</B> area &nbsp;&nbsp;&nbsp;&nbsp;"
  3546. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3547. # "<b> {issue}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3548. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3549. "<B>{issue}</B></a><BR>".format(
  3550. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3551. devel=_("Development"),
  3552. down=_("DOWNLOAD"),
  3553. issue=_("Issue tracker"))
  3554. )
  3555. title.setOpenExternalLinks(True)
  3556. closebtn = QtWidgets.QPushButton(_("Close"))
  3557. tab_widget = QtWidgets.QTabWidget()
  3558. description_label = QtWidgets.QLabel(
  3559. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3560. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3561. version=version,
  3562. beta=('BETA' if beta else ''),
  3563. date=version_date,
  3564. arch=platform.architecture()[0])
  3565. )
  3566. description_label.setOpenExternalLinks(True)
  3567. license_label = QtWidgets.QLabel(
  3568. _(
  3569. '(c) Copyright 2014 Juan Pablo Caram.\n\n'
  3570. 'Licensed under the MIT license:\n'
  3571. 'http://www.opensource.org/licenses/mit-license.php\n\n'
  3572. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3573. 'of this software and associated documentation files (the "Software"), to deal\n'
  3574. 'in the Software without restriction, including without limitation the rights\n'
  3575. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3576. 'copies of the Software, and to permit persons to whom the Software is\n'
  3577. ' furnished to do so, subject to the following conditions:\n\n'
  3578. 'The above copyright notice and this permission notice shall be included in\n'
  3579. 'all copies or substantial portions of the Software.\n\n'
  3580. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3581. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3582. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3583. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3584. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3585. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3586. 'THE SOFTWARE.'
  3587. )
  3588. )
  3589. license_label.setOpenExternalLinks(True)
  3590. # layouts
  3591. layout1 = QtWidgets.QVBoxLayout()
  3592. layout1_1 = QtWidgets.QHBoxLayout()
  3593. layout1_2 = QtWidgets.QHBoxLayout()
  3594. layout2 = QtWidgets.QHBoxLayout()
  3595. layout3 = QtWidgets.QHBoxLayout()
  3596. self.setLayout(layout1)
  3597. layout1.addLayout(layout1_1)
  3598. layout1.addLayout(layout1_2)
  3599. layout1.addLayout(layout2)
  3600. layout1.addLayout(layout3)
  3601. layout1_1.addStretch()
  3602. layout1_1.addWidget(description_label)
  3603. layout1_2.addWidget(tab_widget)
  3604. self.splash_tab = QtWidgets.QWidget()
  3605. self.splash_tab.setObjectName("splash_about")
  3606. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3607. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3608. tab_widget.addTab(self.splash_tab, _("Splash"))
  3609. self.programmmers_tab = QtWidgets.QWidget()
  3610. self.programmmers_tab.setObjectName("programmers_about")
  3611. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3612. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3613. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3614. self.translators_tab = QtWidgets.QWidget()
  3615. self.translators_tab.setObjectName("translators_about")
  3616. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3617. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3618. tab_widget.addTab(self.translators_tab, _("Translators"))
  3619. self.license_tab = QtWidgets.QWidget()
  3620. self.license_tab.setObjectName("license_about")
  3621. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3622. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3623. tab_widget.addTab(self.license_tab, _("License"))
  3624. self.splash_tab_layout.addWidget(logo, stretch=0)
  3625. self.splash_tab_layout.addWidget(title, stretch=1)
  3626. pal = QtGui.QPalette()
  3627. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3628. self.prog_form_lay = QtWidgets.QFormLayout()
  3629. self.prog_form_lay.setHorizontalSpacing(20)
  3630. prog_widget = QtWidgets.QWidget()
  3631. prog_widget.setLayout(self.prog_form_lay)
  3632. prog_scroll = QtWidgets.QScrollArea()
  3633. prog_scroll.setWidget(prog_widget)
  3634. prog_scroll.setWidgetResizable(True)
  3635. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3636. prog_scroll.setPalette(pal)
  3637. self.programmmers_tab_layout.addWidget(prog_scroll)
  3638. self.prog_form_lay.addRow(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")),
  3639. QtWidgets.QLabel('<b>%s</b>' % _("Status")))
  3640. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Juan Pablo Caram"),
  3641. QtWidgets.QLabel('%s' % _("Program Author")))
  3642. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Denis Hayrullin"))
  3643. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Kamil Sopko"))
  3644. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marius Stanciu"),
  3645. QtWidgets.QLabel('%s' % _("Maintainer >=2019")))
  3646. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3647. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Alexandru Lazar"))
  3648. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Matthieu Berthomé"))
  3649. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Evans"))
  3650. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Victor Benso"))
  3651. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3652. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Barnaby Walters"))
  3653. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"))
  3654. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lei Zheng"))
  3655. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marco A Quezada"))
  3656. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3657. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Cedric Dussud"))
  3658. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Chris Hemingway"))
  3659. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Damian Wrobel"))
  3660. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Daniel Sallin"))
  3661. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3662. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Bruno Vunderl"))
  3663. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Gonzalo Lopez"))
  3664. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jakob Staudt"))
  3665. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Smith"))
  3666. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3667. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lubos Medovarsky"))
  3668. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Steve Martina"))
  3669. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Thomas Duffin"))
  3670. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3671. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Idechix"))
  3672. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@SM"))
  3673. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@grbf"))
  3674. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Symonty"))
  3675. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@mgix"))
  3676. self.translator_grid_lay = QtWidgets.QGridLayout()
  3677. # trans_widget = QtWidgets.QWidget()
  3678. # trans_widget.setLayout(self.translator_grid_lay)
  3679. # self.translators_tab_layout.addWidget(trans_widget)
  3680. # self.translators_tab_layout.addStretch()
  3681. trans_widget = QtWidgets.QWidget()
  3682. trans_widget.setLayout(self.translator_grid_lay)
  3683. trans_scroll = QtWidgets.QScrollArea()
  3684. trans_scroll.setWidget(trans_widget)
  3685. trans_scroll.setWidgetResizable(True)
  3686. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3687. trans_scroll.setPalette(pal)
  3688. self.translators_tab_layout.addWidget(trans_scroll)
  3689. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  3690. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  3691. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3692. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Brasilian - Portuguese"), 1, 0)
  3693. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  3694. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 1, 2)
  3695. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  3696. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 2, 1)
  3697. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 2)
  3698. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  3699. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 3, 1)
  3700. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  3701. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  3702. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  3703. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  3704. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  3705. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  3706. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 2)
  3707. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  3708. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 6, 1)
  3709. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 2)
  3710. self.translator_grid_lay.setColumnStretch(0, 0)
  3711. self.translators_tab_layout.addStretch()
  3712. self.license_tab_layout.addWidget(license_label)
  3713. self.license_tab_layout.addStretch()
  3714. layout3.addStretch()
  3715. layout3.addWidget(closebtn)
  3716. closebtn.clicked.connect(self.accept)
  3717. AboutDialog(self.ui).exec_()
  3718. def on_file_savedefaults(self):
  3719. """
  3720. Callback for menu item File->Save Defaults. Saves application default options
  3721. ``self.defaults`` to current_defaults.FlatConfig.
  3722. :return: None
  3723. """
  3724. self.save_defaults()
  3725. # def on_app_exit(self):
  3726. # self.report_usage("on_app_exit()")
  3727. #
  3728. # if self.collection.get_list():
  3729. # msgbox = QtWidgets.QMessageBox()
  3730. # # msgbox.setText("<B>Save changes ...</B>")
  3731. # msgbox.setText("There are files/objects opened in FlatCAM. "
  3732. # "\n"
  3733. # "Do you want to Save the project?")
  3734. # msgbox.setWindowTitle("Save changes")
  3735. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3736. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  3737. # QtWidgets.QMessageBox.Cancel)
  3738. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  3739. #
  3740. # response = msgbox.exec_()
  3741. #
  3742. # if response == QtWidgets.QMessageBox.Yes:
  3743. # self.on_file_saveprojectas(thread=False)
  3744. # elif response == QtWidgets.QMessageBox.Cancel:
  3745. # return
  3746. # self.save_defaults()
  3747. # else:
  3748. # self.save_defaults()
  3749. # log.debug("Application defaults saved ... Exit event.")
  3750. # QtWidgets.qApp.quit()
  3751. def save_defaults(self, silent=False, data_path=None, first_time=False):
  3752. """
  3753. Saves application default options
  3754. ``self.defaults`` to current_defaults.FlatConfig file.
  3755. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  3756. used at the next launch of the application.
  3757. :param silent: whether to display a message in status bar or not; boolean
  3758. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  3759. When the application is portable it should be a mobile location.
  3760. :return: None
  3761. """
  3762. self.report_usage("save_defaults")
  3763. if data_path is None:
  3764. data_path = self.data_path
  3765. # Read options from file
  3766. try:
  3767. f = open(data_path + "/current_defaults.FlatConfig")
  3768. defaults_file_content = f.read()
  3769. f.close()
  3770. except:
  3771. e = sys.exc_info()[0]
  3772. App.log.error("Could not load defaults file.")
  3773. App.log.error(str(e))
  3774. self.inform.emit('[ERROR_NOTCL] %s' %
  3775. _("Could not load defaults file."))
  3776. return
  3777. try:
  3778. defaults = json.loads(defaults_file_content)
  3779. except:
  3780. e = sys.exc_info()[0]
  3781. App.log.error("Failed to parse defaults file.")
  3782. App.log.error(str(e))
  3783. self.inform.emit('[ERROR_NOTCL] %s' %
  3784. _("Failed to parse defaults file."))
  3785. return
  3786. # Update options
  3787. self.defaults_read_form()
  3788. defaults.update(self.defaults)
  3789. self.propagate_defaults(silent=True)
  3790. # Save the toolbar view
  3791. tb_status = 0
  3792. if self.ui.toolbarfile.isVisible():
  3793. tb_status += 1
  3794. if self.ui.toolbargeo.isVisible():
  3795. tb_status += 2
  3796. if self.ui.toolbarview.isVisible():
  3797. tb_status += 4
  3798. if self.ui.toolbartools.isVisible():
  3799. tb_status += 8
  3800. if self.ui.exc_edit_toolbar.isVisible():
  3801. tb_status += 16
  3802. if self.ui.geo_edit_toolbar.isVisible():
  3803. tb_status += 32
  3804. if self.ui.grb_edit_toolbar.isVisible():
  3805. tb_status += 64
  3806. if self.ui.snap_toolbar.isVisible():
  3807. tb_status += 128
  3808. if self.ui.toolbarshell.isVisible():
  3809. tb_status += 256
  3810. if first_time is False:
  3811. self.defaults["global_toolbar_view"] = tb_status
  3812. # Save update options
  3813. try:
  3814. f = open(data_path + "/current_defaults.FlatConfig", "w")
  3815. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  3816. f.close()
  3817. except:
  3818. self.inform.emit('[ERROR_NOTCL] %s' %
  3819. _("Failed to write defaults to file."))
  3820. return
  3821. if not silent:
  3822. self.inform.emit('[success] %s' %
  3823. _("Preferences saved."))
  3824. def save_factory_defaults(self, silent=False, data_path=None):
  3825. """
  3826. Saves application factory default options
  3827. ``self.defaults`` to factory_defaults.FlatConfig.
  3828. It's a one time job done just after the first install.
  3829. :param silent: whether to display a message in status bar or not; boolean
  3830. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  3831. When the application is portable it should be a mobile location.
  3832. :return: None
  3833. """
  3834. self.report_usage("save_factory_defaults")
  3835. if data_path is None:
  3836. data_path = self.data_path
  3837. # Read options from file
  3838. try:
  3839. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  3840. factory_defaults_file_content = f_f_def.read()
  3841. f_f_def.close()
  3842. except:
  3843. e = sys.exc_info()[0]
  3844. App.log.error("Could not load factory defaults file.")
  3845. App.log.error(str(e))
  3846. self.inform.emit('[ERROR_NOTCL] %s' %
  3847. _("Could not load factory defaults file."))
  3848. return
  3849. try:
  3850. factory_defaults = json.loads(factory_defaults_file_content)
  3851. except:
  3852. e = sys.exc_info()[0]
  3853. App.log.error("Failed to parse factory defaults file.")
  3854. App.log.error(str(e))
  3855. self.inform.emit('[ERROR_NOTCL] %s' %
  3856. _("Failed to parse factory defaults file."))
  3857. return
  3858. # Update options
  3859. self.defaults_read_form()
  3860. factory_defaults.update(self.defaults)
  3861. self.propagate_defaults(silent=True)
  3862. # Save update options
  3863. try:
  3864. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  3865. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3866. f_f_def_s.close()
  3867. except:
  3868. self.inform.emit('[ERROR_NOTCL] %s' %
  3869. _("Failed to write factory defaults to file."))
  3870. return
  3871. if silent is False:
  3872. self.inform.emit(_("Factory defaults saved."))
  3873. def final_save(self):
  3874. """
  3875. Callback for doing a preferences save to file whenever the application is about to quit.
  3876. If the project has changes, it will ask the user to save the project.
  3877. :return: None
  3878. """
  3879. if self.save_in_progress:
  3880. self.inform.emit('[WARNING_NOTCL] %s' %
  3881. _("Application is saving the project. Please wait ..."))
  3882. return
  3883. if self.should_we_save and self.collection.get_list():
  3884. msgbox = QtWidgets.QMessageBox()
  3885. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  3886. "\n"
  3887. "Do you want to Save the project?"))
  3888. msgbox.setWindowTitle(_("Save changes"))
  3889. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3890. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  3891. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  3892. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3893. msgbox.setDefaultButton(bt_yes)
  3894. msgbox.exec_()
  3895. response = msgbox.clickedButton()
  3896. if response == bt_yes:
  3897. try:
  3898. self.trayIcon.hide()
  3899. except:
  3900. pass
  3901. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  3902. elif response == bt_no:
  3903. try:
  3904. self.trayIcon.hide()
  3905. except:
  3906. pass
  3907. self.quit_application()
  3908. elif response == bt_cancel:
  3909. return
  3910. else:
  3911. try:
  3912. self.trayIcon.hide()
  3913. except:
  3914. pass
  3915. self.quit_application()
  3916. def quit_application(self):
  3917. """
  3918. Called (as a pyslot or not) when the application is quit.
  3919. :return: None
  3920. """
  3921. self.save_defaults()
  3922. log.debug("App.final_save() --> App Defaults saved.")
  3923. if self.cmd_line_headless != 1:
  3924. # save app state to file
  3925. settings = QSettings("Open Source", "FlatCAM")
  3926. settings.setValue('saved_gui_state', self.ui.saveState())
  3927. settings.setValue('maximized_gui', self.ui.isMaximized())
  3928. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  3929. settings.setValue(
  3930. 'notebook_font_size',
  3931. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  3932. )
  3933. settings.setValue('axis_font_size',
  3934. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value())
  3935. settings.setValue(
  3936. 'textbox_font_size',
  3937. self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  3938. )
  3939. settings.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  3940. # This will write the setting to the platform specific storage.
  3941. del settings
  3942. log.debug("App.final_save() --> App UI state saved.")
  3943. QtWidgets.qApp.quit()
  3944. def on_portable_checked(self, state):
  3945. """
  3946. Callback called when the checkbox in Preferences GUI is checked.
  3947. It will set the application as portable by creating the preferences and recent files in the
  3948. 'config' folder found in the FlatCAM installation folder.
  3949. :param state: boolean, the state of the checkbox when clicked/checked
  3950. :return:
  3951. """
  3952. line_no = 0
  3953. data = None
  3954. if sys.platform != 'win32':
  3955. # this won't work in Linux or MacOS
  3956. return
  3957. # test if the app was frozen and choose the path for the configuration file
  3958. if getattr(sys, "frozen", False) is True:
  3959. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  3960. else:
  3961. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  3962. config_file = current_data_path + '\\configuration.txt'
  3963. try:
  3964. with open(config_file, 'r') as f:
  3965. try:
  3966. data = f.readlines()
  3967. except Exception as e:
  3968. log.debug('App.__init__() -->%s' % str(e))
  3969. return
  3970. except FileNotFoundError:
  3971. pass
  3972. for line in data:
  3973. line = line.strip('\n')
  3974. param = str(line).rpartition('=')
  3975. if param[0] == 'portable':
  3976. break
  3977. line_no += 1
  3978. if state:
  3979. data[line_no] = 'portable=True\n'
  3980. # create the new defauults files
  3981. # create current_defaults.FlatConfig file if there is none
  3982. try:
  3983. f = open(current_data_path + '/current_defaults.FlatConfig')
  3984. f.close()
  3985. except IOError:
  3986. App.log.debug('Creating empty current_defaults.FlatConfig')
  3987. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3988. json.dump({}, f)
  3989. f.close()
  3990. # create factory_defaults.FlatConfig file if there is none
  3991. try:
  3992. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3993. f.close()
  3994. except IOError:
  3995. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3996. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3997. json.dump({}, f)
  3998. f.close()
  3999. try:
  4000. f = open(current_data_path + '/recent.json')
  4001. f.close()
  4002. except IOError:
  4003. App.log.debug('Creating empty recent.json')
  4004. f = open(current_data_path + '/recent.json', 'w')
  4005. json.dump([], f)
  4006. f.close()
  4007. try:
  4008. fp = open(current_data_path + '/recent_projects.json')
  4009. fp.close()
  4010. except IOError:
  4011. App.log.debug('Creating empty recent_projects.json')
  4012. fp = open(current_data_path + '/recent_projects.json', 'w')
  4013. json.dump([], fp)
  4014. fp.close()
  4015. # save the current defaults to the new defaults file
  4016. self.save_defaults(silent=True, data_path=current_data_path)
  4017. self.save_factory_defaults(silent=True, data_path=current_data_path)
  4018. else:
  4019. data[line_no] = 'portable=False\n'
  4020. with open(config_file, 'w') as f:
  4021. f.writelines(data)
  4022. def on_toggle_shell(self):
  4023. """
  4024. Toggle shell: if is visible close it, if it is closed then open it
  4025. :return:
  4026. """
  4027. self.report_usage("on_toggle_shell()")
  4028. if self.ui.shell_dock.isVisible():
  4029. self.ui.shell_dock.hide()
  4030. else:
  4031. self.ui.shell_dock.show()
  4032. def on_register_files(self, obj_type=None):
  4033. """
  4034. Called whenever there is a need to register file extensions with FlatCAM.
  4035. Works only in Windows and should be called only when FlatCAM is run in Windows.
  4036. :param obj_type: the type of object to be register for.
  4037. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  4038. :return: None
  4039. """
  4040. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  4041. new_reg_path = 'Software\\Classes\\'
  4042. # find if the current user is admin
  4043. try:
  4044. is_admin = os.getuid() == 0
  4045. except AttributeError:
  4046. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  4047. if is_admin is True:
  4048. root_path = winreg.HKEY_LOCAL_MACHINE
  4049. else:
  4050. root_path = winreg.HKEY_CURRENT_USER
  4051. # create the keys
  4052. def set_reg(name, root_path, new_reg_path, value):
  4053. try:
  4054. winreg.CreateKey(root_path, new_reg_path)
  4055. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  4056. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  4057. return True
  4058. except WindowsError:
  4059. return False
  4060. # delete key in registry
  4061. def delete_reg(root_path, reg_path, key_to_del):
  4062. key_to_del_path = reg_path + key_to_del
  4063. try:
  4064. winreg.DeleteKey(root_path, key_to_del_path)
  4065. return True
  4066. except WindowsError:
  4067. return False
  4068. if obj_type is None or obj_type == 'excellon':
  4069. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4070. exc_list = [x for x in exc_list if x != '']
  4071. # register all keys in the Preferences window
  4072. for ext in exc_list:
  4073. new_k = new_reg_path + '.%s' % ext
  4074. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4075. # and unregister those that are no longer in the Preferences windows but are in the file
  4076. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  4077. if ext not in exc_list:
  4078. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4079. # now write the updated extensions to the self.defaults
  4080. # new_ext = ''
  4081. # for ext in exc_list:
  4082. # new_ext = new_ext + ext + ', '
  4083. # self.defaults["fa_excellon"] = new_ext
  4084. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  4085. if obj_type is None or obj_type == 'gcode':
  4086. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4087. gco_list = [x for x in gco_list if x != '']
  4088. # register all keys in the Preferences window
  4089. for ext in gco_list:
  4090. new_k = new_reg_path + '.%s' % ext
  4091. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4092. # and unregister those that are no longer in the Preferences windows but are in the file
  4093. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  4094. if ext not in gco_list:
  4095. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4096. # now write the updated extensions to the self.defaults
  4097. # new_ext = ''
  4098. # for ext in gco_list:
  4099. # new_ext = new_ext + ext + ', '
  4100. # self.defaults["fa_gcode"] = new_ext
  4101. self.inform.emit('[success] %s' %
  4102. _("Selected GCode file extensions registered with FlatCAM."))
  4103. if obj_type is None or obj_type == 'gerber':
  4104. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4105. grb_list = [x for x in grb_list if x != '']
  4106. # register all keys in the Preferences window
  4107. for ext in grb_list:
  4108. new_k = new_reg_path + '.%s' % ext
  4109. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4110. # and unregister those that are no longer in the Preferences windows but are in the file
  4111. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  4112. if ext not in grb_list:
  4113. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4114. # now write the updated extensions to the self.defaults
  4115. # new_ext = ''
  4116. # for ext in grb_list:
  4117. # new_ext = new_ext + ext + ', '
  4118. # self.defaults["fa_gerber"] = new_ext
  4119. self.inform.emit('[success] %s' %
  4120. _("Selected Gerber file extensions registered with FlatCAM."))
  4121. def add_extension(self, ext_type):
  4122. if ext_type == 'excellon':
  4123. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4124. if new_ext == '':
  4125. return
  4126. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4127. if new_ext in old_val:
  4128. return
  4129. old_val.append(new_ext)
  4130. old_val.sort()
  4131. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4132. if ext_type == 'gcode':
  4133. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4134. if new_ext == '':
  4135. return
  4136. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4137. if new_ext in old_val:
  4138. return
  4139. old_val.append(new_ext)
  4140. old_val.sort()
  4141. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4142. if ext_type == 'gerber':
  4143. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4144. if new_ext == '':
  4145. return
  4146. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4147. if new_ext in old_val:
  4148. return
  4149. old_val.append(new_ext)
  4150. old_val.sort()
  4151. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4152. if ext_type == 'keyword':
  4153. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4154. if new_kw == '':
  4155. return
  4156. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4157. if new_kw in old_val:
  4158. return
  4159. old_val.append(new_kw)
  4160. old_val.sort()
  4161. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4162. # update the self.myKeywords so the model is updated
  4163. self.autocomplete_kw_list = \
  4164. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4165. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4166. self.shell._edit.set_model_data(self.myKeywords)
  4167. self.ui.code_editor.set_model_data(self.myKeywords)
  4168. def del_extension(self, ext_type):
  4169. if ext_type == 'excellon':
  4170. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4171. if new_ext == '':
  4172. return
  4173. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4174. if new_ext not in old_val:
  4175. return
  4176. old_val.remove(new_ext)
  4177. old_val.sort()
  4178. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4179. if ext_type == 'gcode':
  4180. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4181. if new_ext == '':
  4182. return
  4183. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4184. if new_ext not in old_val:
  4185. return
  4186. old_val.remove(new_ext)
  4187. old_val.sort()
  4188. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4189. if ext_type == 'gerber':
  4190. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4191. if new_ext == '':
  4192. return
  4193. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4194. if new_ext not in old_val:
  4195. return
  4196. old_val.remove(new_ext)
  4197. old_val.sort()
  4198. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4199. if ext_type == 'keyword':
  4200. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4201. if new_kw == '':
  4202. return
  4203. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4204. if new_kw not in old_val:
  4205. return
  4206. old_val.remove(new_kw)
  4207. old_val.sort()
  4208. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4209. # update the self.myKeywords so the model is updated
  4210. self.autocomplete_kw_list = \
  4211. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4212. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4213. self.shell._edit.set_model_data(self.myKeywords)
  4214. self.ui.code_editor.set_model_data(self.myKeywords)
  4215. def restore_extensions(self, ext_type):
  4216. if ext_type == 'excellon':
  4217. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  4218. # for the ability to open Excellon files with .txt extension
  4219. new_exc_list = deepcopy(self.exc_list)
  4220. try:
  4221. new_exc_list.remove('txt')
  4222. except ValueError:
  4223. pass
  4224. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  4225. if ext_type == 'gcode':
  4226. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  4227. if ext_type == 'gerber':
  4228. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  4229. if ext_type == 'keyword':
  4230. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  4231. # update the self.myKeywords so the model is updated
  4232. self.autocomplete_kw_list = self.default_keywords
  4233. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4234. self.shell._edit.set_model_data(self.myKeywords)
  4235. self.ui.code_editor.set_model_data(self.myKeywords)
  4236. def delete_all_extensions(self, ext_type):
  4237. if ext_type == 'excellon':
  4238. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4239. if ext_type == 'gcode':
  4240. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4241. if ext_type == 'gerber':
  4242. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4243. if ext_type == 'keyword':
  4244. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4245. # update the self.myKeywords so the model is updated
  4246. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4247. self.shell._edit.set_model_data(self.myKeywords)
  4248. self.ui.code_editor.set_model_data(self.myKeywords)
  4249. def on_edit_join(self, name=None):
  4250. """
  4251. Callback for Edit->Join. Joins the selected geometry objects into
  4252. a new one.
  4253. :return: None
  4254. """
  4255. self.report_usage("on_edit_join()")
  4256. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4257. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4258. tooldias = []
  4259. geo_type_list = set()
  4260. objs = self.collection.get_selected()
  4261. if len(objs) < 2:
  4262. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4263. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4264. return 'fail'
  4265. for obj in objs:
  4266. geo_type_list.add(obj.multigeo)
  4267. # if len(geo_type_list) == 1 means that all list elements are the same
  4268. if len(geo_type_list) != 1:
  4269. self.inform.emit('[ERROR] %s' %
  4270. _("Failed join. The Geometry objects are of different types.\n"
  4271. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4272. "convert from one to another and retry joining \n"
  4273. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4274. "the result may not be what was expected. \n"
  4275. "Check the generated GCODE."))
  4276. return
  4277. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4278. if True in geo_type_list:
  4279. def initialize(obj, app):
  4280. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=True)
  4281. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4282. for v in obj.tools.values():
  4283. v['data']['name'] = obj_name_multi
  4284. self.new_object("geometry", obj_name_multi, initialize)
  4285. else:
  4286. def initialize(obj, app):
  4287. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=False)
  4288. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4289. for v in obj.tools.values():
  4290. v['data']['name'] = obj_name_single
  4291. self.new_object("geometry", obj_name_single, initialize)
  4292. self.should_we_save = True
  4293. def on_edit_join_exc(self):
  4294. """
  4295. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4296. a new Excellon.
  4297. :return: None
  4298. """
  4299. self.report_usage("on_edit_join_exc()")
  4300. objs = self.collection.get_selected()
  4301. for obj in objs:
  4302. if not isinstance(obj, FlatCAMExcellon):
  4303. self.inform.emit('[ERROR_NOTCL] %s' %
  4304. _("Failed. Excellon joining works only on Excellon objects."))
  4305. return
  4306. if len(objs) < 2:
  4307. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4308. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4309. return 'fail'
  4310. def initialize(obj, app):
  4311. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=obj)
  4312. self.new_object("excellon", 'Combo_Excellon', initialize)
  4313. self.should_we_save = True
  4314. def on_edit_join_grb(self):
  4315. """
  4316. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4317. a new Gerber object.
  4318. :return: None
  4319. """
  4320. self.report_usage("on_edit_join_grb()")
  4321. objs = self.collection.get_selected()
  4322. for obj in objs:
  4323. if not isinstance(obj, FlatCAMGerber):
  4324. self.inform.emit('[ERROR_NOTCL] %s' %
  4325. _("Failed. Gerber joining works only on Gerber objects."))
  4326. return
  4327. if len(objs) < 2:
  4328. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4329. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4330. return 'fail'
  4331. def initialize(obj, app):
  4332. FlatCAMGerber.merge(self, grb_list=objs, grb_final=obj)
  4333. self.new_object("gerber", 'Combo_Gerber', initialize)
  4334. self.should_we_save = True
  4335. def on_convert_singlegeo_to_multigeo(self):
  4336. """
  4337. Called for converting a Geometry object from single-geo to multi-geo.
  4338. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4339. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4340. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4341. the solid-geometry of that tool.
  4342. :return: None
  4343. """
  4344. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4345. obj = self.collection.get_active()
  4346. if obj is None:
  4347. self.inform.emit('[ERROR_NOTCL] %s' %
  4348. _("Failed. Select a Geometry Object and try again."))
  4349. return
  4350. if not isinstance(obj, FlatCAMGeometry):
  4351. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4352. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4353. return
  4354. obj.multigeo = True
  4355. for tooluid, dict_value in obj.tools.items():
  4356. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4357. if not isinstance(obj.solid_geometry, list):
  4358. obj.solid_geometry = [obj.solid_geometry]
  4359. obj.solid_geometry[:] = []
  4360. obj.plot()
  4361. self.should_we_save = True
  4362. self.inform.emit('[success] %s' %
  4363. _("A Geometry object was converted to MultiGeo type."))
  4364. def on_convert_multigeo_to_singlegeo(self):
  4365. """
  4366. Called for converting a Geometry object from multi-geo to single-geo.
  4367. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4368. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4369. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4370. the solid-geometry of that tool.
  4371. :return: None
  4372. """
  4373. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4374. obj = self.collection.get_active()
  4375. if obj is None:
  4376. self.inform.emit('[ERROR_NOTCL] %s' %
  4377. _("Failed. Select a Geometry Object and try again."))
  4378. return
  4379. if not isinstance(obj, FlatCAMGeometry):
  4380. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4381. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4382. return
  4383. obj.multigeo = False
  4384. total_solid_geometry = []
  4385. for tooluid, dict_value in obj.tools.items():
  4386. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4387. # clear the original geometry
  4388. dict_value['solid_geometry'][:] = []
  4389. obj.solid_geometry = deepcopy(total_solid_geometry)
  4390. obj.plot()
  4391. self.should_we_save = True
  4392. self.inform.emit('[success] %s' %
  4393. _("A Geometry object was converted to SingleGeo type."))
  4394. def on_options_dict_change(self, field):
  4395. """
  4396. Called whenever a key changed in the self.options dictionary. This dict was used to store the preferences of the
  4397. current project. This feature is no longer used.
  4398. :param field:
  4399. :return:
  4400. """
  4401. self.options_write_form_field(field)
  4402. if field == "units":
  4403. self.set_screen_units(self.options['units'])
  4404. def on_defaults_dict_change(self, field):
  4405. """
  4406. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4407. Edit -> Preferences tab window.
  4408. :param field: the key of the self.defaults dictionary that was changed.
  4409. :return: None
  4410. """
  4411. self.defaults_write_form_field(field)
  4412. if field == "units":
  4413. self.set_screen_units(self.defaults['units'])
  4414. def set_screen_units(self, units):
  4415. """
  4416. Set the FlatCAM units on the status bar.
  4417. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4418. :return: None
  4419. """
  4420. self.ui.units_label.setText("[" + units.lower() + "]")
  4421. def on_toggle_units(self, no_pref=False):
  4422. """
  4423. Callback for the Units radio-button change in the Preferences tab.
  4424. Changes the application's default units adn for the project too.
  4425. If changing the project's units, the change propagates to all of
  4426. the objects in the project.
  4427. :return: None
  4428. """
  4429. self.report_usage("on_toggle_units")
  4430. if self.toggle_units_ignore:
  4431. return
  4432. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4433. # If option is the same, then ignore
  4434. if new_units == self.defaults["units"].upper():
  4435. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4436. return
  4437. # Options to scale
  4438. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  4439. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  4440. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4441. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  4442. "excellon_z_pdepth",
  4443. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4444. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4445. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  4446. "geometry_feedrate_probe",
  4447. 'cncjob_tooldia',
  4448. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4449. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia"
  4450. "tools_2sided_drilldia", "tools_film_boundary",
  4451. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4452. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4453. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4454. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4455. "tools_transform_offset_y",
  4456. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4457. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4458. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4459. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4460. 'global_gridx', 'global_gridy', 'global_snap_max']
  4461. def scale_options(sfactor):
  4462. for dim in dimensions:
  4463. if dim == 'excellon_toolchangexy':
  4464. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4465. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4466. coords_xy[0] *= sfactor
  4467. coords_xy[1] *= sfactor
  4468. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4469. elif dim == 'geometry_toolchangexy':
  4470. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4471. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4472. coords_xy[0] *= sfactor
  4473. coords_xy[1] *= sfactor
  4474. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4475. elif dim == 'geometry_cnctooldia':
  4476. tools_diameters = []
  4477. try:
  4478. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4479. tools_diameters = [eval(a) for a in tools_string if a != '']
  4480. except Exception as e:
  4481. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4482. self.options['geometry_cnctooldia'] = ''
  4483. for t in range(len(tools_diameters)):
  4484. tools_diameters[t] *= sfactor
  4485. self.options['geometry_cnctooldia'] += "%f," % tools_diameters[t]
  4486. elif dim == 'tools_ncctools':
  4487. ncctools = []
  4488. try:
  4489. tools_string = self.defaults["tools_ncctools"].split(",")
  4490. ncctools = [eval(a) for a in tools_string if a != '']
  4491. except Exception as e:
  4492. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4493. self.options['tools_ncctools'] = ''
  4494. for t in range(len(ncctools)):
  4495. ncctools[t] *= sfactor
  4496. self.options['tools_ncctools'] += "%f," % ncctools[t]
  4497. elif dim == 'tools_solderpaste_tools':
  4498. sptools = []
  4499. try:
  4500. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4501. sptools = [eval(a) for a in tools_string if a != '']
  4502. except Exception as e:
  4503. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4504. self.options['tools_solderpaste_tools'] = ""
  4505. for t in range(len(sptools)):
  4506. sptools[t] *= sfactor
  4507. self.options['tools_solderpaste_tools'] += "%f," % sptools[t]
  4508. elif dim == 'tools_solderpaste_xy_toolchange':
  4509. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4510. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4511. sp_coords[0] *= sfactor
  4512. sp_coords[1] *= sfactor
  4513. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  4514. elif dim == 'global_gridx' or dim == 'global_gridy':
  4515. if new_units == 'IN':
  4516. val = 0.1
  4517. try:
  4518. val = float(self.defaults[dim]) * sfactor
  4519. except Exception as e:
  4520. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4521. self.options[dim] = float('%.6f' % val)
  4522. else:
  4523. val = 0.1
  4524. try:
  4525. val = float(self.defaults[dim]) * sfactor
  4526. except Exception as e:
  4527. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4528. self.options[dim] = float('%.4f' % val)
  4529. else:
  4530. val = 0.1
  4531. try:
  4532. val = float(self.options[dim]) * sfactor
  4533. except Exception as e:
  4534. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  4535. self.options[dim] = val
  4536. def scale_defaults(sfactor):
  4537. for dim in dimensions:
  4538. if dim == 'excellon_toolchangexy':
  4539. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4540. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4541. coords_xy[0] *= sfactor
  4542. coords_xy[1] *= sfactor
  4543. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4544. elif dim == 'geometry_toolchangexy':
  4545. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4546. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4547. coords_xy[0] *= sfactor
  4548. coords_xy[1] *= sfactor
  4549. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4550. elif dim == 'geometry_cnctooldia':
  4551. tools_diameters = []
  4552. try:
  4553. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4554. tools_diameters = [eval(a) for a in tools_string if a != '']
  4555. except Exception as e:
  4556. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4557. self.defaults['geometry_cnctooldia'] = ''
  4558. for t in range(len(tools_diameters)):
  4559. tools_diameters[t] *= sfactor
  4560. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  4561. elif dim == 'tools_ncctools':
  4562. ncctools = []
  4563. try:
  4564. tools_string = self.defaults["tools_ncctools"].split(",")
  4565. ncctools = [eval(a) for a in tools_string if a != '']
  4566. except Exception as e:
  4567. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4568. self.defaults['tools_ncctools'] = ''
  4569. for t in range(len(ncctools)):
  4570. ncctools[t] *= sfactor
  4571. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  4572. elif dim == 'tools_solderpaste_tools':
  4573. sptools = []
  4574. try:
  4575. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4576. sptools = [eval(a) for a in tools_string if a != '']
  4577. except Exception as e:
  4578. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4579. self.defaults['tools_solderpaste_tools'] = ""
  4580. for t in range(len(sptools)):
  4581. sptools[t] *= sfactor
  4582. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  4583. elif dim == 'tools_solderpaste_xy_toolchange':
  4584. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4585. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4586. sp_coords[0] *= sfactor
  4587. sp_coords[1] *= sfactor
  4588. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  4589. elif dim == 'global_gridx' or dim == 'global_gridy':
  4590. if new_units == 'IN':
  4591. val = 0.1
  4592. try:
  4593. val = float(self.defaults[dim]) * sfactor
  4594. except Exception as e:
  4595. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4596. self.defaults[dim] = float('%.6f' % val)
  4597. else:
  4598. val = 0.1
  4599. try:
  4600. val = float(self.defaults[dim]) * sfactor
  4601. except Exception as e:
  4602. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4603. self.defaults[dim] = float('%.4f' % val)
  4604. else:
  4605. val = 0.1
  4606. try:
  4607. val = float(self.defaults[dim]) * sfactor
  4608. except Exception as e:
  4609. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4610. self.defaults[dim] = val
  4611. # The scaling factor depending on choice of units.
  4612. factor = 1/25.4
  4613. if new_units == 'MM':
  4614. factor = 25.4
  4615. # Changing project units. Warn user.
  4616. msgbox = QtWidgets.QMessageBox()
  4617. msgbox.setWindowTitle(_("Toggle Units"))
  4618. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  4619. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4620. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  4621. "properties of all objects to be scaled accordingly.\nContinue?"))
  4622. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4623. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4624. msgbox.setDefaultButton(bt_ok)
  4625. msgbox.exec_()
  4626. response = msgbox.clickedButton()
  4627. if response == bt_ok:
  4628. if no_pref is False:
  4629. self.options_read_form()
  4630. scale_options(factor)
  4631. self.options_write_form()
  4632. self.defaults_read_form()
  4633. scale_defaults(factor)
  4634. self.defaults_write_form(fl_units=new_units)
  4635. # save the defaults to file, some may assume that the conversion is enough and it's not
  4636. self.on_save_button()
  4637. self.should_we_save = True
  4638. # change this only if the workspace is active
  4639. if self.defaults['global_workspace'] is True:
  4640. self.plotcanvas.draw_workspace()
  4641. # adjust the grid values on the main toolbar
  4642. dec = 6 if new_units == 'IN'else 4
  4643. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  4644. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  4645. if not self.ui.grid_gap_link_cb.isChecked():
  4646. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  4647. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  4648. for obj in self.collection.get_list():
  4649. obj.convert_units(new_units)
  4650. # make that the properties stored in the object are also updated
  4651. self.object_changed.emit(obj)
  4652. obj.build_ui()
  4653. current = self.collection.get_active()
  4654. if current is not None:
  4655. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4656. if not isinstance(current, FlatCAMGeometry):
  4657. current.to_form()
  4658. self.plot_all()
  4659. self.inform.emit('[success] %s: %s' %
  4660. (_("Converted units to"), new_units))
  4661. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4662. self.set_screen_units(new_units)
  4663. else:
  4664. # Undo toggling
  4665. self.toggle_units_ignore = True
  4666. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4667. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4668. else:
  4669. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4670. self.toggle_units_ignore = False
  4671. self.inform.emit('[WARNING_NOTCL]%s' %
  4672. _(" Units conversion cancelled."))
  4673. self.options_read_form()
  4674. self.defaults_read_form()
  4675. def on_toggle_units_click(self):
  4676. try:
  4677. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4678. except (TypeError, AttributeError):
  4679. pass
  4680. if self.defaults["units"] == 'MM':
  4681. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4682. else:
  4683. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4684. self.on_toggle_units(no_pref=True)
  4685. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4686. lambda: self.on_toggle_units(no_pref=False))
  4687. def on_fullscreen(self):
  4688. self.report_usage("on_fullscreen()")
  4689. if self.toggle_fscreen is False:
  4690. # self.ui.showFullScreen()
  4691. self.ui.setWindowFlags(self.ui.windowFlags() | Qt.FramelessWindowHint)
  4692. a = self.ui.geometry()
  4693. self.x_pos = a.x()
  4694. self.y_pos = a.y()
  4695. self.width = a.width()
  4696. self.height = a.height()
  4697. # set new geometry to full desktop rect
  4698. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  4699. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  4700. # everything else will not work without this hack. This happen in Windows.
  4701. # https://bugreports.qt.io/browse/QTBUG-41309
  4702. desktop = QtWidgets.QApplication.desktop()
  4703. screen = desktop.screenNumber(QtGui.QCursor.pos())
  4704. rec = desktop.screenGeometry(screen)
  4705. x = rec.x() - 1
  4706. y = rec.y() - 1
  4707. h = rec.height() + 2
  4708. w = rec.width() + 2
  4709. self.ui.setGeometry(x, y, w, h)
  4710. self.ui.show()
  4711. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4712. tb.setVisible(False)
  4713. self.ui.splitter_left.setVisible(False)
  4714. self.toggle_fscreen = True
  4715. else:
  4716. self.ui.setWindowFlags(self.ui.windowFlags() & ~Qt.FramelessWindowHint)
  4717. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  4718. self.ui.showNormal()
  4719. self.restore_toolbar_view()
  4720. self.ui.splitter_left.setVisible(True)
  4721. self.toggle_fscreen = False
  4722. def on_toggle_plotarea(self):
  4723. self.report_usage("on_toggle_plotarea()")
  4724. try:
  4725. name = self.ui.plot_tab_area.widget(0).objectName()
  4726. except AttributeError:
  4727. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4728. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4729. self.ui.plot_tab_area.protectTab(0)
  4730. return
  4731. if name != 'plotarea':
  4732. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4733. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4734. self.ui.plot_tab_area.protectTab(0)
  4735. else:
  4736. self.ui.plot_tab_area.closeTab(0)
  4737. def on_toggle_notebook(self):
  4738. if self.ui.splitter.sizes()[0] == 0:
  4739. self.ui.splitter.setSizes([1, 1])
  4740. else:
  4741. self.ui.splitter.setSizes([0, 1])
  4742. def on_toggle_axis(self):
  4743. self.report_usage("on_toggle_axis()")
  4744. if self.toggle_axis is False:
  4745. if self.is_legacy is False:
  4746. # self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4747. # self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4748. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  4749. parent=self.plotcanvas.view.scene)
  4750. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  4751. parent=self.plotcanvas.view.scene)
  4752. # self.plotcanvas.redraw()
  4753. else:
  4754. self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  4755. self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  4756. self.plotcanvas.canvas.draw()
  4757. pass
  4758. self.toggle_axis = True
  4759. else:
  4760. if self.is_legacy is False:
  4761. # self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4762. # self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4763. # self.plotcanvas.redraw()
  4764. self.plotcanvas.v_line.parent = None
  4765. self.plotcanvas.h_line.parent = None
  4766. else:
  4767. self.plotcanvas.axes.lines[:] = []
  4768. self.plotcanvas.canvas.draw()
  4769. self.toggle_axis = False
  4770. def on_toggle_grid(self):
  4771. self.report_usage("on_toggle_grid()")
  4772. self.ui.grid_snap_btn.trigger()
  4773. def on_options_combo_change(self, sel):
  4774. """
  4775. Called when the combo box to choose between application defaults and
  4776. project option changes value. The corresponding variables are
  4777. copied to the UI.
  4778. :param sel: The option index that was chosen.
  4779. :return: None
  4780. """
  4781. # combo_sel = self.ui.notebook.combo_options.get_active()
  4782. App.log.debug("Options --> %s" % sel)
  4783. # form = [self.defaults_form, self.options_form][sel]
  4784. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  4785. if sel == 0:
  4786. self.gen_form = self.ui.general_defaults_form
  4787. self.ger_form = self.ui.gerber_defaults_form
  4788. self.exc_form = self.ui.excellon_defaults_form
  4789. self.geo_form = self.ui.geometry_defaults_form
  4790. self.cnc_form = self.ui.cncjob_defaults_form
  4791. self.tools_form = self.ui.tools_defaults_form
  4792. self.fa_form = self.ui.util_defaults_form
  4793. elif sel == 1:
  4794. self.gen_form = self.ui.general_options_form
  4795. self.ger_form = self.ui.gerber_options_form
  4796. self.exc_form = self.ui.excellon_options_form
  4797. self.geo_form = self.ui.geometry_options_form
  4798. self.cnc_form = self.ui.cncjob_options_form
  4799. self.tools_form = self.ui.tools_options_form
  4800. self.fa_form = self.ui.util_options_form
  4801. else:
  4802. return
  4803. try:
  4804. self.ui.general_scroll_area.takeWidget()
  4805. except:
  4806. self.log.debug("Nothing to remove")
  4807. self.ui.general_scroll_area.setWidget(self.gen_form)
  4808. self.gen_form.show()
  4809. try:
  4810. self.ui.gerber_scroll_area.takeWidget()
  4811. except:
  4812. self.log.debug("Nothing to remove")
  4813. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  4814. self.ger_form.show()
  4815. try:
  4816. self.ui.excellon_scroll_area.takeWidget()
  4817. except:
  4818. self.log.debug("Nothing to remove")
  4819. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  4820. self.exc_form.show()
  4821. try:
  4822. self.ui.geometry_scroll_area.takeWidget()
  4823. except:
  4824. self.log.debug("Nothing to remove")
  4825. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  4826. self.geo_form.show()
  4827. try:
  4828. self.ui.cncjob_scroll_area.takeWidget()
  4829. except:
  4830. self.log.debug("Nothing to remove")
  4831. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  4832. self.cnc_form.show()
  4833. try:
  4834. self.ui.tools_scroll_area.takeWidget()
  4835. except:
  4836. self.log.debug("Nothing to remove")
  4837. self.ui.tools_scroll_area.setWidget(self.tools_form)
  4838. self.tools_form.show()
  4839. try:
  4840. self.ui.fa_scroll_area.takeWidget()
  4841. except:
  4842. self.log.debug("Nothing to remove")
  4843. self.ui.fa_scroll_area.setWidget(self.fa_form)
  4844. self.fa_form.show()
  4845. self.log.debug("Finished GUI form initialization.")
  4846. # self.options2form()
  4847. def on_excellon_defaults_button(self):
  4848. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  4849. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  4850. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  4851. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  4852. self.defaults_form_fields["excellon_zeros"].set_value('L')
  4853. self.defaults_form_fields["excellon_units"].set_value('INCH')
  4854. log.debug("Excellon app defaults loaded ...")
  4855. def on_excellon_options_button(self):
  4856. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  4857. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  4858. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  4859. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  4860. self.options_form_fields["excellon_zeros"].set_value('L')
  4861. self.options_form_fields["excellon_units"].set_value('INCH')
  4862. log.debug("Excellon options defaults loaded ...")
  4863. def on_update_exc_export(self, state):
  4864. """
  4865. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  4866. if the update_excellon_cb checkbox is checked
  4867. :param state: state of the checkbox whose signals is tied to his slot
  4868. :return:
  4869. """
  4870. if state:
  4871. # first try to disconnect
  4872. try:
  4873. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.\
  4874. disconnect(self.on_excellon_format_changed)
  4875. except TypeError:
  4876. pass
  4877. try:
  4878. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged.\
  4879. disconnect(self.on_excellon_format_changed)
  4880. except TypeError:
  4881. pass
  4882. try:
  4883. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged.\
  4884. disconnect(self.on_excellon_format_changed)
  4885. except TypeError:
  4886. pass
  4887. try:
  4888. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged.\
  4889. disconnect(self.on_excellon_format_changed)
  4890. except TypeError:
  4891. pass
  4892. try:
  4893. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  4894. disconnect(self.on_excellon_zeros_changed)
  4895. except TypeError:
  4896. pass
  4897. try:
  4898. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  4899. disconnect(self.on_excellon_zeros_changed)
  4900. except TypeError:
  4901. pass
  4902. # the connect them
  4903. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.connect(
  4904. self.on_excellon_format_changed)
  4905. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged.connect(
  4906. self.on_excellon_format_changed)
  4907. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged.connect(
  4908. self.on_excellon_format_changed)
  4909. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged.connect(
  4910. self.on_excellon_format_changed)
  4911. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  4912. self.on_excellon_zeros_changed)
  4913. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  4914. self.on_excellon_units_changed)
  4915. else:
  4916. # disconnect the signals
  4917. try:
  4918. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged. \
  4919. disconnect(self.on_excellon_format_changed)
  4920. except TypeError:
  4921. pass
  4922. try:
  4923. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged. \
  4924. disconnect(self.on_excellon_format_changed)
  4925. except TypeError:
  4926. pass
  4927. try:
  4928. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged. \
  4929. disconnect(self.on_excellon_format_changed)
  4930. except TypeError:
  4931. pass
  4932. try:
  4933. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged. \
  4934. disconnect(self.on_excellon_format_changed)
  4935. except TypeError:
  4936. pass
  4937. try:
  4938. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  4939. disconnect(self.on_excellon_zeros_changed)
  4940. except TypeError:
  4941. pass
  4942. try:
  4943. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  4944. disconnect(self.on_excellon_zeros_changed)
  4945. except TypeError:
  4946. pass
  4947. def on_excellon_format_changed(self):
  4948. """
  4949. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  4950. :return: None
  4951. """
  4952. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  4953. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4954. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  4955. )
  4956. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4957. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  4958. )
  4959. else:
  4960. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4961. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  4962. )
  4963. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4964. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  4965. )
  4966. def on_excellon_zeros_changed(self):
  4967. """
  4968. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  4969. :return: None
  4970. """
  4971. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  4972. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  4973. )
  4974. def on_excellon_units_changed(self):
  4975. """
  4976. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  4977. :return: None
  4978. """
  4979. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  4980. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  4981. )
  4982. self.on_excellon_format_changed()
  4983. # Setting plot colors handlers
  4984. def on_pf_color_entry(self):
  4985. self.defaults['global_plot_fill'] = \
  4986. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  4987. self.defaults['global_plot_fill'][7:9]
  4988. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4989. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  4990. def on_pf_color_button(self):
  4991. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  4992. c_dialog = QtWidgets.QColorDialog()
  4993. plot_fill_color = c_dialog.getColor(initial=current_color)
  4994. if plot_fill_color.isValid() is False:
  4995. return
  4996. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4997. "background-color:%s" % str(plot_fill_color.name()))
  4998. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  4999. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  5000. self.defaults['global_plot_fill'] = new_val
  5001. def on_pf_color_spinner(self):
  5002. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  5003. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  5004. self.defaults['global_plot_fill'] = \
  5005. self.defaults['global_plot_fill'][:7] + \
  5006. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5007. self.defaults['global_plot_line'] = \
  5008. self.defaults['global_plot_line'][:7] + \
  5009. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5010. def on_pf_color_slider(self):
  5011. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  5012. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  5013. def on_pl_color_entry(self):
  5014. self.defaults['global_plot_line'] = \
  5015. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  5016. self.defaults['global_plot_line'][7:9]
  5017. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5018. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  5019. def on_pl_color_button(self):
  5020. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  5021. # print(current_color)
  5022. c_dialog = QtWidgets.QColorDialog()
  5023. plot_line_color = c_dialog.getColor(initial=current_color)
  5024. if plot_line_color.isValid() is False:
  5025. return
  5026. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5027. "background-color:%s" % str(plot_line_color.name()))
  5028. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  5029. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  5030. self.defaults['global_plot_line'] = new_val_line
  5031. # Setting selection colors (left - right) handlers
  5032. def on_sf_color_entry(self):
  5033. self.defaults['global_sel_fill'] = \
  5034. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  5035. self.defaults['global_sel_fill'][7:9]
  5036. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5037. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  5038. def on_sf_color_button(self):
  5039. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  5040. c_dialog = QtWidgets.QColorDialog()
  5041. plot_fill_color = c_dialog.getColor(initial=current_color)
  5042. if plot_fill_color.isValid() is False:
  5043. return
  5044. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5045. "background-color:%s" % str(plot_fill_color.name()))
  5046. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  5047. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  5048. self.defaults['global_sel_fill'] = new_val
  5049. def on_sf_color_spinner(self):
  5050. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  5051. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  5052. self.defaults['global_sel_fill'] = \
  5053. self.defaults['global_sel_fill'][:7] + \
  5054. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5055. self.defaults['global_sel_line'] = \
  5056. self.defaults['global_sel_line'][:7] + \
  5057. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5058. def on_sf_color_slider(self):
  5059. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  5060. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  5061. def on_sl_color_entry(self):
  5062. self.defaults['global_sel_line'] = \
  5063. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  5064. self.defaults['global_sel_line'][7:9]
  5065. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5066. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  5067. def on_sl_color_button(self):
  5068. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  5069. c_dialog = QtWidgets.QColorDialog()
  5070. plot_line_color = c_dialog.getColor(initial=current_color)
  5071. if plot_line_color.isValid() is False:
  5072. return
  5073. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5074. "background-color:%s" % str(plot_line_color.name()))
  5075. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  5076. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  5077. self.defaults['global_sel_line'] = new_val_line
  5078. # Setting selection colors (right - left) handlers
  5079. def on_alt_sf_color_entry(self):
  5080. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  5081. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  5082. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5083. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  5084. def on_alt_sf_color_button(self):
  5085. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  5086. c_dialog = QtWidgets.QColorDialog()
  5087. plot_fill_color = c_dialog.getColor(initial=current_color)
  5088. if plot_fill_color.isValid() is False:
  5089. return
  5090. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5091. "background-color:%s" % str(plot_fill_color.name()))
  5092. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  5093. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  5094. self.defaults['global_alt_sel_fill'] = new_val
  5095. def on_alt_sf_color_spinner(self):
  5096. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  5097. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  5098. self.defaults['global_alt_sel_fill'] = \
  5099. self.defaults['global_alt_sel_fill'][:7] + \
  5100. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5101. self.defaults['global_alt_sel_line'] = \
  5102. self.defaults['global_alt_sel_line'][:7] + \
  5103. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5104. def on_alt_sf_color_slider(self):
  5105. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  5106. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  5107. def on_alt_sl_color_entry(self):
  5108. self.defaults['global_alt_sel_line'] = \
  5109. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  5110. self.defaults['global_alt_sel_line'][7:9]
  5111. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5112. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  5113. def on_alt_sl_color_button(self):
  5114. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  5115. c_dialog = QtWidgets.QColorDialog()
  5116. plot_line_color = c_dialog.getColor(initial=current_color)
  5117. if plot_line_color.isValid() is False:
  5118. return
  5119. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5120. "background-color:%s" % str(plot_line_color.name()))
  5121. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  5122. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  5123. self.defaults['global_alt_sel_line'] = new_val_line
  5124. # Setting Editor colors
  5125. def on_draw_color_entry(self):
  5126. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5127. .draw_color_entry.get_value()
  5128. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5129. "background-color:%s" % str(self.defaults['global_draw_color']))
  5130. def on_draw_color_button(self):
  5131. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  5132. c_dialog = QtWidgets.QColorDialog()
  5133. draw_color = c_dialog.getColor(initial=current_color)
  5134. if draw_color.isValid() is False:
  5135. return
  5136. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5137. "background-color:%s" % str(draw_color.name()))
  5138. new_val = str(draw_color.name())
  5139. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  5140. self.defaults['global_draw_color'] = new_val
  5141. def on_sel_draw_color_entry(self):
  5142. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5143. .sel_draw_color_entry.get_value()
  5144. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5145. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  5146. def on_sel_draw_color_button(self):
  5147. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  5148. c_dialog = QtWidgets.QColorDialog()
  5149. sel_draw_color = c_dialog.getColor(initial=current_color)
  5150. if sel_draw_color.isValid() is False:
  5151. return
  5152. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5153. "background-color:%s" % str(sel_draw_color.name()))
  5154. new_val_sel = str(sel_draw_color.name())
  5155. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  5156. self.defaults['global_sel_draw_color'] = new_val_sel
  5157. def on_proj_color_entry(self):
  5158. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  5159. .proj_color_entry.get_value()
  5160. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5161. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  5162. def on_proj_color_button(self):
  5163. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  5164. c_dialog = QtWidgets.QColorDialog()
  5165. proj_color = c_dialog.getColor(initial=current_color)
  5166. if proj_color.isValid() is False:
  5167. return
  5168. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5169. "background-color:%s" % str(proj_color.name()))
  5170. new_val_sel = str(proj_color.name())
  5171. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  5172. self.defaults['global_proj_item_color'] = new_val_sel
  5173. def on_proj_color_dis_entry(self):
  5174. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  5175. .proj_color_dis_entry.get_value()
  5176. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5177. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  5178. def on_proj_color_dis_button(self):
  5179. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  5180. c_dialog = QtWidgets.QColorDialog()
  5181. proj_color = c_dialog.getColor(initial=current_color)
  5182. if proj_color.isValid() is False:
  5183. return
  5184. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5185. "background-color:%s" % str(proj_color.name()))
  5186. new_val_sel = str(proj_color.name())
  5187. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  5188. self.defaults['global_proj_item_dis_color'] = new_val_sel
  5189. def on_annotation_fontcolor_entry(self):
  5190. self.defaults['cncjob_annotation_fontcolor'] = \
  5191. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.get_value()
  5192. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5193. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  5194. def on_annotation_fontcolor_button(self):
  5195. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  5196. c_dialog = QtWidgets.QColorDialog()
  5197. annotation_color = c_dialog.getColor(initial=current_color)
  5198. if annotation_color.isValid() is False:
  5199. return
  5200. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5201. "background-color:%s" % str(annotation_color.name()))
  5202. new_val_sel = str(annotation_color.name())
  5203. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(new_val_sel)
  5204. self.defaults['cncjob_annotation_fontcolor'] = new_val_sel
  5205. def on_film_color_entry(self):
  5206. self.defaults['tools_film_color'] = \
  5207. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  5208. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5209. "background-color:%s" % str(self.defaults['tools_film_color']))
  5210. def on_film_color_button(self):
  5211. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  5212. c_dialog = QtWidgets.QColorDialog()
  5213. film_color = c_dialog.getColor(initial=current_color)
  5214. if film_color.isValid() is False:
  5215. return
  5216. # if new color is different then mark that the Preferences are changed
  5217. if film_color != current_color:
  5218. self.on_preferences_edited()
  5219. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5220. "background-color:%s" % str(film_color.name()))
  5221. new_val_sel = str(film_color.name())
  5222. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  5223. self.defaults['tools_film_color'] = new_val_sel
  5224. def on_splash_changed(self, state):
  5225. settings = QSettings("Open Source", "FlatCAM")
  5226. settings.setValue('splash_screen', 1) if state else settings.setValue('splash_screen', 0)
  5227. # This will write the setting to the platform specific storage.
  5228. del settings
  5229. def on_notebook_tab_rmb_click(self, checked):
  5230. self.ui.notebook.set_detachable(val=checked)
  5231. self.defaults["global_tabs_detachable"] = checked
  5232. self.ui.plot_tab_area.set_detachable(val=checked)
  5233. self.defaults["global_tabs_detachable"] = checked
  5234. def on_deselect_all(self):
  5235. self.collection.set_all_inactive()
  5236. self.delete_selection_shape()
  5237. def on_workspace_modified(self):
  5238. self.save_defaults(silent=True)
  5239. self.plotcanvas.draw_workspace()
  5240. def on_workspace(self):
  5241. self.report_usage("on_workspace()")
  5242. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5243. self.plotcanvas.restore_workspace()
  5244. else:
  5245. self.plotcanvas.delete_workspace()
  5246. self.save_defaults(silent=True)
  5247. def on_workspace_menu(self):
  5248. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5249. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  5250. else:
  5251. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  5252. self.on_workspace()
  5253. def on_layout(self, index=None, lay=None):
  5254. self.report_usage("on_layout()")
  5255. if lay:
  5256. current_layout = lay
  5257. else:
  5258. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  5259. settings = QSettings("Open Source", "FlatCAM")
  5260. settings.setValue('layout', current_layout)
  5261. # This will write the setting to the platform specific storage.
  5262. del settings
  5263. # first remove the toolbars:
  5264. try:
  5265. self.ui.removeToolBar(self.ui.toolbarfile)
  5266. self.ui.removeToolBar(self.ui.toolbargeo)
  5267. self.ui.removeToolBar(self.ui.toolbarview)
  5268. self.ui.removeToolBar(self.ui.toolbarshell)
  5269. self.ui.removeToolBar(self.ui.toolbartools)
  5270. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  5271. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  5272. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  5273. self.ui.removeToolBar(self.ui.snap_toolbar)
  5274. self.ui.removeToolBar(self.ui.toolbarshell)
  5275. except Exception as e:
  5276. pass
  5277. if current_layout == 'standard':
  5278. # ## TOOLBAR INSTALLATION # ##
  5279. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5280. self.ui.toolbarfile.setObjectName('File_TB')
  5281. self.ui.addToolBar(self.ui.toolbarfile)
  5282. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5283. self.ui.toolbargeo.setObjectName('Edit_TB')
  5284. self.ui.addToolBar(self.ui.toolbargeo)
  5285. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5286. self.ui.toolbarview.setObjectName('View_TB')
  5287. self.ui.addToolBar(self.ui.toolbarview)
  5288. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5289. self.ui.toolbarshell.setObjectName('Shell_TB')
  5290. self.ui.addToolBar(self.ui.toolbarshell)
  5291. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5292. self.ui.toolbartools.setObjectName('Tools_TB')
  5293. self.ui.addToolBar(self.ui.toolbartools)
  5294. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5295. # self.ui.exc_edit_toolbar.setVisible(False)
  5296. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5297. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  5298. self.ui.addToolBarBreak()
  5299. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5300. # self.ui.geo_edit_toolbar.setVisible(False)
  5301. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5302. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  5303. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5304. # self.ui.grb_edit_toolbar.setVisible(False)
  5305. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5306. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  5307. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5308. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5309. # self.ui.snap_toolbar.setMaximumHeight(30)
  5310. self.ui.addToolBar(self.ui.snap_toolbar)
  5311. self.ui.corner_snap_btn.setVisible(False)
  5312. self.ui.snap_magnet.setVisible(False)
  5313. elif current_layout == 'compact':
  5314. # ## TOOLBAR INSTALLATION # ##
  5315. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5316. self.ui.toolbarfile.setObjectName('File_TB')
  5317. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  5318. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5319. self.ui.toolbargeo.setObjectName('Edit_TB')
  5320. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  5321. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5322. self.ui.toolbarshell.setObjectName('Shell_TB')
  5323. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  5324. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5325. self.ui.toolbartools.setObjectName('Tools_TB')
  5326. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  5327. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5328. # self.ui.geo_edit_toolbar.setVisible(False)
  5329. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5330. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  5331. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5332. self.ui.toolbarview.setObjectName('View_TB')
  5333. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  5334. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  5335. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5336. # self.ui.grb_edit_toolbar.setVisible(False)
  5337. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5338. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  5339. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5340. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5341. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  5342. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5343. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5344. self.ui.snap_toolbar.setMaximumHeight(30)
  5345. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  5346. self.ui.corner_snap_btn.setVisible(True)
  5347. self.ui.snap_magnet.setVisible(True)
  5348. # add all the actions to the toolbars
  5349. self.ui.populate_toolbars()
  5350. # reconnect all the signals to the toolbar actions
  5351. self.connect_toolbar_signals()
  5352. self.ui.grid_snap_btn.setChecked(True)
  5353. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  5354. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  5355. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  5356. self.ui.grid_gap_link_cb.setChecked(True)
  5357. def on_cnc_custom_parameters(self, signal_text):
  5358. if signal_text == 'Parameters':
  5359. return
  5360. else:
  5361. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  5362. def on_save_button(self):
  5363. log.debug("App.on_save_button() --> Saving preferences to file.")
  5364. self.preferences_changed_flag = False
  5365. self.save_defaults(silent=False)
  5366. # load the defaults so they are updated into the app
  5367. self.load_defaults(filename='current_defaults')
  5368. # Re-fresh project options
  5369. self.on_options_app2project()
  5370. settings = QSettings("Open Source", "FlatCAM")
  5371. # save the notebook font size
  5372. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  5373. settings.setValue('notebook_font_size', fsize)
  5374. # save the axis font size
  5375. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  5376. settings.setValue('axis_font_size', g_fsize)
  5377. # save the textbox font size
  5378. tb_fsize = self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  5379. settings.setValue('textbox_font_size', tb_fsize)
  5380. # This will write the setting to the platform specific storage.
  5381. del settings
  5382. def handlePrint(self):
  5383. self.report_usage("handlePrint()")
  5384. dialog = QtPrintSupport.QPrintDialog()
  5385. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  5386. self.ui.code_editor.document().print_(dialog.printer())
  5387. def handlePreview(self):
  5388. self.report_usage("handlePreview()")
  5389. dialog = QtPrintSupport.QPrintPreviewDialog()
  5390. dialog.paintRequested.connect(self.ui.code_editor.print_)
  5391. dialog.exec_()
  5392. def handleTextChanged(self):
  5393. # enable = not self.ui.code_editor.document().isEmpty()
  5394. # self.ui.buttonPrint.setEnabled(enable)
  5395. # self.ui.buttonPreview.setEnabled(enable)
  5396. pass
  5397. def handleOpen(self, filt=None):
  5398. self.report_usage("handleOpen()")
  5399. if filt:
  5400. _filter_ = filt
  5401. else:
  5402. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  5403. "All Files (*.*)"
  5404. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  5405. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  5406. if path:
  5407. file = QtCore.QFile(path)
  5408. if file.open(QtCore.QIODevice.ReadOnly):
  5409. stream = QtCore.QTextStream(file)
  5410. self.gcode_edited = stream.readAll()
  5411. self.ui.code_editor.setPlainText(self.gcode_edited)
  5412. file.close()
  5413. def handleSaveGCode(self, name=None, filt=None):
  5414. self.report_usage("handleSaveGCode()")
  5415. if filt:
  5416. _filter_ = filt
  5417. else:
  5418. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  5419. "All Files (*.*)"
  5420. if name:
  5421. obj_name = name
  5422. else:
  5423. try:
  5424. obj_name = self.collection.get_active().options['name']
  5425. except AttributeError:
  5426. obj_name = 'file'
  5427. if filt is None:
  5428. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  5429. try:
  5430. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  5431. caption=_("Export G-Code ..."),
  5432. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  5433. filter=_filter_
  5434. )[0])
  5435. except TypeError:
  5436. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  5437. if filename == "":
  5438. self.inform.emit('[WARNING_NOTCL] %s' %
  5439. _("Export Code cancelled."))
  5440. return
  5441. else:
  5442. try:
  5443. my_gcode = self.ui.code_editor.toPlainText()
  5444. with open(filename, 'w') as f:
  5445. for line in my_gcode:
  5446. f.write(line)
  5447. except FileNotFoundError:
  5448. self.inform.emit('[WARNING] %s' %
  5449. _("No such file or directory"))
  5450. return
  5451. except PermissionError:
  5452. self.inform.emit('[WARNING] %s' %
  5453. _("Permission denied, saving not possible.\n"
  5454. "Most likely another app is holding the file open and not accessible."))
  5455. return
  5456. # Just for adding it to the recent files list.
  5457. if self.defaults["global_open_style"] is False:
  5458. self.file_opened.emit("cncjob", filename)
  5459. self.file_saved.emit("cncjob", filename)
  5460. self.inform.emit('%s: %s' % (_("Saved to"), str(filename)))
  5461. def handleFindGCode(self):
  5462. self.report_usage("handleFindGCode()")
  5463. flags = QtGui.QTextDocument.FindCaseSensitively
  5464. text_to_be_found = self.ui.entryFind.get_value()
  5465. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  5466. if r is False:
  5467. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5468. def handleReplaceGCode(self):
  5469. self.report_usage("handleReplaceGCode()")
  5470. old = self.ui.entryFind.get_value()
  5471. new = self.ui.entryReplace.get_value()
  5472. if self.ui.sel_all_cb.isChecked():
  5473. while True:
  5474. cursor = self.ui.code_editor.textCursor()
  5475. cursor.beginEditBlock()
  5476. flags = QtGui.QTextDocument.FindCaseSensitively
  5477. # self.ui.editor is the QPlainTextEdit
  5478. r = self.ui.code_editor.find(str(old), flags)
  5479. if r:
  5480. qc = self.ui.code_editor.textCursor()
  5481. if qc.hasSelection():
  5482. qc.insertText(new)
  5483. else:
  5484. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5485. break
  5486. # Mark end of undo block
  5487. cursor.endEditBlock()
  5488. else:
  5489. cursor = self.ui.code_editor.textCursor()
  5490. cursor.beginEditBlock()
  5491. qc = self.ui.code_editor.textCursor()
  5492. if qc.hasSelection():
  5493. qc.insertText(new)
  5494. # Mark end of undo block
  5495. cursor.endEditBlock()
  5496. def handleCopyAll(self):
  5497. text = self.ui.code_editor.toPlainText()
  5498. self.clipboard.setText(text)
  5499. self.inform.emit(_("Code Editor content copied to clipboard ..."))
  5500. def handleRunCode(self):
  5501. # trying to run a Tcl command without having the Shell open will create some warnings because the Tcl Shell
  5502. # tries to print on a hidden widget, therefore show the dock if hidden
  5503. if self.ui.shell_dock.isHidden():
  5504. self.ui.shell_dock.show()
  5505. self.script_code = deepcopy(self.ui.code_editor.toPlainText())
  5506. # self.shell._sysShell.exec_command(script_code)
  5507. old_line = ''
  5508. for tcl_command_line in self.script_code.splitlines():
  5509. # do not process lines starting with '#' = comment and empty lines
  5510. if not tcl_command_line.startswith('#') and tcl_command_line != '':
  5511. # id FlatCAM is run in Windows then replace all the slashes with
  5512. # the UNIX style slash that TCL understands
  5513. if sys.platform == 'win32':
  5514. if "open" in tcl_command_line:
  5515. tcl_command_line = tcl_command_line.replace('\\', '/')
  5516. if old_line != '':
  5517. new_command = old_line + tcl_command_line + '\n'
  5518. else:
  5519. new_command = tcl_command_line
  5520. # execute the actual Tcl command
  5521. try:
  5522. self.shell.open_proccessing() # Disables input box.
  5523. result = self.tcl.eval(str(new_command))
  5524. if result != 'None':
  5525. self.shell.append_output(result + '\n')
  5526. old_line = ''
  5527. except tk.TclError:
  5528. old_line = old_line + tcl_command_line + '\n'
  5529. except Exception as e:
  5530. log.debug("App.handleRunCode() --> %s" % str(e))
  5531. if old_line != '':
  5532. # it means that the script finished with an error
  5533. result = self.tcl.eval("set errorInfo")
  5534. self.log.error("Exec command Exception: %s" % (result + '\n'))
  5535. self.shell.append_error('ERROR: ' + result + '\n')
  5536. self.shell.close_proccessing()
  5537. def on_tool_add_keypress(self):
  5538. # ## Current application units in Upper Case
  5539. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5540. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5541. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5542. if notebook_widget_name == 'selected_tab':
  5543. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5544. # Tool add works for Geometry only if Advanced is True in Preferences
  5545. if self.defaults["global_app_level"] == 'a':
  5546. tool_add_popup = FCInputDialog(title="New Tool ...",
  5547. text='Enter a Tool Diameter:',
  5548. min=0.0000, max=99.9999, decimals=4)
  5549. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5550. val, ok = tool_add_popup.get_value()
  5551. if ok:
  5552. if float(val) == 0:
  5553. self.inform.emit('[WARNING_NOTCL] %s' %
  5554. _("Please enter a tool diameter with non-zero value, in Float format."))
  5555. return
  5556. self.collection.get_active().on_tool_add(dia=float(val))
  5557. else:
  5558. self.inform.emit('[WARNING_NOTCL] %s...' %
  5559. _("Adding Tool cancelled"))
  5560. else:
  5561. msgbox = QtWidgets.QMessageBox()
  5562. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5563. "Go to Preferences -> General - Show Advanced Options."))
  5564. msgbox.setWindowTitle("Tool adding ...")
  5565. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  5566. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5567. msgbox.setDefaultButton(bt_ok)
  5568. msgbox.exec_()
  5569. # work only if the notebook tab on focus is the Tools_Tab
  5570. if notebook_widget_name == 'tool_tab':
  5571. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5572. tool_add_popup = FCInputDialog(title="New Tool ...",
  5573. text='Enter a Tool Diameter:',
  5574. min=0.0000, max=99.9999, decimals=4)
  5575. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5576. val, ok = tool_add_popup.get_value()
  5577. # and only if the tool is NCC Tool
  5578. if tool_widget == self.ncclear_tool.toolName:
  5579. if ok:
  5580. if float(val) == 0:
  5581. self.inform.emit('[WARNING_NOTCL] %s' %
  5582. _("Please enter a tool diameter with non-zero value, in Float format."))
  5583. return
  5584. self.ncclear_tool.on_tool_add(dia=float(val))
  5585. else:
  5586. self.inform.emit('[WARNING_NOTCL] %s...' %
  5587. _("Adding Tool cancelled"))
  5588. # and only if the tool is Paint Area Tool
  5589. elif tool_widget == self.paint_tool.toolName:
  5590. if ok:
  5591. if float(val) == 0:
  5592. self.inform.emit('[WARNING_NOTCL] %s' %
  5593. _("Please enter a tool diameter with non-zero value, in Float format."))
  5594. return
  5595. self.paint_tool.on_tool_add(dia=float(val))
  5596. else:
  5597. self.inform.emit('[WARNING_NOTCL] %s...' %
  5598. _("Adding Tool cancelled"))
  5599. # and only if the tool is Solder Paste Dispensing Tool
  5600. elif tool_widget == self.paste_tool.toolName:
  5601. if ok:
  5602. if float(val) == 0:
  5603. self.inform.emit('[WARNING_NOTCL] %s' %
  5604. _("Please enter a tool diameter with non-zero value, in Float format."))
  5605. return
  5606. self.paste_tool.on_tool_add(dia=float(val))
  5607. else:
  5608. self.inform.emit('[WARNING_NOTCL] %s...' %
  5609. _("Adding Tool cancelled"))
  5610. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5611. # See description bellow.
  5612. def on_delete_keypress(self):
  5613. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5614. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5615. if notebook_widget_name == 'selected_tab':
  5616. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5617. self.collection.get_active().on_tool_delete()
  5618. # work only if the notebook tab on focus is the Tools_Tab
  5619. elif notebook_widget_name == 'tool_tab':
  5620. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5621. # and only if the tool is NCC Tool
  5622. if tool_widget == self.ncclear_tool.toolName:
  5623. self.ncclear_tool.on_tool_delete()
  5624. # and only if the tool is Paint Tool
  5625. elif tool_widget == self.paint_tool.toolName:
  5626. self.paint_tool.on_tool_delete()
  5627. # and only if the tool is Solder Paste Dispensing Tool
  5628. elif tool_widget == self.paste_tool.toolName:
  5629. self.paste_tool.on_tool_delete()
  5630. else:
  5631. self.on_delete()
  5632. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5633. # some screens you have to be careful where you hover with your mouse.
  5634. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5635. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5636. # Complicated, I know :)
  5637. def on_delete(self):
  5638. """
  5639. Delete the currently selected FlatCAMObjs.
  5640. :return: None
  5641. """
  5642. self.report_usage("on_delete()")
  5643. response = None
  5644. bt_ok = None
  5645. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5646. # a geometry object before we update it.
  5647. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5648. and self.grb_editor.editor_active is False:
  5649. if self.defaults["global_delete_confirmation"] is True:
  5650. msgbox = QtWidgets.QMessageBox()
  5651. msgbox.setWindowTitle(_("Delete objects"))
  5652. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  5653. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5654. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5655. "the selected objects?"))
  5656. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5657. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5658. msgbox.setDefaultButton(bt_ok)
  5659. msgbox.exec_()
  5660. response = msgbox.clickedButton()
  5661. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  5662. if self.collection.get_active():
  5663. self.log.debug("App.on_delete()")
  5664. while self.collection.get_active():
  5665. obj_active = self.collection.get_active()
  5666. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  5667. if isinstance(obj_active, FlatCAMGerber):
  5668. for el in obj_active.mark_shapes:
  5669. obj_active.mark_shapes[el].clear(update=True)
  5670. obj_active.mark_shapes[el].enabled = False
  5671. # obj_active.mark_shapes[el] = None
  5672. del el
  5673. elif isinstance(obj_active, FlatCAMCNCjob):
  5674. try:
  5675. obj_active.annotation.clear(update=True)
  5676. obj_active.annotation.enabled = False
  5677. except AttributeError:
  5678. pass
  5679. self.delete_first_selected()
  5680. self.inform.emit('%s...' %
  5681. _("Object(s) deleted"))
  5682. # make sure that the selection shape is deleted, too
  5683. self.delete_selection_shape()
  5684. else:
  5685. self.inform.emit(_("Failed. No object(s) selected..."))
  5686. else:
  5687. self.inform.emit(_("Save the work in Editor and try again ..."))
  5688. def delete_first_selected(self):
  5689. # Keep this for later
  5690. try:
  5691. sel_obj = self.collection.get_active()
  5692. name = sel_obj.options["name"]
  5693. isPlotted = sel_obj.options["plot"]
  5694. except AttributeError:
  5695. self.log.debug("Nothing selected for deletion")
  5696. return
  5697. if self.is_legacy is True:
  5698. # Remove plot only if the object was plotted otherwise delaxes will fail
  5699. if isPlotted:
  5700. try:
  5701. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  5702. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  5703. except Exception as e:
  5704. log.debug("App.delete_first_selected() --> %s" % str(e))
  5705. self.plotcanvas.auto_adjust_axes()
  5706. # Remove from dictionary
  5707. self.collection.delete_active()
  5708. # Clear form
  5709. self.setup_component_editor()
  5710. self.inform.emit('%s: %s' %
  5711. (_("Object deleted"), name))
  5712. def on_set_origin(self):
  5713. """
  5714. Set the origin to the left mouse click position
  5715. :return: None
  5716. """
  5717. # display the message for the user
  5718. # and ask him to click on the desired position
  5719. self.report_usage("on_set_origin()")
  5720. def origin_replot():
  5721. def worker_task():
  5722. with self.proc_container.new('%s...' % _("Plotting")):
  5723. for obj in self.collection.get_list():
  5724. obj.plot()
  5725. self.plotcanvas.fit_view()
  5726. if self.is_legacy:
  5727. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  5728. else:
  5729. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  5730. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5731. self.inform.emit(_('Click to set the origin ...'))
  5732. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  5733. # first disconnect it as it may have been used by something else
  5734. try:
  5735. self.replot_signal.disconnect()
  5736. except TypeError:
  5737. pass
  5738. self.replot_signal[list].connect(origin_replot)
  5739. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  5740. """
  5741. :param event:
  5742. :param location:
  5743. :param noplot:
  5744. :param use_thread:
  5745. :return:
  5746. """
  5747. noplot_sig = noplot
  5748. def worker_task():
  5749. with self.proc_container.new(_("Setting Origin...")):
  5750. for obj in self.collection.get_list():
  5751. obj.offset((x, y))
  5752. self.object_changed.emit(obj)
  5753. # Update the object bounding box options
  5754. a, b, c, d = obj.bounds()
  5755. obj.options['xmin'] = a
  5756. obj.options['ymin'] = b
  5757. obj.options['xmax'] = c
  5758. obj.options['ymax'] = d
  5759. self.inform.emit('[success] %s...' %
  5760. _('Origin set'))
  5761. if noplot_sig is False:
  5762. self.replot_signal.emit([])
  5763. if location is not None:
  5764. if len(location) != 2:
  5765. self.inform.emit('[ERROR_NOTCL] %s...' %
  5766. _("Origin coordinates specified but incomplete."))
  5767. return 'fail'
  5768. x, y = location
  5769. if use_thread is True:
  5770. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5771. else:
  5772. worker_task()
  5773. self.should_we_save = True
  5774. return
  5775. if event.button == 1:
  5776. if self.is_legacy is False:
  5777. event_pos = event.pos
  5778. else:
  5779. event_pos = (event.xdata, event.ydata)
  5780. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5781. if self.grid_status() == True:
  5782. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5783. else:
  5784. pos = pos_canvas
  5785. x = 0 - pos[0]
  5786. y = 0 - pos[1]
  5787. if use_thread is True:
  5788. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5789. else:
  5790. worker_task()
  5791. self.should_we_save = True
  5792. def on_jump_to(self, custom_location=None, fit_center=True):
  5793. """
  5794. Jump to a location by setting the mouse cursor location
  5795. :return:
  5796. """
  5797. self.report_usage("on_jump_to()")
  5798. # if self.is_legacy is True:
  5799. # self.inform.emit(_("Not available with the current Graphic Engine Legacy(2D)."))
  5800. # return
  5801. if not custom_location:
  5802. dia_box = Dialog_box(title=_("Jump to ..."),
  5803. label=_("Enter the coordinates in format X,Y:"),
  5804. icon=QtGui.QIcon('share/jump_to16.png'))
  5805. if dia_box.ok is True:
  5806. try:
  5807. location = eval(dia_box.location)
  5808. if not isinstance(location, tuple):
  5809. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  5810. return
  5811. except:
  5812. return
  5813. else:
  5814. return
  5815. else:
  5816. location = custom_location
  5817. if fit_center:
  5818. self.plotcanvas.fit_center(loc=location)
  5819. cursor = QtGui.QCursor()
  5820. if self.is_legacy is False:
  5821. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5822. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  5823. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  5824. else:
  5825. # find the canvas origin which is in the top left corner
  5826. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5827. # determine the coordinates for the lowest left point of the canvas
  5828. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  5829. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  5830. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  5831. # canvas) and the point (width, height) is in the top-right location
  5832. loc = self.plotcanvas.axes.transData.transform_point(location)
  5833. cursor.setPos(x0 + loc[0], y0 - loc[1])
  5834. self.inform.emit('[success] %s' %
  5835. _("Done."))
  5836. return location
  5837. def on_copy_object(self):
  5838. self.report_usage("on_copy_object()")
  5839. def initialize(obj_init, app):
  5840. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5841. try:
  5842. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5843. except AttributeError:
  5844. pass
  5845. try:
  5846. obj_init.apertures = deepcopy(obj.apertures)
  5847. except AttributeError:
  5848. pass
  5849. try:
  5850. if obj.tools:
  5851. obj_init.tools = deepcopy(obj.tools)
  5852. except Exception as e:
  5853. log.debug("App.on_copy_object() --> %s" % str(e))
  5854. def initialize_excellon(obj_init, app):
  5855. obj_init.tools = deepcopy(obj.tools)
  5856. # drills are offset, so they need to be deep copied
  5857. obj_init.drills = deepcopy(obj.drills)
  5858. # slots are offset, so they need to be deep copied
  5859. obj_init.slots = deepcopy(obj.slots)
  5860. obj_init.create_geometry()
  5861. for obj in self.collection.get_selected():
  5862. obj_name = obj.options["name"]
  5863. try:
  5864. if isinstance(obj, FlatCAMExcellon):
  5865. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  5866. elif isinstance(obj, FlatCAMGerber):
  5867. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  5868. elif isinstance(obj, FlatCAMGeometry):
  5869. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  5870. except Exception as e:
  5871. return "Operation failed: %s" % str(e)
  5872. def on_copy_object2(self, custom_name):
  5873. def initialize_geometry(obj_init, app):
  5874. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5875. try:
  5876. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5877. except AttributeError:
  5878. pass
  5879. try:
  5880. obj_init.apertures = deepcopy(obj.apertures)
  5881. except AttributeError:
  5882. pass
  5883. try:
  5884. if obj.tools:
  5885. obj_init.tools = deepcopy(obj.tools)
  5886. except Exception as e:
  5887. log.debug("on_copy_object2() --> %s" % str(e))
  5888. def initialize_gerber(obj_init, app):
  5889. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5890. obj_init.apertures = deepcopy(obj.apertures)
  5891. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  5892. def initialize_excellon(obj_init, app):
  5893. obj_init.tools = deepcopy(obj.tools)
  5894. # drills are offset, so they need to be deep copied
  5895. obj_init.drills = deepcopy(obj.drills)
  5896. # slots are offset, so they need to be deep copied
  5897. obj_init.slots = deepcopy(obj.slots)
  5898. obj_init.create_geometry()
  5899. for obj in self.collection.get_selected():
  5900. obj_name = obj.options["name"]
  5901. try:
  5902. if isinstance(obj, FlatCAMExcellon):
  5903. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  5904. elif isinstance(obj, FlatCAMGerber):
  5905. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  5906. elif isinstance(obj, FlatCAMGeometry):
  5907. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  5908. except Exception as e:
  5909. return "Operation failed: %s" % str(e)
  5910. def on_rename_object(self, text):
  5911. self.report_usage("on_rename_object()")
  5912. named_obj = self.collection.get_active()
  5913. for obj in named_obj:
  5914. if obj is list:
  5915. self.on_rename_object(text)
  5916. else:
  5917. try:
  5918. obj.options['name'] = text
  5919. except Exception as e:
  5920. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  5921. def convert_any2geo(self):
  5922. self.report_usage("convert_any2geo()")
  5923. def initialize(obj_init, app):
  5924. obj_init.solid_geometry = obj.solid_geometry
  5925. try:
  5926. obj_init.follow_geometry = obj.follow_geometry
  5927. except AttributeError:
  5928. pass
  5929. try:
  5930. obj_init.apertures = obj.apertures
  5931. except AttributeError:
  5932. pass
  5933. try:
  5934. if obj.tools:
  5935. obj_init.tools = obj.tools
  5936. except AttributeError:
  5937. pass
  5938. def initialize_excellon(obj_init, app):
  5939. # objs = self.collection.get_selected()
  5940. # FlatCAMGeometry.merge(objs, obj)
  5941. solid_geo = []
  5942. for tool in obj.tools:
  5943. for geo in obj.tools[tool]['solid_geometry']:
  5944. solid_geo.append(geo)
  5945. obj_init.solid_geometry = deepcopy(solid_geo)
  5946. if not self.collection.get_selected():
  5947. log.warning("App.convert_any2geo --> No object selected")
  5948. self.inform.emit('[WARNING_NOTCL] %s' %
  5949. _("No object is selected. Select an object and try again."))
  5950. return
  5951. for obj in self.collection.get_selected():
  5952. obj_name = obj.options["name"]
  5953. try:
  5954. if isinstance(obj, FlatCAMExcellon):
  5955. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  5956. else:
  5957. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  5958. except Exception as e:
  5959. return "Operation failed: %s" % str(e)
  5960. def convert_any2gerber(self):
  5961. self.report_usage("convert_any2gerber()")
  5962. def initialize_geometry(obj_init, app):
  5963. apertures = {}
  5964. apid = 0
  5965. apertures[str(apid)] = {}
  5966. apertures[str(apid)]['geometry'] = []
  5967. for obj_orig in obj.solid_geometry:
  5968. new_elem = dict()
  5969. new_elem['solid'] = obj_orig
  5970. new_elem['follow'] = obj_orig.exterior
  5971. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  5972. apertures[str(apid)]['size'] = 0.0
  5973. apertures[str(apid)]['type'] = 'C'
  5974. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5975. obj_init.apertures = deepcopy(apertures)
  5976. def initialize_excellon(obj_init, app):
  5977. apertures = {}
  5978. apid = 10
  5979. for tool in obj.tools:
  5980. apertures[str(apid)] = {}
  5981. apertures[str(apid)]['geometry'] = []
  5982. for geo in obj.tools[tool]['solid_geometry']:
  5983. new_el = dict()
  5984. new_el['solid'] = geo
  5985. new_el['follow'] = geo.exterior
  5986. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  5987. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  5988. apertures[str(apid)]['type'] = 'C'
  5989. apid += 1
  5990. # create solid_geometry
  5991. solid_geometry = []
  5992. for apid in apertures:
  5993. for geo_el in apertures[apid]['geometry']:
  5994. solid_geometry.append(geo_el['solid'])
  5995. solid_geometry = MultiPolygon(solid_geometry)
  5996. solid_geometry = solid_geometry.buffer(0.0000001)
  5997. obj_init.solid_geometry = deepcopy(solid_geometry)
  5998. obj_init.apertures = deepcopy(apertures)
  5999. # clear the working objects (perhaps not necessary due of Python GC)
  6000. apertures.clear()
  6001. if not self.collection.get_selected():
  6002. log.warning("App.convert_any2gerber --> No object selected")
  6003. self.inform.emit('[WARNING_NOTCL] %s' %
  6004. _("No object is selected. Select an object and try again."))
  6005. return
  6006. for obj in self.collection.get_selected():
  6007. obj_name = obj.options["name"]
  6008. try:
  6009. if isinstance(obj, FlatCAMExcellon):
  6010. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  6011. elif isinstance(obj, FlatCAMGeometry):
  6012. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  6013. else:
  6014. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  6015. except Exception as e:
  6016. return "Operation failed: %s" % str(e)
  6017. def abort_all_tasks(self):
  6018. if self.abort_flag is False:
  6019. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  6020. self.abort_flag = True
  6021. def app_is_idle(self):
  6022. if self.abort_flag:
  6023. self.inform.emit('[WARNING_NOTCL] %s' %
  6024. _("The current task was gracefully closed on user request..."))
  6025. self.abort_flag = False
  6026. def on_selectall(self):
  6027. self.report_usage("on_selectall()")
  6028. # delete the possible selection box around a possible selected object
  6029. self.delete_selection_shape()
  6030. for name in self.collection.get_names():
  6031. self.collection.set_active(name)
  6032. curr_sel_obj = self.collection.get_by_name(name)
  6033. # create the selection box around the selected object
  6034. if self.defaults['global_selection_shape'] is True:
  6035. self.draw_selection_shape(curr_sel_obj)
  6036. def on_preferences(self):
  6037. # add the tab if it was closed
  6038. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  6039. # delete the absolute and relative position and messages in the infobar
  6040. self.ui.position_label.setText("")
  6041. self.ui.rel_position_label.setText("")
  6042. # Switch plot_area to preferences page
  6043. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  6044. # self.ui.show()
  6045. # this disconnect() is done so the slot will be connected only once
  6046. try:
  6047. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_preferences_closed)
  6048. except (TypeError, AttributeError):
  6049. pass
  6050. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_preferences_closed)
  6051. # detect changes in the preferences
  6052. for idx in range(self.ui.pref_tab_area.count()):
  6053. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6054. try:
  6055. try:
  6056. tb.textEdited.disconnect(self.on_preferences_edited)
  6057. except (TypeError, AttributeError):
  6058. pass
  6059. tb.textEdited.connect(self.on_preferences_edited)
  6060. except AttributeError:
  6061. pass
  6062. try:
  6063. try:
  6064. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6065. except (TypeError, AttributeError):
  6066. pass
  6067. tb.modificationChanged.connect(self.on_preferences_edited)
  6068. except AttributeError:
  6069. pass
  6070. try:
  6071. try:
  6072. tb.toggled.disconnect(self.on_preferences_edited)
  6073. except (TypeError, AttributeError):
  6074. pass
  6075. tb.toggled.connect(self.on_preferences_edited)
  6076. except AttributeError:
  6077. pass
  6078. try:
  6079. try:
  6080. tb.valueChanged.disconnect(self.on_preferences_edited)
  6081. except (TypeError, AttributeError):
  6082. pass
  6083. tb.valueChanged.connect(self.on_preferences_edited)
  6084. except AttributeError:
  6085. pass
  6086. try:
  6087. try:
  6088. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6089. except (TypeError, AttributeError):
  6090. pass
  6091. tb.currentIndexChanged.connect(self.on_preferences_edited)
  6092. except AttributeError:
  6093. pass
  6094. def on_preferences_edited(self):
  6095. self.inform.emit('[WARNING_NOTCL] %s' %
  6096. _("Preferences edited but not saved."))
  6097. self.preferences_changed_flag = True
  6098. def on_preferences_closed(self):
  6099. # disconnect
  6100. for idx in range(self.ui.pref_tab_area.count()):
  6101. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6102. try:
  6103. tb.textEdited.disconnect(self.on_preferences_edited)
  6104. except (TypeError, AttributeError):
  6105. pass
  6106. try:
  6107. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6108. except (TypeError, AttributeError):
  6109. pass
  6110. try:
  6111. tb.toggled.disconnect(self.on_preferences_edited)
  6112. except (TypeError, AttributeError):
  6113. pass
  6114. try:
  6115. tb.valueChanged.disconnect(self.on_preferences_edited)
  6116. except (TypeError, AttributeError):
  6117. pass
  6118. try:
  6119. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6120. except (TypeError, AttributeError):
  6121. pass
  6122. if self.preferences_changed_flag is True:
  6123. msgbox = QtWidgets.QMessageBox()
  6124. msgbox.setText(_("One or more values are changed.\n"
  6125. "Do you want to save the Preferences?"))
  6126. msgbox.setWindowTitle(_("Save Preferences"))
  6127. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6128. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6129. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6130. msgbox.setDefaultButton(bt_yes)
  6131. msgbox.exec_()
  6132. response = msgbox.clickedButton()
  6133. if response == bt_yes:
  6134. self.on_save_button()
  6135. self.inform.emit('[success] %s' %
  6136. _("Preferences saved."))
  6137. else:
  6138. self.preferences_changed_flag = False
  6139. return
  6140. def on_flipy(self):
  6141. self.report_usage("on_flipy()")
  6142. obj_list = self.collection.get_selected()
  6143. xminlist = []
  6144. yminlist = []
  6145. xmaxlist = []
  6146. ymaxlist = []
  6147. if not obj_list:
  6148. self.inform.emit('[WARNING_NOTCL] %s' %
  6149. _("No object selected to Flip on Y axis."))
  6150. else:
  6151. try:
  6152. # first get a bounding box to fit all
  6153. for obj in obj_list:
  6154. xmin, ymin, xmax, ymax = obj.bounds()
  6155. xminlist.append(xmin)
  6156. yminlist.append(ymin)
  6157. xmaxlist.append(xmax)
  6158. ymaxlist.append(ymax)
  6159. # get the minimum x,y and maximum x,y for all objects selected
  6160. xminimal = min(xminlist)
  6161. yminimal = min(yminlist)
  6162. xmaximal = max(xmaxlist)
  6163. ymaximal = max(ymaxlist)
  6164. px = 0.5 * (xminimal + xmaximal)
  6165. py = 0.5 * (yminimal + ymaximal)
  6166. # execute mirroring
  6167. for obj in obj_list:
  6168. obj.mirror('X', [px, py])
  6169. obj.plot()
  6170. self.object_changed.emit(obj)
  6171. self.inform.emit('[success] %s' %
  6172. _("Flip on Y axis done."))
  6173. except Exception as e:
  6174. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6175. (_("Flip action was not executed."), str(e)))
  6176. return
  6177. def on_flipx(self):
  6178. self.report_usage("on_flipx()")
  6179. obj_list = self.collection.get_selected()
  6180. xminlist = []
  6181. yminlist = []
  6182. xmaxlist = []
  6183. ymaxlist = []
  6184. if not obj_list:
  6185. self.inform.emit('[WARNING_NOTCL] %s' %
  6186. _("No object selected to Flip on X axis."))
  6187. else:
  6188. try:
  6189. # first get a bounding box to fit all
  6190. for obj in obj_list:
  6191. xmin, ymin, xmax, ymax = obj.bounds()
  6192. xminlist.append(xmin)
  6193. yminlist.append(ymin)
  6194. xmaxlist.append(xmax)
  6195. ymaxlist.append(ymax)
  6196. # get the minimum x,y and maximum x,y for all objects selected
  6197. xminimal = min(xminlist)
  6198. yminimal = min(yminlist)
  6199. xmaximal = max(xmaxlist)
  6200. ymaximal = max(ymaxlist)
  6201. px = 0.5 * (xminimal + xmaximal)
  6202. py = 0.5 * (yminimal + ymaximal)
  6203. # execute mirroring
  6204. for obj in obj_list:
  6205. obj.mirror('Y', [px, py])
  6206. obj.plot()
  6207. self.object_changed.emit(obj)
  6208. self.inform.emit('[success] %s' %
  6209. _("Flip on X axis done."))
  6210. except Exception as e:
  6211. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6212. (_("Flip action was not executed."), str(e)))
  6213. return
  6214. def on_rotate(self, silent=False, preset=None):
  6215. self.report_usage("on_rotate()")
  6216. obj_list = self.collection.get_selected()
  6217. xminlist = []
  6218. yminlist = []
  6219. xmaxlist = []
  6220. ymaxlist = []
  6221. if not obj_list:
  6222. self.inform.emit('[WARNING_NOTCL] %s' %
  6223. _("No object selected to Rotate."))
  6224. else:
  6225. if silent is False:
  6226. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6227. min=-360, max=360, decimals=4,
  6228. init_val=float(self.defaults['tools_transform_rotate']))
  6229. num, ok = rotatebox.get_value()
  6230. else:
  6231. num = preset
  6232. ok = True
  6233. if ok:
  6234. try:
  6235. # first get a bounding box to fit all
  6236. for obj in obj_list:
  6237. xmin, ymin, xmax, ymax = obj.bounds()
  6238. xminlist.append(xmin)
  6239. yminlist.append(ymin)
  6240. xmaxlist.append(xmax)
  6241. ymaxlist.append(ymax)
  6242. # get the minimum x,y and maximum x,y for all objects selected
  6243. xminimal = min(xminlist)
  6244. yminimal = min(yminlist)
  6245. xmaximal = max(xmaxlist)
  6246. ymaximal = max(ymaxlist)
  6247. px = 0.5 * (xminimal + xmaximal)
  6248. py = 0.5 * (yminimal + ymaximal)
  6249. for sel_obj in obj_list:
  6250. sel_obj.rotate(-float(num), point=(px, py))
  6251. sel_obj.plot()
  6252. self.object_changed.emit(sel_obj)
  6253. self.inform.emit('[success] %s' %
  6254. _("Rotation done."))
  6255. except Exception as e:
  6256. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6257. (_("Rotation movement was not executed."), str(e)))
  6258. return
  6259. def on_skewx(self):
  6260. self.report_usage("on_skewx()")
  6261. obj_list = self.collection.get_selected()
  6262. xminlist = []
  6263. yminlist = []
  6264. if not obj_list:
  6265. self.inform.emit('[WARNING_NOTCL] %s' %
  6266. _("No object selected to Skew/Shear on X axis."))
  6267. else:
  6268. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6269. min=-360, max=360, decimals=4,
  6270. init_val=float(self.defaults['tools_transform_skew_x']))
  6271. num, ok = skewxbox.get_value()
  6272. if ok:
  6273. # first get a bounding box to fit all
  6274. for obj in obj_list:
  6275. xmin, ymin, xmax, ymax = obj.bounds()
  6276. xminlist.append(xmin)
  6277. yminlist.append(ymin)
  6278. # get the minimum x,y and maximum x,y for all objects selected
  6279. xminimal = min(xminlist)
  6280. yminimal = min(yminlist)
  6281. for obj in obj_list:
  6282. obj.skew(num, 0, point=(xminimal, yminimal))
  6283. obj.plot()
  6284. self.object_changed.emit(obj)
  6285. self.inform.emit('[success] %s' %
  6286. _("Skew on X axis done."))
  6287. def on_skewy(self):
  6288. self.report_usage("on_skewy()")
  6289. obj_list = self.collection.get_selected()
  6290. xminlist = []
  6291. yminlist = []
  6292. if not obj_list:
  6293. self.inform.emit('[WARNING_NOTCL] %s' %
  6294. _("No object selected to Skew/Shear on Y axis."))
  6295. else:
  6296. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6297. min=-360, max=360, decimals=4,
  6298. init_val=float(self.defaults['tools_transform_skew_y']))
  6299. num, ok = skewybox.get_value()
  6300. if ok:
  6301. # first get a bounding box to fit all
  6302. for obj in obj_list:
  6303. xmin, ymin, xmax, ymax = obj.bounds()
  6304. xminlist.append(xmin)
  6305. yminlist.append(ymin)
  6306. # get the minimum x,y and maximum x,y for all objects selected
  6307. xminimal = min(xminlist)
  6308. yminimal = min(yminlist)
  6309. for obj in obj_list:
  6310. obj.skew(0, num, point=(xminimal, yminimal))
  6311. obj.plot()
  6312. self.object_changed.emit(obj)
  6313. self.inform.emit('[success] %s' %
  6314. _("Skew on Y axis done."))
  6315. def on_plots_updated(self):
  6316. """
  6317. Callback used to report when the plots have changed.
  6318. Adjust axes and zooms to fit.
  6319. :return: None
  6320. """
  6321. if self.is_legacy is False:
  6322. self.plotcanvas.update() # TODO: Need update canvas?
  6323. else:
  6324. self.plotcanvas.auto_adjust_axes()
  6325. self.on_zoom_fit(None)
  6326. self.collection.update_view()
  6327. # self.inform.emit(_("Plots updated ..."))
  6328. # TODO: Rework toolbar 'clear', 'replot' functions
  6329. def on_toolbar_replot(self):
  6330. """
  6331. Callback for toolbar button. Re-plots all objects.
  6332. :return: None
  6333. """
  6334. self.report_usage("on_toolbar_replot")
  6335. self.log.debug("on_toolbar_replot()")
  6336. try:
  6337. self.collection.get_active().read_form()
  6338. except AttributeError:
  6339. self.log.debug("on_toolbar_replot(): AttributeError")
  6340. pass
  6341. self.plot_all()
  6342. def on_row_activated(self, index):
  6343. if index.isValid():
  6344. if index.internalPointer().parent_item != self.collection.root_item:
  6345. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6346. self.collection.on_item_activated(index)
  6347. def grid_status(self):
  6348. if self.ui.grid_snap_btn.isChecked():
  6349. return True
  6350. else:
  6351. return False
  6352. def populate_cmenu_grids(self):
  6353. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6354. self.ui.cmenu_gridmenu.clear()
  6355. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  6356. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  6357. grid_toggle.setCheckable(True)
  6358. if self.grid_status() == True:
  6359. grid_toggle.setChecked(True)
  6360. else:
  6361. grid_toggle.setChecked(False)
  6362. self.ui.cmenu_gridmenu.addSeparator()
  6363. for grid in sorted_list:
  6364. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  6365. action.triggered.connect(self.set_grid)
  6366. self.ui.cmenu_gridmenu.addSeparator()
  6367. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  6368. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  6369. grid_add.triggered.connect(self.on_grid_add)
  6370. grid_delete.triggered.connect(self.on_grid_delete)
  6371. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  6372. def set_grid(self):
  6373. self.ui.grid_gap_x_entry.setText(self.sender().text())
  6374. self.ui.grid_gap_y_entry.setText(self.sender().text())
  6375. def on_grid_add(self):
  6376. # ## Current application units in lower Case
  6377. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6378. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  6379. text=_('Enter a Grid Value:'),
  6380. min=0.0000, max=99.9999, decimals=4)
  6381. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  6382. val, ok = grid_add_popup.get_value()
  6383. if ok:
  6384. if float(val) == 0:
  6385. self.inform.emit('[WARNING_NOTCL] %s' %
  6386. _("Please enter a grid value with non-zero value, in Float format."))
  6387. return
  6388. else:
  6389. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  6390. self.defaults["global_grid_context_menu"][str(units)].append(val)
  6391. self.inform.emit('[success] %s...' %
  6392. _("New Grid added"))
  6393. else:
  6394. self.inform.emit('[WARNING_NOTCL] %s...' %
  6395. _("Grid already exists"))
  6396. else:
  6397. self.inform.emit('[WARNING_NOTCL] %s...' %
  6398. _("Adding New Grid cancelled"))
  6399. def on_grid_delete(self):
  6400. # ## Current application units in lower Case
  6401. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6402. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  6403. text='Enter a Grid Value:',
  6404. min=0.0000, max=99.9999, decimals=4)
  6405. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  6406. val, ok = grid_del_popup.get_value()
  6407. if ok:
  6408. if float(val) == 0:
  6409. self.inform.emit('[WARNING_NOTCL] %s' %
  6410. _("Please enter a grid value with non-zero value, in Float format."))
  6411. return
  6412. else:
  6413. try:
  6414. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  6415. except ValueError:
  6416. self.inform.emit('[ERROR_NOTCL]%s...' %
  6417. _(" Grid Value does not exist"))
  6418. return
  6419. self.inform.emit('[success] %s...' %
  6420. _("Grid Value deleted"))
  6421. else:
  6422. self.inform.emit('[WARNING_NOTCL] %s...' %
  6423. _("Delete Grid value cancelled"))
  6424. def on_shortcut_list(self):
  6425. self.report_usage("on_shortcut_list()")
  6426. # add the tab if it was closed
  6427. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  6428. # delete the absolute and relative position and messages in the infobar
  6429. self.ui.position_label.setText("")
  6430. self.ui.rel_position_label.setText("")
  6431. # Switch plot_area to preferences page
  6432. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  6433. # self.ui.show()
  6434. def on_select_tab(self, name):
  6435. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  6436. if self.ui.splitter.sizes()[0] == 0:
  6437. self.ui.splitter.setSizes([1, 1])
  6438. else:
  6439. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  6440. self.ui.splitter.setSizes([0, 1])
  6441. if name == 'project':
  6442. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6443. elif name == 'selected':
  6444. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6445. elif name == 'tool':
  6446. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  6447. def on_copy_name(self):
  6448. self.report_usage("on_copy_name()")
  6449. obj = self.collection.get_active()
  6450. try:
  6451. name = obj.options["name"]
  6452. except AttributeError:
  6453. log.debug("on_copy_name() --> No object selected to copy it's name")
  6454. self.inform.emit('[WARNING_NOTCL]%s' %
  6455. _(" No object selected to copy it's name"))
  6456. return
  6457. self.clipboard.setText(name)
  6458. self.inform.emit(_("Name copied on clipboard ..."))
  6459. def on_mouse_click_over_plot(self, event):
  6460. """
  6461. Default actions are:
  6462. :param event: Contains information about the event, like which button
  6463. was clicked, the pixel coordinates and the axes coordinates.
  6464. :return: None
  6465. """
  6466. self.pos = []
  6467. if self.is_legacy is False:
  6468. event_pos = event.pos
  6469. if self.defaults["global_pan_button"] == '2':
  6470. pan_button = 2
  6471. else:
  6472. pan_button = 3
  6473. # Set the mouse button for panning
  6474. self.plotcanvas.view.camera.pan_button_setting = pan_button
  6475. else:
  6476. event_pos = (event.xdata, event.ydata)
  6477. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6478. if self.defaults["global_pan_button"] == '2':
  6479. pan_button = 3
  6480. else:
  6481. pan_button = 2
  6482. # So it can receive key presses
  6483. self.plotcanvas.native.setFocus()
  6484. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6485. if self.grid_status() == True:
  6486. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  6487. else:
  6488. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  6489. try:
  6490. modifiers = QtWidgets.QApplication.keyboardModifiers()
  6491. if event.button == 1:
  6492. # Reset here the relative coordinates so there is a new reference on the click position
  6493. if self.rel_point1 is None:
  6494. self.rel_point1 = self.pos
  6495. else:
  6496. self.rel_point2 = copy(self.rel_point1)
  6497. self.rel_point1 = self.pos
  6498. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  6499. if modifiers == QtCore.Qt.ShiftModifier:
  6500. # do not auto open the Project Tab
  6501. self.click_noproject = True
  6502. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  6503. self.inform.emit('[success] %s' %
  6504. _("Coordinates copied to clipboard."))
  6505. return
  6506. self.on_mouse_move_over_plot(event, origin_click=True)
  6507. except Exception as e:
  6508. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  6509. def on_double_click_over_plot(self, event):
  6510. if event.button == 1:
  6511. self.doubleclick = True
  6512. def on_mouse_move_over_plot(self, event, origin_click=None):
  6513. """
  6514. Callback for the mouse motion event over the plot.
  6515. :param event: Contains information about the event.
  6516. :param origin_click
  6517. :return: None
  6518. """
  6519. if self.is_legacy is False:
  6520. event_pos = event.pos
  6521. if self.defaults["global_pan_button"] == '2':
  6522. pan_button = 2
  6523. else:
  6524. pan_button = 3
  6525. event_is_dragging = event.is_dragging
  6526. else:
  6527. event_pos = (event.xdata, event.ydata)
  6528. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6529. if self.defaults["global_pan_button"] == '2':
  6530. pan_button = 3
  6531. else:
  6532. pan_button = 2
  6533. event_is_dragging = self.plotcanvas.is_dragging
  6534. # So it can receive key presses
  6535. self.plotcanvas.native.setFocus()
  6536. self.pos_jump = event_pos
  6537. self.ui.popMenu.mouse_is_panning = False
  6538. if not origin_click:
  6539. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  6540. if event.button == pan_button and event_is_dragging == 1:
  6541. self.ui.popMenu.mouse_is_panning = True
  6542. return
  6543. if self.rel_point1 is not None:
  6544. try: # May fail in case mouse not within axes
  6545. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6546. if self.grid_status() == True:
  6547. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6548. # Update cursor
  6549. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  6550. symbol='++', edge_color='black', size=20)
  6551. else:
  6552. pos = (pos_canvas[0], pos_canvas[1])
  6553. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6554. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  6555. dx = pos[0] - float(self.rel_point1[0])
  6556. dy = pos[1] - float(self.rel_point1[1])
  6557. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6558. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6559. self.mouse = [pos[0], pos[1]]
  6560. # if the mouse is moved and the LMB is clicked then the action is a selection
  6561. if event_is_dragging == 1 and event.button == 1:
  6562. self.delete_selection_shape()
  6563. if dx < 0:
  6564. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  6565. face_color=self.defaults['global_alt_sel_fill'])
  6566. self.selection_type = False
  6567. elif dx > 0:
  6568. self.draw_moving_selection_shape(self.pos, pos)
  6569. self.selection_type = True
  6570. else:
  6571. self.selection_type = None
  6572. # hover effect - enabled in Preferences -> General -> GUI Settings
  6573. if self.defaults['global_hover']:
  6574. for obj in self.collection.get_list():
  6575. try:
  6576. # select the object(s) only if it is enabled (plotted)
  6577. if obj.options['plot']:
  6578. if obj not in self.collection.get_selected():
  6579. poly_obj = Polygon(
  6580. [(obj.options['xmin'], obj.options['ymin']),
  6581. (obj.options['xmax'], obj.options['ymin']),
  6582. (obj.options['xmax'], obj.options['ymax']),
  6583. (obj.options['xmin'], obj.options['ymax'])]
  6584. )
  6585. if Point(pos).within(poly_obj):
  6586. if obj.isHovering is False:
  6587. obj.isHovering = True
  6588. obj.notHovering = True
  6589. # create the selection box around the selected object
  6590. self.draw_hover_shape(obj, color='#d1e0e0FF')
  6591. else:
  6592. if obj.notHovering is True:
  6593. obj.notHovering = False
  6594. obj.isHovering = False
  6595. self.delete_hover_shape()
  6596. except:
  6597. # the Exception here will happen if we try to select on screen and we have an
  6598. # newly (and empty) just created Geometry or Excellon object that do not have the
  6599. # xmin, xmax, ymin, ymax options.
  6600. # In this case poly_obj creation (see above) will fail
  6601. pass
  6602. except:
  6603. self.ui.position_label.setText("")
  6604. self.ui.rel_position_label.setText("")
  6605. self.mouse = None
  6606. def on_mouse_click_release_over_plot(self, event):
  6607. """
  6608. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  6609. and has been registered in ''self.__init__()''.
  6610. :param event: contains information about the event.
  6611. :return:
  6612. """
  6613. pos = 0, 0
  6614. if self.is_legacy is False:
  6615. event_pos = event.pos
  6616. right_button = 2
  6617. else:
  6618. event_pos = (event.xdata, event.ydata)
  6619. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6620. right_button = 3
  6621. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6622. if self.grid_status() == True:
  6623. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6624. else:
  6625. pos = (pos_canvas[0], pos_canvas[1])
  6626. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  6627. # canvas menu
  6628. if event.button == right_button: # right click
  6629. if self.ui.popMenu.mouse_is_panning is False:
  6630. self.cursor = QtGui.QCursor()
  6631. self.populate_cmenu_grids()
  6632. self.ui.popMenu.popup(self.cursor.pos())
  6633. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  6634. # selection and then select a type of selection ("enclosing" or "touching")
  6635. try:
  6636. if event.button == 1: # left click
  6637. if self.doubleclick is True:
  6638. self.doubleclick = False
  6639. if self.collection.get_selected():
  6640. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6641. if self.ui.splitter.sizes()[0] == 0:
  6642. self.ui.splitter.setSizes([1, 1])
  6643. # delete the selection shape(S) as it may be in the way
  6644. self.delete_selection_shape()
  6645. self.delete_hover_shape()
  6646. else:
  6647. if self.selection_type is not None:
  6648. self.selection_area_handler(self.pos, pos, self.selection_type)
  6649. self.selection_type = None
  6650. else:
  6651. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  6652. if key_modifier == QtCore.Qt.ShiftModifier:
  6653. mod_key = 'Shift'
  6654. elif key_modifier == QtCore.Qt.ControlModifier:
  6655. mod_key = 'Control'
  6656. else:
  6657. mod_key = None
  6658. if mod_key == self.defaults["global_mselect_key"]:
  6659. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  6660. # deselect, and if it's not selected then it will be selected
  6661. # If there is no active command (self.command_active is None) then we check if we clicked
  6662. # on a object by checking the bounding limits against mouse click position
  6663. if self.command_active is None:
  6664. self.select_objects(key='CTRL')
  6665. self.delete_hover_shape()
  6666. else:
  6667. # If there is no active command (self.command_active is None) then we check if we clicked
  6668. # on a object by checking the bounding limits against mouse click position
  6669. if self.command_active is None:
  6670. self.select_objects()
  6671. self.delete_hover_shape()
  6672. except Exception as e:
  6673. log.warning("Error: %s" % str(e))
  6674. return
  6675. def selection_area_handler(self, start_pos, end_pos, sel_type):
  6676. """
  6677. :param start_pos: mouse position when the selection LMB click was done
  6678. :param end_pos: mouse position when the left mouse button is released
  6679. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  6680. :return:
  6681. """
  6682. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  6683. self.delete_selection_shape()
  6684. for obj in self.collection.get_list():
  6685. try:
  6686. # select the object(s) only if it is enabled (plotted)
  6687. if obj.options['plot']:
  6688. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  6689. (obj.options['xmax'], obj.options['ymin']),
  6690. (obj.options['xmax'], obj.options['ymax']),
  6691. (obj.options['xmin'], obj.options['ymax'])])
  6692. if sel_type is True:
  6693. if poly_obj.within(poly_selection):
  6694. # create the selection box around the selected object
  6695. if self.defaults['global_selection_shape'] is True:
  6696. self.draw_selection_shape(obj)
  6697. self.collection.set_active(obj.options['name'])
  6698. else:
  6699. if poly_selection.intersects(poly_obj):
  6700. # create the selection box around the selected object
  6701. if self.defaults['global_selection_shape'] is True:
  6702. self.draw_selection_shape(obj)
  6703. self.collection.set_active(obj.options['name'])
  6704. except Exception as e:
  6705. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  6706. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  6707. # In this case poly_obj creation (see above) will fail
  6708. log.debug("App.selection_area_handler() --> %s" % str(e))
  6709. def select_objects(self, key=None):
  6710. # list where we store the overlapped objects under our mouse left click position
  6711. objects_under_the_click_list = []
  6712. # Populate the list with the overlapped objects on the click position
  6713. curr_x, curr_y = self.pos
  6714. for obj in self.all_objects_list:
  6715. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  6716. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  6717. if obj.options['name'] not in objects_under_the_click_list:
  6718. if obj.options['plot']:
  6719. # add objects to the objects_under_the_click list only if the object is plotted
  6720. # (active and not disabled)
  6721. objects_under_the_click_list.append(obj.options['name'])
  6722. try:
  6723. # If there is no element in the overlapped objects list then make everyone inactive
  6724. # because we selected "nothing"
  6725. if not objects_under_the_click_list:
  6726. self.collection.set_all_inactive()
  6727. # delete the possible selection box around a possible selected object
  6728. self.delete_selection_shape()
  6729. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  6730. # only when working on App
  6731. if self.call_source == 'app':
  6732. if self.click_noproject is False:
  6733. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6734. else:
  6735. # restore auto open the Project Tab
  6736. self.click_noproject = False
  6737. # delete any text in the status bar, implicitly the last object name that was selected
  6738. self.inform.emit("")
  6739. else:
  6740. self.call_source = 'app'
  6741. else:
  6742. # case when there is only an object under the click and we toggle it
  6743. if len(objects_under_the_click_list) == 1:
  6744. if self.collection.get_active() is None:
  6745. self.collection.set_active(objects_under_the_click_list[0])
  6746. # create the selection box around the selected object
  6747. curr_sel_obj = self.collection.get_active()
  6748. if self.defaults['global_selection_shape'] is True:
  6749. self.draw_selection_shape(curr_sel_obj)
  6750. # self.inform.emit('[selected] %s: %s selected' %
  6751. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6752. if curr_sel_obj.kind == 'gerber':
  6753. self.inform.emit(
  6754. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6755. color='green', name=str(curr_sel_obj.options['name'])))
  6756. elif curr_sel_obj.kind == 'excellon':
  6757. self.inform.emit(
  6758. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6759. color='brown', name=str(curr_sel_obj.options['name'])))
  6760. elif curr_sel_obj.kind == 'cncjob':
  6761. self.inform.emit(
  6762. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6763. color='blue', name=str(curr_sel_obj.options['name'])))
  6764. elif curr_sel_obj.kind == 'geometry':
  6765. self.inform.emit(
  6766. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6767. color='red', name=str(curr_sel_obj.options['name'])))
  6768. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  6769. self.collection.set_all_inactive()
  6770. self.delete_selection_shape()
  6771. self.collection.set_active(objects_under_the_click_list[0])
  6772. # create the selection box around the selected object
  6773. curr_sel_obj = self.collection.get_active()
  6774. if self.defaults['global_selection_shape'] is True:
  6775. self.draw_selection_shape(curr_sel_obj)
  6776. # self.inform.emit('[selected] %s: %s selected' %
  6777. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6778. if curr_sel_obj.kind == 'gerber':
  6779. self.inform.emit(
  6780. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6781. color='green', name=str(curr_sel_obj.options['name'])))
  6782. elif curr_sel_obj.kind == 'excellon':
  6783. self.inform.emit(
  6784. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6785. color='brown', name=str(curr_sel_obj.options['name'])))
  6786. elif curr_sel_obj.kind == 'cncjob':
  6787. self.inform.emit(
  6788. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6789. color='blue', name=str(curr_sel_obj.options['name'])))
  6790. elif curr_sel_obj.kind == 'geometry':
  6791. self.inform.emit(
  6792. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6793. color='red', name=str(curr_sel_obj.options['name'])))
  6794. else:
  6795. self.collection.set_all_inactive()
  6796. self.delete_selection_shape()
  6797. if self.call_source == 'app':
  6798. # delete any text in the status bar, implicitly the last object name that was selected
  6799. self.inform.emit("")
  6800. else:
  6801. self.call_source = 'app'
  6802. else:
  6803. # If there is no selected object
  6804. # make active the first element of the overlapped objects list
  6805. if self.collection.get_active() is None:
  6806. self.collection.set_active(objects_under_the_click_list[0])
  6807. name_sel_obj = self.collection.get_active().options['name']
  6808. # In case that there is a selected object but it is not in the overlapped object list
  6809. # make that object inactive and activate the first element in the overlapped object list
  6810. if name_sel_obj not in objects_under_the_click_list:
  6811. self.collection.set_inactive(name_sel_obj)
  6812. name_sel_obj = objects_under_the_click_list[0]
  6813. self.collection.set_active(name_sel_obj)
  6814. else:
  6815. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  6816. self.collection.set_all_inactive()
  6817. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  6818. len(objects_under_the_click_list)])
  6819. curr_sel_obj = self.collection.get_active()
  6820. # delete the possible selection box around a possible selected object
  6821. self.delete_selection_shape()
  6822. # create the selection box around the selected object
  6823. if self.defaults['global_selection_shape'] is True:
  6824. self.draw_selection_shape(curr_sel_obj)
  6825. # self.inform.emit('[selected] %s: %s selected' %
  6826. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6827. if curr_sel_obj.kind == 'gerber':
  6828. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6829. color='green', name=str(curr_sel_obj.options['name'])))
  6830. elif curr_sel_obj.kind == 'excellon':
  6831. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6832. color='brown', name=str(curr_sel_obj.options['name'])))
  6833. elif curr_sel_obj.kind == 'cncjob':
  6834. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6835. color='blue', name=str(curr_sel_obj.options['name'])))
  6836. elif curr_sel_obj.kind == 'geometry':
  6837. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6838. color='red', name=str(curr_sel_obj.options['name'])))
  6839. # for obj in self.collection.get_list():
  6840. # obj.plot()
  6841. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  6842. # TODO: on selected objects change the object colors and do not draw the selection box
  6843. # self.plotcanvas.update() # this updates the canvas
  6844. except Exception as e:
  6845. log.error("[ERROR] Something went bad. %s" % str(e))
  6846. return
  6847. def delete_hover_shape(self):
  6848. self.hover_shapes.clear()
  6849. self.hover_shapes.redraw()
  6850. def draw_hover_shape(self, sel_obj, color=None):
  6851. """
  6852. :param sel_obj: the object for which the hover shape must be drawn
  6853. :return:
  6854. """
  6855. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6856. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6857. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6858. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6859. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  6860. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6861. hover_rect = hover_rect.buffer(-0.1)
  6862. hover_rect = hover_rect.buffer(0.2)
  6863. else:
  6864. hover_rect = hover_rect.buffer(-0.00393)
  6865. hover_rect = hover_rect.buffer(0.00787)
  6866. # if color:
  6867. # face = Color(color)
  6868. # face.alpha = 0.2
  6869. # outline = Color(color, alpha=0.8)
  6870. # else:
  6871. # face = Color(self.defaults['global_sel_fill'])
  6872. # face.alpha = 0.2
  6873. # outline = self.defaults['global_sel_line']
  6874. if color:
  6875. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  6876. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  6877. else:
  6878. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  6879. outline = self.defaults['global_sel_line']
  6880. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  6881. if self.is_legacy is True:
  6882. self.hover_shapes.redraw()
  6883. def delete_selection_shape(self):
  6884. self.move_tool.sel_shapes.clear()
  6885. self.move_tool.sel_shapes.redraw()
  6886. def draw_selection_shape(self, sel_obj, color=None):
  6887. """
  6888. :param sel_obj: the object for which the selection shape must be drawn
  6889. :return:
  6890. """
  6891. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6892. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6893. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6894. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6895. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6896. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6897. sel_rect = sel_rect.buffer(-0.1)
  6898. sel_rect = sel_rect.buffer(0.2)
  6899. else:
  6900. sel_rect = sel_rect.buffer(-0.00393)
  6901. sel_rect = sel_rect.buffer(0.00787)
  6902. # if color:
  6903. # face = Color(color, alpha=0.2)
  6904. # outline = Color(color, alpha=0.8)
  6905. # else:
  6906. # face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  6907. # outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  6908. if color:
  6909. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  6910. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  6911. else:
  6912. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  6913. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  6914. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  6915. color=outline,
  6916. face_color=face,
  6917. update=True,
  6918. layer=0,
  6919. tolerance=None))
  6920. if self.is_legacy is True:
  6921. self.move_tool.sel_shapes.redraw()
  6922. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  6923. """
  6924. :param old_coords: old coordinates
  6925. :param coords: new coordinates
  6926. :return:
  6927. """
  6928. if 'color' in kwargs:
  6929. color = kwargs['color']
  6930. else:
  6931. color = self.defaults['global_sel_line']
  6932. if 'face_color' in kwargs:
  6933. face_color = kwargs['face_color']
  6934. else:
  6935. face_color = self.defaults['global_sel_fill']
  6936. if 'face_alpha' in kwargs:
  6937. face_alpha = kwargs['face_alpha']
  6938. else:
  6939. face_alpha = 0.3
  6940. x0, y0 = old_coords
  6941. x1, y1 = coords
  6942. pt1 = (x0, y0)
  6943. pt2 = (x1, y0)
  6944. pt3 = (x1, y1)
  6945. pt4 = (x0, y1)
  6946. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6947. # color_t = Color(face_color)
  6948. # color_t.alpha = face_alpha
  6949. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  6950. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  6951. layer=0, tolerance=None)
  6952. if self.is_legacy is True:
  6953. self.move_tool.sel_shapes.redraw()
  6954. def on_file_new_click(self):
  6955. if self.collection.get_list() and self.should_we_save:
  6956. msgbox = QtWidgets.QMessageBox()
  6957. # msgbox.setText("<B>Save changes ...</B>")
  6958. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  6959. "Creating a New project will delete them.\n"
  6960. "Do you want to Save the project?"))
  6961. msgbox.setWindowTitle(_("Save changes"))
  6962. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6963. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6964. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6965. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6966. msgbox.setDefaultButton(bt_yes)
  6967. msgbox.exec_()
  6968. response = msgbox.clickedButton()
  6969. if response == bt_yes:
  6970. self.on_file_saveprojectas()
  6971. elif response == bt_cancel:
  6972. return
  6973. elif response == bt_no:
  6974. self.on_file_new()
  6975. else:
  6976. self.on_file_new()
  6977. self.inform.emit('[success] %s...' %
  6978. _("New Project created"))
  6979. def on_file_new(self, cli=None):
  6980. """
  6981. Callback for menu item File->New. Returns the application to its
  6982. startup state. This method is thread-safe.
  6983. :return: None
  6984. """
  6985. self.report_usage("on_file_new")
  6986. # Remove everything from memory
  6987. App.log.debug("on_file_new()")
  6988. if self.call_source != 'app':
  6989. self.editor2object(cleanup=True)
  6990. # ## EDITOR section
  6991. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  6992. self.exc_editor = FlatCAMExcEditor(self)
  6993. self.grb_editor = FlatCAMGrbEditor(self)
  6994. # Clear pool
  6995. self.clear_pool()
  6996. for obj in self.collection.get_list():
  6997. # delete shapes left drawn from mark shape_collections, if any
  6998. if isinstance(obj, FlatCAMGerber):
  6999. try:
  7000. obj.mark_shapes.enabled = False
  7001. obj.mark_shapes.clear(update=True)
  7002. except AttributeError:
  7003. pass
  7004. # also delete annotation shapes, if any
  7005. elif isinstance(obj, FlatCAMCNCjob):
  7006. try:
  7007. obj.annotation.enabled = False
  7008. obj.annotation.clear(update=True)
  7009. except AttributeError:
  7010. pass
  7011. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7012. self.init_tcl()
  7013. self.delete_selection_shape()
  7014. self.collection.delete_all()
  7015. self.setup_component_editor()
  7016. # Clear project filename
  7017. self.project_filename = None
  7018. # Load the application defaults
  7019. self.load_defaults(filename='current_defaults')
  7020. # Re-fresh project options
  7021. self.on_options_app2project()
  7022. # Init Tools
  7023. self.init_tools()
  7024. if cli is None:
  7025. # Close any Tabs opened in the Plot Tab Area section
  7026. for index in range(self.ui.plot_tab_area.count()):
  7027. self.ui.plot_tab_area.closeTab(index)
  7028. # for whatever reason previous command does not close the last tab so I do it manually
  7029. self.ui.plot_tab_area.closeTab(0)
  7030. # # And then add again the Plot Area
  7031. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  7032. self.ui.plot_tab_area.protectTab(0)
  7033. # take the focus of the Notebook on Project Tab.
  7034. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7035. self.set_ui_title(name=_("New Project - Not saved"))
  7036. def obj_properties(self):
  7037. self.report_usage("obj_properties()")
  7038. self.properties_tool.run(toggle=False)
  7039. def on_project_context_save(self):
  7040. obj = self.collection.get_active()
  7041. if type(obj) == FlatCAMGeometry:
  7042. self.on_file_exportdxf()
  7043. elif type(obj) == FlatCAMExcellon:
  7044. self.on_file_saveexcellon()
  7045. elif type(obj) == FlatCAMCNCjob:
  7046. obj.on_exportgcode_button_click()
  7047. elif type(obj) == FlatCAMGerber:
  7048. self.on_file_savegerber()
  7049. def obj_move(self):
  7050. self.report_usage("obj_move()")
  7051. self.move_tool.run(toggle=False)
  7052. def on_fileopengerber(self, checked=None, name=None):
  7053. """
  7054. File menu callback for opening a Gerber.
  7055. :return: None
  7056. """
  7057. self.report_usage("on_fileopengerber")
  7058. App.log.debug("on_fileopengerber()")
  7059. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  7060. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  7061. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  7062. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  7063. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  7064. "*.mil);;" \
  7065. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  7066. "Allegro Files (*.art);;" \
  7067. "Mentor Files (*.pho *.gdo);;" \
  7068. "All Files (*.*)"
  7069. if name is None:
  7070. try:
  7071. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  7072. directory=self.get_last_folder(),
  7073. filter=_filter_)
  7074. except TypeError:
  7075. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  7076. filenames = [str(filename) for filename in filenames]
  7077. else:
  7078. filenames = [name]
  7079. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7080. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7081. _("Opening Gerber file.")),
  7082. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7083. color=QtGui.QColor("gray"))
  7084. if len(filenames) == 0:
  7085. self.inform.emit('[WARNING_NOTCL] %s' %
  7086. _("Open Gerber cancelled."))
  7087. else:
  7088. for filename in filenames:
  7089. if filename != '':
  7090. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  7091. def on_fileopenexcellon(self, checked=None, name=None):
  7092. """
  7093. File menu callback for opening an Excellon file.
  7094. :return: None
  7095. """
  7096. self.report_usage("on_fileopenexcellon")
  7097. App.log.debug("on_fileopenexcellon()")
  7098. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  7099. "All Files (*.*)"
  7100. if name is None:
  7101. try:
  7102. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  7103. directory=self.get_last_folder(),
  7104. filter=_filter_)
  7105. except TypeError:
  7106. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  7107. filenames = [str(filename) for filename in filenames]
  7108. else:
  7109. filenames = [str(name)]
  7110. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7111. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7112. _("Opening Excellon file.")),
  7113. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7114. color=QtGui.QColor("gray"))
  7115. if len(filenames) == 0:
  7116. self.inform.emit('[WARNING_NOTCL]%s' %
  7117. _(" Open Excellon cancelled."))
  7118. else:
  7119. for filename in filenames:
  7120. if filename != '':
  7121. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  7122. def on_fileopengcode(self, checked=None, name=None):
  7123. """
  7124. File menu call back for opening gcode.
  7125. :return: None
  7126. """
  7127. self.report_usage("on_fileopengcode")
  7128. App.log.debug("on_fileopengcode()")
  7129. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  7130. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  7131. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  7132. "All Files (*.*)"
  7133. if name is None:
  7134. try:
  7135. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  7136. directory=self.get_last_folder(),
  7137. filter=_filter_)
  7138. except TypeError:
  7139. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  7140. filenames = [str(filename) for filename in filenames]
  7141. else:
  7142. filenames = [name]
  7143. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7144. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7145. _("Opening G-Code file.")),
  7146. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7147. color=QtGui.QColor("gray"))
  7148. if len(filenames) == 0:
  7149. self.inform.emit('[WARNING_NOTCL] %s' %
  7150. _("Open G-Code cancelled."))
  7151. else:
  7152. for filename in filenames:
  7153. if filename != '':
  7154. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename]})
  7155. def on_file_openproject(self, checked=None):
  7156. """
  7157. File menu callback for opening a project.
  7158. :return: None
  7159. """
  7160. self.report_usage("on_file_openproject")
  7161. App.log.debug("on_file_openproject()")
  7162. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  7163. try:
  7164. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  7165. directory=self.get_last_folder(), filter=_filter_)
  7166. except TypeError:
  7167. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  7168. # The Qt methods above will return a QString which can cause problems later.
  7169. # So far json.dump() will fail to serialize it.
  7170. # TODO: Improve the serialization methods and remove this fix.
  7171. filename = str(filename)
  7172. if filename == "":
  7173. self.inform.emit('[WARNING_NOTCL] %s' %
  7174. _("Open Project cancelled."))
  7175. else:
  7176. # self.worker_task.emit({'fcn': self.open_project,
  7177. # 'params': [filename]})
  7178. # The above was failing because open_project() is not
  7179. # thread safe. The new_project()
  7180. self.open_project(filename)
  7181. def on_file_openconfig(self, checked=None):
  7182. """
  7183. File menu callback for opening a config file.
  7184. :return: None
  7185. """
  7186. self.report_usage("on_file_openconfig")
  7187. App.log.debug("on_file_openconfig()")
  7188. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  7189. try:
  7190. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7191. directory=self.data_path, filter=_filter_)
  7192. except TypeError:
  7193. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7194. filter=_filter_)
  7195. if filename == "":
  7196. self.inform.emit('[WARNING_NOTCL] %s' %
  7197. _("Open Config cancelled."))
  7198. else:
  7199. self.open_config_file(filename)
  7200. def on_file_exportsvg(self):
  7201. """
  7202. Callback for menu item File->Export SVG.
  7203. :return: None
  7204. """
  7205. self.report_usage("on_file_exportsvg")
  7206. App.log.debug("on_file_exportsvg()")
  7207. obj = self.collection.get_active()
  7208. if obj is None:
  7209. self.inform.emit('[WARNING_NOTCL] %s' %
  7210. _("No object selected."))
  7211. msg = _("Please Select a Geometry object to export")
  7212. msgbox = QtWidgets.QMessageBox()
  7213. msgbox.setInformativeText(msg)
  7214. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7215. msgbox.setDefaultButton(bt_ok)
  7216. msgbox.exec_()
  7217. return
  7218. # Check for more compatible types and add as required
  7219. if (not isinstance(obj, FlatCAMGeometry)
  7220. and not isinstance(obj, FlatCAMGerber)
  7221. and not isinstance(obj, FlatCAMCNCjob)
  7222. and not isinstance(obj, FlatCAMExcellon)):
  7223. msg = '[ERROR_NOTCL] %s' % \
  7224. _("Only Geometry, Gerber and CNCJob objects can be used.")
  7225. msgbox = QtWidgets.QMessageBox()
  7226. msgbox.setInformativeText(msg)
  7227. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7228. msgbox.setDefaultButton(bt_ok)
  7229. msgbox.exec_()
  7230. return
  7231. name = obj.options["name"]
  7232. _filter = "SVG File (*.svg);;All Files (*.*)"
  7233. try:
  7234. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7235. caption=_("Export SVG"),
  7236. directory=self.get_last_save_folder() + '/' + str(name),
  7237. filter=_filter)
  7238. except TypeError:
  7239. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  7240. filename = str(filename)
  7241. if filename == "":
  7242. self.inform.emit('[WARNING_NOTCL]%s' %
  7243. _(" Export SVG cancelled."))
  7244. return
  7245. else:
  7246. self.export_svg(name, filename)
  7247. if self.defaults["global_open_style"] is False:
  7248. self.file_opened.emit("SVG", filename)
  7249. self.file_saved.emit("SVG", filename)
  7250. def on_file_exportpng(self):
  7251. self.report_usage("on_file_exportpng")
  7252. App.log.debug("on_file_exportpng()")
  7253. self.date = str(datetime.today()).rpartition('.')[0]
  7254. self.date = ''.join(c for c in self.date if c not in ':-')
  7255. self.date = self.date.replace(' ', '_')
  7256. image = _screenshot()
  7257. data = np.asarray(image)
  7258. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  7259. self.inform.emit('[[WARNING_NOTCL]] %s' %
  7260. _('Data must be a 3D array with last dimension 3 or 4'))
  7261. return
  7262. filter_ = "PNG File (*.png);;All Files (*.*)"
  7263. try:
  7264. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7265. caption=_("Export PNG Image"),
  7266. directory=self.get_last_save_folder() + '/png_' + self.date,
  7267. filter=filter_)
  7268. except TypeError:
  7269. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  7270. filename = str(filename)
  7271. if filename == "":
  7272. self.inform.emit(_("Export PNG cancelled."))
  7273. return
  7274. else:
  7275. write_png(filename, data)
  7276. if self.defaults["global_open_style"] is False:
  7277. self.file_opened.emit("png", filename)
  7278. self.file_saved.emit("png", filename)
  7279. def on_file_savegerber(self):
  7280. """
  7281. Callback for menu item in Project context menu.
  7282. :return: None
  7283. """
  7284. self.report_usage("on_file_savegerber")
  7285. App.log.debug("on_file_savegerber()")
  7286. obj = self.collection.get_active()
  7287. if obj is None:
  7288. self.inform.emit('[WARNING_NOTCL] %s' %
  7289. _("No object selected. Please select an Gerber object to export."))
  7290. return
  7291. # Check for more compatible types and add as required
  7292. if not isinstance(obj, FlatCAMGerber):
  7293. self.inform.emit('[ERROR_NOTCL] %s' %
  7294. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7295. return
  7296. name = self.collection.get_active().options["name"]
  7297. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  7298. try:
  7299. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7300. caption="Save Gerber source file",
  7301. directory=self.get_last_save_folder() + '/' + name,
  7302. filter=_filter)
  7303. except TypeError:
  7304. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  7305. filename = str(filename)
  7306. if filename == "":
  7307. self.inform.emit('[WARNING_NOTCL] %s' %
  7308. _("Save Gerber source file cancelled."))
  7309. return
  7310. else:
  7311. self.save_source_file(name, filename)
  7312. if self.defaults["global_open_style"] is False:
  7313. self.file_opened.emit("Gerber", filename)
  7314. self.file_saved.emit("Gerber", filename)
  7315. def on_file_saveexcellon(self):
  7316. """
  7317. Callback for menu item in project context menu.
  7318. :return: None
  7319. """
  7320. self.report_usage("on_file_saveexcellon")
  7321. App.log.debug("on_file_saveexcellon()")
  7322. obj = self.collection.get_active()
  7323. if obj is None:
  7324. self.inform.emit('[WARNING_NOTCL] %s' %
  7325. _("No object selected. Please select an Excellon object to export."))
  7326. return
  7327. # Check for more compatible types and add as required
  7328. if not isinstance(obj, FlatCAMExcellon):
  7329. self.inform.emit('[ERROR_NOTCL] %s' %
  7330. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7331. return
  7332. name = self.collection.get_active().options["name"]
  7333. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7334. try:
  7335. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7336. caption=_("Save Excellon source file"),
  7337. directory=self.get_last_save_folder() + '/' + name,
  7338. filter=_filter)
  7339. except TypeError:
  7340. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  7341. filename = str(filename)
  7342. if filename == "":
  7343. self.inform.emit('[WARNING_NOTCL] %s' %
  7344. _("Saving Excellon source file cancelled."))
  7345. return
  7346. else:
  7347. self.save_source_file(name, filename)
  7348. if self.defaults["global_open_style"] is False:
  7349. self.file_opened.emit("Excellon", filename)
  7350. self.file_saved.emit("Excellon", filename)
  7351. def on_file_exportexcellon(self):
  7352. """
  7353. Callback for menu item File->Export->Excellon.
  7354. :return: None
  7355. """
  7356. self.report_usage("on_file_exportexcellon")
  7357. App.log.debug("on_file_exportexcellon()")
  7358. obj = self.collection.get_active()
  7359. if obj is None:
  7360. self.inform.emit('[WARNING_NOTCL] %s' %
  7361. _("No object selected. Please Select an Excellon object to export."))
  7362. return
  7363. # Check for more compatible types and add as required
  7364. if not isinstance(obj, FlatCAMExcellon):
  7365. self.inform.emit('[ERROR_NOTCL] %s' %
  7366. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7367. return
  7368. name = self.collection.get_active().options["name"]
  7369. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7370. try:
  7371. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7372. caption=_("Export Excellon"),
  7373. directory=self.get_last_save_folder() + '/' + name,
  7374. filter=_filter)
  7375. except TypeError:
  7376. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  7377. filename = str(filename)
  7378. if filename == "":
  7379. self.inform.emit('[WARNING_NOTCL] %s' %
  7380. _("Export Excellon cancelled."))
  7381. return
  7382. else:
  7383. self.export_excellon(name, filename)
  7384. if self.defaults["global_open_style"] is False:
  7385. self.file_opened.emit("Excellon", filename)
  7386. self.file_saved.emit("Excellon", filename)
  7387. def on_file_exportgerber(self):
  7388. """
  7389. Callback for menu item File->Export->Gerber.
  7390. :return: None
  7391. """
  7392. self.report_usage("on_file_exportgerber")
  7393. App.log.debug("on_file_exportgerber()")
  7394. obj = self.collection.get_active()
  7395. if obj is None:
  7396. self.inform.emit('[WARNING_NOTCL] %s' %
  7397. _("No object selected. Please Select an Gerber object to export."))
  7398. return
  7399. # Check for more compatible types and add as required
  7400. if not isinstance(obj, FlatCAMGerber):
  7401. self.inform.emit('[ERROR_NOTCL] %s' %
  7402. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7403. return
  7404. name = self.collection.get_active().options["name"]
  7405. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  7406. try:
  7407. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7408. caption=_("Export Gerber"),
  7409. directory=self.get_last_save_folder() + '/' + name,
  7410. filter=_filter_)
  7411. except TypeError:
  7412. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  7413. filename = str(filename)
  7414. if filename == "":
  7415. self.inform.emit('[WARNING_NOTCL] %s' %
  7416. _("Export Gerber cancelled."))
  7417. return
  7418. else:
  7419. self.export_gerber(name, filename)
  7420. if self.defaults["global_open_style"] is False:
  7421. self.file_opened.emit("Gerber", filename)
  7422. self.file_saved.emit("Gerber", filename)
  7423. def on_file_exportdxf(self):
  7424. """
  7425. Callback for menu item File->Export DXF.
  7426. :return: None
  7427. """
  7428. self.report_usage("on_file_exportdxf")
  7429. App.log.debug("on_file_exportdxf()")
  7430. obj = self.collection.get_active()
  7431. if obj is None:
  7432. self.inform.emit('[WARNING_NOTCL] %s' %
  7433. _("No object selected."))
  7434. msg = _("Please Select a Geometry object to export")
  7435. msgbox = QtWidgets.QMessageBox()
  7436. msgbox.setInformativeText(msg)
  7437. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7438. msgbox.setDefaultButton(bt_ok)
  7439. msgbox.exec_()
  7440. return
  7441. # Check for more compatible types and add as required
  7442. if not isinstance(obj, FlatCAMGeometry):
  7443. msg = '[ERROR_NOTCL] %s' % \
  7444. _("Only Geometry objects can be used.")
  7445. msgbox = QtWidgets.QMessageBox()
  7446. msgbox.setInformativeText(msg)
  7447. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7448. msgbox.setDefaultButton(bt_ok)
  7449. msgbox.exec_()
  7450. return
  7451. name = self.collection.get_active().options["name"]
  7452. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7453. try:
  7454. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7455. caption=_("Export DXF"),
  7456. directory=self.get_last_save_folder() + '/' + name,
  7457. filter=_filter_)
  7458. except TypeError:
  7459. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  7460. filter=_filter_)
  7461. filename = str(filename)
  7462. if filename == "":
  7463. self.inform.emit('[WARNING_NOTCL] %s' %
  7464. _("Export DXF cancelled."))
  7465. return
  7466. else:
  7467. self.export_dxf(name, filename)
  7468. if self.defaults["global_open_style"] is False:
  7469. self.file_opened.emit("DXF", filename)
  7470. self.file_saved.emit("DXF", filename)
  7471. def on_file_importsvg(self, type_of_obj):
  7472. """
  7473. Callback for menu item File->Import SVG.
  7474. :param type_of_obj: to import the SVG as Geometry or as Gerber
  7475. :type type_of_obj: str
  7476. :return: None
  7477. """
  7478. self.report_usage("on_file_importsvg")
  7479. App.log.debug("on_file_importsvg()")
  7480. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  7481. try:
  7482. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7483. directory=self.get_last_folder(), filter=_filter_)
  7484. except TypeError:
  7485. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7486. filter=_filter_)
  7487. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7488. type_of_obj = "geometry"
  7489. filenames = [str(filename) for filename in filenames]
  7490. if len(filenames) == 0:
  7491. self.inform.emit('[WARNING_NOTCL] %s' %
  7492. _("Open SVG cancelled."))
  7493. else:
  7494. for filename in filenames:
  7495. if filename != '':
  7496. self.worker_task.emit({'fcn': self.import_svg,
  7497. 'params': [filename, type_of_obj]})
  7498. def on_file_importdxf(self, type_of_obj):
  7499. """
  7500. Callback for menu item File->Import DXF.
  7501. :param type_of_obj: to import the DXF as Geometry or as Gerber
  7502. :type type_of_obj: str
  7503. :return: None
  7504. """
  7505. self.report_usage("on_file_importdxf")
  7506. App.log.debug("on_file_importdxf()")
  7507. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7508. try:
  7509. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7510. directory=self.get_last_folder(),
  7511. filter=_filter_)
  7512. except TypeError:
  7513. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7514. filter=_filter_)
  7515. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7516. type_of_obj = "geometry"
  7517. filenames = [str(filename) for filename in filenames]
  7518. if len(filenames) == 0:
  7519. self.inform.emit('[WARNING_NOTCL] %s' %
  7520. _("Open DXF cancelled."))
  7521. else:
  7522. for filename in filenames:
  7523. if filename != '':
  7524. self.worker_task.emit({'fcn': self.import_dxf,
  7525. 'params': [filename, type_of_obj]})
  7526. # ###############################################################################################################
  7527. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  7528. # ###############################################################################################################
  7529. def init_code_editor(self, name):
  7530. # Signals section
  7531. # Disconnect the old signals
  7532. try:
  7533. self.ui.buttonOpen.clicked.disconnect()
  7534. except TypeError:
  7535. pass
  7536. try:
  7537. self.ui.buttonSave.clicked.disconnect()
  7538. except TypeError:
  7539. pass
  7540. # add the tab if it was closed
  7541. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, '%s' % name)
  7542. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  7543. # delete the absolute and relative position and messages in the infobar
  7544. self.ui.position_label.setText("")
  7545. self.ui.rel_position_label.setText("")
  7546. # first clear previous text in text editor (if any)
  7547. self.ui.code_editor.clear()
  7548. self.ui.code_editor.setReadOnly(False)
  7549. self.toggle_codeeditor = True
  7550. self.ui.code_editor.completer_enable = False
  7551. self.ui.buttonRun.hide()
  7552. # make sure to keep a reference to the code editor
  7553. self.reference_code_editor = self.ui.code_editor
  7554. # Switch plot_area to CNCJob tab
  7555. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  7556. def on_view_source(self):
  7557. self.inform.emit('%s' %
  7558. _("Viewing the source code of the selected object."))
  7559. self.proc_container.view.set_busy(_("Loading..."))
  7560. try:
  7561. obj = self.collection.get_active()
  7562. except Exception as e:
  7563. log.debug("App.on_view_source() --> %s" % str(e))
  7564. self.inform.emit('[WARNING_NOTCL] %s' %
  7565. _("Select an Gerber or Excellon file to view it's source file."))
  7566. return 'fail'
  7567. if obj.kind == 'gerber':
  7568. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  7569. elif obj.kind == 'excellon':
  7570. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  7571. elif obj.kind == 'cncjob':
  7572. "GCode Files (*.NC);;All Files (*.*)"
  7573. else:
  7574. flt = "All Files (*.*)"
  7575. self.init_code_editor(name=_("Source Editor"))
  7576. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  7577. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  7578. # then append the text from GCode to the text editor
  7579. if obj.kind == 'cncjob':
  7580. try:
  7581. file = obj.export_gcode(
  7582. preamble=self.defaults["cncjob_prepend"],
  7583. postamble=self.defaults["cncjob_append"],
  7584. to_file=True)
  7585. if file == 'fail':
  7586. return 'fail'
  7587. except AttributeError:
  7588. self.inform.emit('[WARNING_NOTCL] %s' %
  7589. _("There is no selected object for which to see it's source file code."))
  7590. return 'fail'
  7591. else:
  7592. try:
  7593. file = StringIO(obj.source_file)
  7594. except AttributeError:
  7595. self.inform.emit('[WARNING_NOTCL] %s' %
  7596. _("There is no selected object for which to see it's source file code."))
  7597. return 'fail'
  7598. self.ui.cncjob_frame.hide()
  7599. try:
  7600. for line in file:
  7601. QtWidgets.QApplication.processEvents()
  7602. proc_line = str(line).strip('\n')
  7603. self.ui.code_editor.append(proc_line)
  7604. except Exception as e:
  7605. log.debug('App.on_view_source() -->%s' % str(e))
  7606. self.inform.emit('[ERROR] %s: %s' %
  7607. (_('Failed to load the source code for the selected object'), str(e)))
  7608. return
  7609. self.handleTextChanged()
  7610. self.ui.cncjob_frame.show()
  7611. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7612. self.proc_container.view.set_idle()
  7613. # self.ui.show()
  7614. def on_toggle_code_editor(self):
  7615. self.report_usage("on_toggle_code_editor()")
  7616. if self.toggle_codeeditor is False:
  7617. self.init_code_editor(name=_("Code Editor"))
  7618. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  7619. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  7620. else:
  7621. for idx in range(self.ui.plot_tab_area.count()):
  7622. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  7623. self.ui.plot_tab_area.closeTab(idx)
  7624. break
  7625. self.toggle_codeeditor = False
  7626. def on_filenewscript(self, silent=False):
  7627. """
  7628. Will create a new script file and open it in the Code Editor
  7629. :param silent: if True will not display status messages
  7630. :return: None
  7631. """
  7632. if silent is False:
  7633. self.inform.emit('[success] %s' %
  7634. _("New TCL script file created in Code Editor."))
  7635. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  7636. self.init_code_editor(name=_("Script Editor"))
  7637. self.ui.code_editor.completer_enable = True
  7638. self.ui.code_editor.append(_(
  7639. "#\n"
  7640. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  7641. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  7642. "#\n\n"
  7643. "# FlatCAM commands list:\n"
  7644. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, ClearCopper,\n"
  7645. "# Cncjob, Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, GetNames,\n"
  7646. "# GetSys, ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillDrills,\n"
  7647. "# MillSlots, Mirror, New, NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"
  7648. "# Options, Paint, Panelize, Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, SubtractPoly,\n"
  7649. "# SubtractRectangle, Version, WriteGCode\n"
  7650. "#\n\n"
  7651. ))
  7652. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  7653. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  7654. self.ui.buttonRun.show()
  7655. try:
  7656. self.ui.buttonRun.clicked.disconnect(self.handleRunCode)
  7657. except TypeError:
  7658. pass
  7659. self.ui.buttonRun.clicked.connect(self.handleRunCode)
  7660. self.handleTextChanged()
  7661. self.ui.code_editor.show()
  7662. def on_fileopenscript(self, name=None, silent=False):
  7663. """
  7664. Will open a Tcl script file into the Code Editor
  7665. :param silent: if True will not display status messages
  7666. :param name: name of a Tcl script file to open
  7667. :return:
  7668. """
  7669. if name:
  7670. filename = name
  7671. else:
  7672. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7673. try:
  7674. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  7675. directory=self.get_last_folder(), filter=_filter_)
  7676. except TypeError:
  7677. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  7678. # The Qt methods above will return a QString which can cause problems later.
  7679. # So far json.dump() will fail to serialize it.
  7680. # TODO: Improve the serialization methods and remove this fix.
  7681. filename = str(filename)
  7682. if filename == "":
  7683. if silent is False:
  7684. self.inform.emit('[WARNING_NOTCL] %s' %
  7685. _("Open TCL script cancelled."))
  7686. else:
  7687. self.on_filenewscript()
  7688. try:
  7689. with open(filename, "r") as opened_script:
  7690. try:
  7691. for line in opened_script:
  7692. proc_line = str(line).strip('\n')
  7693. self.ui.code_editor.append(proc_line)
  7694. except Exception as e:
  7695. log.debug('App.on_fileopenscript() -->%s' % str(e))
  7696. if silent is False:
  7697. self.inform.emit('[ERROR] %s %s' %
  7698. ('App.on_fileopenscript() -->', str(e)))
  7699. return
  7700. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7701. self.handleTextChanged()
  7702. if silent is False:
  7703. self.inform.emit('[success] %s' %
  7704. _("TCL script file opened in Code Editor."))
  7705. # self.ui.show()
  7706. except Exception as e:
  7707. log.debug("App.on_fileopenscript() -> %s" % str(e))
  7708. def on_filerunscript(self, name=None, silent=False):
  7709. """
  7710. File menu callback for loading and running a TCL script.
  7711. :param silent: if True will not display status messages
  7712. :param name: name of a Tcl script file to be run by FlatCAM
  7713. :return: None
  7714. """
  7715. self.report_usage("on_filerunscript")
  7716. App.log.debug("on_file_runscript()")
  7717. if name:
  7718. filename = name
  7719. if self.cmd_line_headless != 1:
  7720. self.splash.showMessage('%s: %ssec\n%s' %
  7721. (_("Canvas initialization started.\n"
  7722. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7723. _("Executing FlatCAMScript file.")
  7724. ),
  7725. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7726. color=QtGui.QColor("gray"))
  7727. else:
  7728. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7729. try:
  7730. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  7731. directory=self.get_last_folder(), filter=_filter_)
  7732. except TypeError:
  7733. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  7734. # The Qt methods above will return a QString which can cause problems later.
  7735. # So far json.dump() will fail to serialize it.
  7736. # TODO: Improve the serialization methods and remove this fix.
  7737. filename = str(filename)
  7738. if filename == "":
  7739. if silent is False:
  7740. self.inform.emit('[WARNING_NOTCL] %s' %
  7741. _("Run TCL script cancelled."))
  7742. else:
  7743. if self.cmd_line_headless != 1:
  7744. if self.ui.shell_dock.isHidden():
  7745. self.ui.shell_dock.show()
  7746. try:
  7747. with open(filename, "r") as tcl_script:
  7748. cmd_line_shellfile_content = tcl_script.read()
  7749. if self.cmd_line_headless != 1:
  7750. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  7751. else:
  7752. self.shell._sysShell.exec_command(cmd_line_shellfile_content, no_echo=True)
  7753. if silent is False:
  7754. self.inform.emit('[success] %s' %
  7755. _("TCL script file opened in Code Editor and executed."))
  7756. except Exception as e:
  7757. log.debug("App.on_filerunscript() -> %s" % str(e))
  7758. sys.exit(2)
  7759. def on_file_saveproject(self, silent=False):
  7760. """
  7761. Callback for menu item File->Save Project. Saves the project to
  7762. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7763. if set to None. The project is saved by calling ``self.save_project()``.
  7764. :param silent: if True will not display status messages
  7765. :return: None
  7766. """
  7767. self.report_usage("on_file_saveproject")
  7768. if self.project_filename is None:
  7769. self.on_file_saveprojectas()
  7770. else:
  7771. self.worker_task.emit({'fcn': self.save_project,
  7772. 'params': [self.project_filename, silent]})
  7773. if self.defaults["global_open_style"] is False:
  7774. self.file_opened.emit("project", self.project_filename)
  7775. self.file_saved.emit("project", self.project_filename)
  7776. self.set_ui_title(name=self.project_filename)
  7777. self.should_we_save = False
  7778. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7779. """
  7780. Callback for menu item File->Save Project As... Opens a file
  7781. chooser and saves the project to the given file via
  7782. ``self.save_project()``.
  7783. :param make_copy if to be create a copy of the project; boolean
  7784. :param use_thread: if to be run in a separate thread; boolean
  7785. :param quit_action: if to be followed by quiting the application; boolean
  7786. :return: None
  7787. """
  7788. self.report_usage("on_file_saveprojectas")
  7789. self.date = str(datetime.today()).rpartition('.')[0]
  7790. self.date = ''.join(c for c in self.date if c not in ':-')
  7791. self.date = self.date.replace(' ', '_')
  7792. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  7793. try:
  7794. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7795. caption=_("Save Project As ..."),
  7796. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  7797. filter=filter_)
  7798. except TypeError:
  7799. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  7800. filename = str(filename)
  7801. if filename == '':
  7802. self.inform.emit('[WARNING_NOTCL] %s' %
  7803. _("Save Project cancelled."))
  7804. return
  7805. try:
  7806. f = open(filename, 'r')
  7807. f.close()
  7808. except IOError:
  7809. pass
  7810. if use_thread is True:
  7811. self.worker_task.emit({'fcn': self.save_project,
  7812. 'params': [filename, quit_action]})
  7813. else:
  7814. self.save_project(filename, quit_action)
  7815. # self.save_project(filename)
  7816. if self.defaults["global_open_style"] is False:
  7817. self.file_opened.emit("project", filename)
  7818. self.file_saved.emit("project", filename)
  7819. if not make_copy:
  7820. self.project_filename = filename
  7821. self.set_ui_title(name=self.project_filename)
  7822. self.should_we_save = False
  7823. def export_svg(self, obj_name, filename, scale_factor=0.00):
  7824. """
  7825. Exports a Geometry Object to an SVG file.
  7826. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7827. :param filename: Path to the SVG file to save to.
  7828. :param scale_factor: factor by which to change/scale the thickness of the features
  7829. :return:
  7830. """
  7831. self.report_usage("export_svg()")
  7832. if filename is None:
  7833. filename = self.defaults["global_last_save_folder"]
  7834. self.log.debug("export_svg()")
  7835. try:
  7836. obj = self.collection.get_by_name(str(obj_name))
  7837. except:
  7838. # TODO: The return behavior has not been established... should raise exception?
  7839. return "Could not retrieve object: %s" % obj_name
  7840. with self.proc_container.new(_("Exporting SVG")) as proc:
  7841. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7842. # Determine bounding area for svg export
  7843. bounds = obj.bounds()
  7844. size = obj.size()
  7845. # Convert everything to strings for use in the xml doc
  7846. svgwidth = str(size[0])
  7847. svgheight = str(size[1])
  7848. minx = str(bounds[0])
  7849. miny = str(bounds[1] - size[1])
  7850. uom = obj.units.lower()
  7851. # Add a SVG Header and footer to the svg output from shapely
  7852. # The transform flips the Y Axis so that everything renders
  7853. # properly within svg apps such as inkscape
  7854. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7855. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7856. svg_header += 'width="' + svgwidth + uom + '" '
  7857. svg_header += 'height="' + svgheight + uom + '" '
  7858. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7859. svg_header += '<g transform="scale(1,-1)">'
  7860. svg_footer = '</g> </svg>'
  7861. svg_elem = svg_header + exported_svg + svg_footer
  7862. # Parse the xml through a xml parser just to add line feeds
  7863. # and to make it look more pretty for the output
  7864. svgcode = parse_xml_string(svg_elem)
  7865. try:
  7866. with open(filename, 'w') as fp:
  7867. fp.write(svgcode.toprettyxml())
  7868. except PermissionError:
  7869. self.inform.emit('[WARNING] %s' %
  7870. _("Permission denied, saving not possible.\n"
  7871. "Most likely another app is holding the file open and not accessible."))
  7872. return 'fail'
  7873. if self.defaults["global_open_style"] is False:
  7874. self.file_opened.emit("SVG", filename)
  7875. self.file_saved.emit("SVG", filename)
  7876. self.inform.emit('[success] %s: %s' %
  7877. (_("SVG file exported to"), filename))
  7878. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  7879. """
  7880. Exports a Geometry Object to an SVG file in negative.
  7881. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7882. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  7883. :param filename: Path to the SVG file to save to.
  7884. :param boundary: thickness of a black border to surround all the features
  7885. :param scale_factor: factor by which to change/scale the thickness of the features
  7886. :param use_thread: if to be run in a separate thread; boolean
  7887. :return:
  7888. """
  7889. self.report_usage("export_negative()")
  7890. if filename is None:
  7891. filename = self.defaults["global_last_save_folder"]
  7892. self.log.debug("export_svg() negative")
  7893. try:
  7894. obj = self.collection.get_by_name(str(obj_name))
  7895. except:
  7896. # TODO: The return behavior has not been established... should raise exception?
  7897. return "Could not retrieve object: %s" % obj_name
  7898. try:
  7899. box = self.collection.get_by_name(str(box_name))
  7900. except:
  7901. # TODO: The return behavior has not been established... should raise exception?
  7902. return "Could not retrieve object: %s" % box_name
  7903. if box is None:
  7904. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  7905. (_("No object Box. Using instead"), obj))
  7906. box = obj
  7907. def make_negative_film():
  7908. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7909. # Determine bounding area for svg export
  7910. bounds = box.bounds()
  7911. size = box.size()
  7912. uom = obj.units.lower()
  7913. # Convert everything to strings for use in the xml doc
  7914. svgwidth = str(size[0] + (2 * boundary))
  7915. svgheight = str(size[1] + (2 * boundary))
  7916. minx = str(bounds[0] - boundary)
  7917. miny = str(bounds[1] + boundary + size[1])
  7918. miny_rect = str(bounds[1] - boundary)
  7919. # Add a SVG Header and footer to the svg output from shapely
  7920. # The transform flips the Y Axis so that everything renders
  7921. # properly within svg apps such as inkscape
  7922. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7923. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7924. svg_header += 'width="' + svgwidth + uom + '" '
  7925. svg_header += 'height="' + svgheight + uom + '" '
  7926. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7927. svg_header += '>'
  7928. svg_header += '<g transform="scale(1,-1)">'
  7929. svg_footer = '</g> </svg>'
  7930. # Change the attributes of the exported SVG
  7931. # We don't need stroke-width - wrong, we do when we have lines with certain width
  7932. # We set opacity to maximum
  7933. # We set the color to WHITE
  7934. root = ET.fromstring(exported_svg)
  7935. for child in root:
  7936. child.set('fill', '#FFFFFF')
  7937. child.set('opacity', '1.0')
  7938. child.set('stroke', '#FFFFFF')
  7939. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  7940. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  7941. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  7942. first_svg_elem_tag = 'rect'
  7943. first_svg_elem_attribs = {
  7944. 'x': minx,
  7945. 'y': miny_rect,
  7946. 'width': svgwidth,
  7947. 'height': svgheight,
  7948. 'id': 'neg_rect',
  7949. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  7950. }
  7951. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  7952. exported_svg = ET.tostring(root)
  7953. svg_elem = svg_header + str(exported_svg) + svg_footer
  7954. # Parse the xml through a xml parser just to add line feeds
  7955. # and to make it look more pretty for the output
  7956. doc = parse_xml_string(svg_elem)
  7957. try:
  7958. with open(filename, 'w') as fp:
  7959. fp.write(doc.toprettyxml())
  7960. except PermissionError:
  7961. self.inform.emit('[WARNING] %s' %
  7962. _("Permission denied, saving not possible.\n"
  7963. "Most likely another app is holding the file open and not accessible."))
  7964. return 'fail'
  7965. if self.defaults["global_open_style"] is False:
  7966. self.file_opened.emit("SVG", filename)
  7967. self.file_saved.emit("SVG", filename)
  7968. self.inform.emit('[success] %s: %s' %
  7969. (_("SVG file exported to"), filename))
  7970. if use_thread is True:
  7971. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  7972. def job_thread_film(app_obj):
  7973. try:
  7974. make_negative_film()
  7975. except Exception as e:
  7976. proc.done()
  7977. return
  7978. proc.done()
  7979. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  7980. else:
  7981. make_negative_film()
  7982. def export_svg_positive(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  7983. """
  7984. Exports a Geometry Object to an SVG file in positive black.
  7985. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7986. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  7987. :param filename: Path to the SVG file to save to.
  7988. :param scale_factor: factor by which to change/scale the thickness of the features
  7989. :param use_thread: if to be run in a separate thread; boolean
  7990. :return:
  7991. """
  7992. self.report_usage("export_svg_positive()")
  7993. if filename is None:
  7994. filename = self.defaults["global_last_save_folder"]
  7995. self.log.debug("export_svg() black")
  7996. try:
  7997. obj = self.collection.get_by_name(str(obj_name))
  7998. except:
  7999. # TODO: The return behavior has not been established... should raise exception?
  8000. return "Could not retrieve object: %s" % obj_name
  8001. try:
  8002. box = self.collection.get_by_name(str(box_name))
  8003. except:
  8004. # TODO: The return behavior has not been established... should raise exception?
  8005. return "Could not retrieve object: %s" % box_name
  8006. if box is None:
  8007. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  8008. (_("No object Box. Using instead"), obj))
  8009. box = obj
  8010. def make_positive_film():
  8011. exported_svg = obj.export_svg(scale_factor=scale_factor)
  8012. self.progress.emit(40)
  8013. # Change the attributes of the exported SVG
  8014. # We don't need stroke-width
  8015. # We set opacity to maximum
  8016. # We set the colour to WHITE
  8017. root = ET.fromstring(exported_svg)
  8018. for child in root:
  8019. child.set('fill', str(self.defaults['tools_film_color']))
  8020. child.set('opacity', '1.0')
  8021. child.set('stroke', str(self.defaults['tools_film_color']))
  8022. exported_svg = ET.tostring(root)
  8023. # Determine bounding area for svg export
  8024. bounds = box.bounds()
  8025. size = box.size()
  8026. # This contain the measure units
  8027. uom = obj.units.lower()
  8028. # Define a boundary around SVG of about 1.0mm (~39mils)
  8029. if uom in "mm":
  8030. boundary = 1.0
  8031. else:
  8032. boundary = 0.0393701
  8033. self.progress.emit(80)
  8034. # Convert everything to strings for use in the xml doc
  8035. svgwidth = str(size[0] + (2 * boundary))
  8036. svgheight = str(size[1] + (2 * boundary))
  8037. minx = str(bounds[0] - boundary)
  8038. miny = str(bounds[1] + boundary + size[1])
  8039. self.log.debug(minx)
  8040. self.log.debug(miny)
  8041. # Add a SVG Header and footer to the svg output from shapely
  8042. # The transform flips the Y Axis so that everything renders
  8043. # properly within svg apps such as inkscape
  8044. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8045. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8046. svg_header += 'width="' + svgwidth + uom + '" '
  8047. svg_header += 'height="' + svgheight + uom + '" '
  8048. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  8049. svg_header += '>'
  8050. svg_header += '<g transform="scale(1,-1)">'
  8051. svg_footer = '</g> </svg>'
  8052. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  8053. self.progress.emit(90)
  8054. # Parse the xml through a xml parser just to add line feeds
  8055. # and to make it look more pretty for the output
  8056. doc = parse_xml_string(svg_elem)
  8057. try:
  8058. with open(filename, 'w') as fp:
  8059. fp.write(doc.toprettyxml())
  8060. except PermissionError:
  8061. self.inform.emit('[WARNING] %s' %
  8062. _("Permission denied, saving not possible.\n"
  8063. "Most likely another app is holding the file open and not accessible."))
  8064. return 'fail'
  8065. self.progress.emit(100)
  8066. if self.defaults["global_open_style"] is False:
  8067. self.file_opened.emit("SVG", filename)
  8068. self.file_saved.emit("SVG", filename)
  8069. self.inform.emit('[success] %s: %s' %
  8070. (_("SVG file exported to"), filename))
  8071. if use_thread is True:
  8072. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  8073. def job_thread_film(app_obj):
  8074. try:
  8075. make_positive_film()
  8076. except Exception as e:
  8077. proc.done()
  8078. return
  8079. proc.done()
  8080. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  8081. else:
  8082. make_positive_film()
  8083. def save_source_file(self, obj_name, filename, use_thread=True):
  8084. """
  8085. Exports a FlatCAM Object to an Gerber/Excellon file.
  8086. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8087. :param filename: Path to the Gerber file to save to.
  8088. :param use_thread: if to be run in a separate thread
  8089. :return:
  8090. """
  8091. self.report_usage("save source file()")
  8092. if filename is None:
  8093. filename = self.defaults["global_last_save_folder"]
  8094. self.log.debug("save source file()")
  8095. obj = self.collection.get_by_name(obj_name)
  8096. file_string = StringIO(obj.source_file)
  8097. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8098. try:
  8099. with open(filename, 'w') as file:
  8100. file.writelines('G04*\n')
  8101. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8102. (obj.kind.upper(), str(self.version), str(self.version_date)))
  8103. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8104. file.writelines('G04 Created on : %s*\n' % time_string)
  8105. for line in file_string:
  8106. file.writelines(line)
  8107. except PermissionError:
  8108. self.inform.emit('[WARNING] %s' %
  8109. _("Permission denied, saving not possible.\n"
  8110. "Most likely another app is holding the file open and not accessible."))
  8111. return 'fail'
  8112. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  8113. """
  8114. Exports a Excellon Object to an Excellon file.
  8115. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  8116. :param filename: Path to the Excellon file to save to.
  8117. :param use_thread: if to be run in a separate thread
  8118. :return:
  8119. """
  8120. self.report_usage("export_excellon()")
  8121. if filename is None:
  8122. filename = self.defaults["global_last_save_folder"]
  8123. self.log.debug("export_excellon()")
  8124. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  8125. self.defaults["excellon_exp_decimals"]
  8126. )
  8127. units = ''
  8128. if local_use is None:
  8129. try:
  8130. obj = self.collection.get_by_name(str(obj_name))
  8131. except:
  8132. # TODO: The return behavior has not been established... should raise exception?
  8133. return "Could not retrieve object: %s" % obj_name
  8134. else:
  8135. obj = local_use
  8136. # updated units
  8137. eunits = self.defaults["excellon_exp_units"]
  8138. ewhole = self.defaults["excellon_exp_integer"]
  8139. efract = self.defaults["excellon_exp_decimals"]
  8140. ezeros = self.defaults["excellon_exp_zeros"]
  8141. eformat = self.defaults["excellon_exp_format"]
  8142. slot_type = self.defaults["excellon_exp_slot_type"]
  8143. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8144. if fc_units == 'MM':
  8145. factor = 1 if eunits == 'METRIC' else 0.03937
  8146. else:
  8147. factor = 25.4 if eunits == 'METRIC' else 1
  8148. def make_excellon():
  8149. try:
  8150. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8151. header = 'M48\n'
  8152. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  8153. (str(self.version), str(self.version_date))
  8154. header += ';Filename: %s' % str(obj_name) + '\n'
  8155. header += ';Created on : %s' % time_str + '\n'
  8156. if eformat == 'dec':
  8157. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  8158. header += eunits + '\n'
  8159. for tool in obj.tools:
  8160. if eunits == 'METRIC':
  8161. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8162. tool=str(tool),
  8163. dec=2)
  8164. else:
  8165. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8166. tool=str(tool),
  8167. dec=4)
  8168. else:
  8169. if ezeros == 'LZ':
  8170. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8171. form='ndec', e_zeros='LZ', factor=factor,
  8172. slot_type=slot_type)
  8173. header += '%s,%s\n' % (eunits, 'LZ')
  8174. header += format_exc
  8175. for tool in obj.tools:
  8176. if eunits == 'METRIC':
  8177. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8178. tool=str(tool),
  8179. dec=2)
  8180. else:
  8181. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8182. tool=str(tool),
  8183. dec=4)
  8184. else:
  8185. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8186. form='ndec', e_zeros='TZ', factor=factor,
  8187. slot_type=slot_type)
  8188. header += '%s,%s\n' % (eunits, 'TZ')
  8189. header += format_exc
  8190. for tool in obj.tools:
  8191. if eunits == 'METRIC':
  8192. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8193. tool=str(tool),
  8194. dec=2)
  8195. else:
  8196. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8197. tool=str(tool),
  8198. dec=4)
  8199. header += '%\n'
  8200. footer = 'M30\n'
  8201. exported_excellon = header
  8202. exported_excellon += excellon_code
  8203. exported_excellon += footer
  8204. if local_use is None:
  8205. try:
  8206. with open(filename, 'w') as fp:
  8207. fp.write(exported_excellon)
  8208. except PermissionError:
  8209. self.inform.emit('[WARNING] %s' %
  8210. _("Permission denied, saving not possible.\n"
  8211. "Most likely another app is holding the file open and not accessible."))
  8212. return 'fail'
  8213. if self.defaults["global_open_style"] is False:
  8214. self.file_opened.emit("Excellon", filename)
  8215. self.file_saved.emit("Excellon", filename)
  8216. self.inform.emit('[success] %s: %s' %
  8217. (_("Excellon file exported to"), filename))
  8218. else:
  8219. return exported_excellon
  8220. except Exception as e:
  8221. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  8222. return 'fail'
  8223. if use_thread is True:
  8224. with self.proc_container.new(_("Exporting Excellon")) as proc:
  8225. def job_thread_exc(app_obj):
  8226. ret = make_excellon()
  8227. if ret == 'fail':
  8228. self.inform.emit('[ERROR_NOTCL] %s' %
  8229. _('Could not export Excellon file.'))
  8230. return
  8231. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8232. else:
  8233. ret = make_excellon()
  8234. if ret == 'fail':
  8235. self.inform.emit('[ERROR_NOTCL] %s' %
  8236. _('Could not export Excellon file.'))
  8237. return 'fail'
  8238. if local_use is not None:
  8239. return ret
  8240. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  8241. """
  8242. Exports a Gerber Object to an Gerber file.
  8243. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  8244. :param filename: Path to the Gerber file to save to.
  8245. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8246. When not None, the value will be the actual Gerber object for which to create the Gerber code
  8247. :param use_thread: if to be run in a separate thread
  8248. :return:
  8249. """
  8250. self.report_usage("export_gerber()")
  8251. if filename is None:
  8252. filename = self.defaults["global_last_save_folder"]
  8253. self.log.debug("export_gerber()")
  8254. if local_use is None:
  8255. try:
  8256. obj = self.collection.get_by_name(str(obj_name))
  8257. except:
  8258. # TODO: The return behavior has not been established... should raise exception?
  8259. return "Could not retrieve object: %s" % obj_name
  8260. else:
  8261. obj = local_use
  8262. # updated units
  8263. gunits = self.defaults["gerber_exp_units"]
  8264. gwhole = self.defaults["gerber_exp_integer"]
  8265. gfract = self.defaults["gerber_exp_decimals"]
  8266. gzeros = self.defaults["gerber_exp_zeros"]
  8267. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8268. if fc_units == 'MM':
  8269. factor = 1 if gunits == 'MM' else 0.03937
  8270. else:
  8271. factor = 25.4 if gunits == 'MM' else 1
  8272. def make_gerber():
  8273. try:
  8274. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8275. header = 'G04*\n'
  8276. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  8277. (str(self.version), str(self.version_date))
  8278. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  8279. header += 'G04 Created on : %s*' % time_str + '\n'
  8280. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  8281. header += "%MO{units}*%\n".format(units=gunits)
  8282. for apid in obj.apertures:
  8283. if obj.apertures[apid]['type'] == 'C':
  8284. header += "%ADD{apid}{type},{size}*%\n".format(
  8285. apid=str(apid),
  8286. type='C',
  8287. size=(factor * obj.apertures[apid]['size'])
  8288. )
  8289. elif obj.apertures[apid]['type'] == 'R':
  8290. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8291. apid=str(apid),
  8292. type='R',
  8293. width=(factor * obj.apertures[apid]['width']),
  8294. height=(factor * obj.apertures[apid]['height'])
  8295. )
  8296. elif obj.apertures[apid]['type'] == 'O':
  8297. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8298. apid=str(apid),
  8299. type='O',
  8300. width=(factor * obj.apertures[apid]['width']),
  8301. height=(factor * obj.apertures[apid]['height'])
  8302. )
  8303. header += '\n'
  8304. # obsolete units but some software may need it
  8305. if gunits == 'IN':
  8306. header += 'G70*\n'
  8307. else:
  8308. header += 'G71*\n'
  8309. # Absolute Mode
  8310. header += 'G90*\n'
  8311. header += 'G01*\n'
  8312. # positive polarity
  8313. header += '%LPD*%\n'
  8314. footer = 'M02*\n'
  8315. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8316. exported_gerber = header
  8317. exported_gerber += gerber_code
  8318. exported_gerber += footer
  8319. if local_use is None:
  8320. try:
  8321. with open(filename, 'w') as fp:
  8322. fp.write(exported_gerber)
  8323. except PermissionError:
  8324. self.inform.emit('[WARNING] %s' %
  8325. _("Permission denied, saving not possible.\n"
  8326. "Most likely another app is holding the file open and not accessible."))
  8327. return 'fail'
  8328. if self.defaults["global_open_style"] is False:
  8329. self.file_opened.emit("Gerber", filename)
  8330. self.file_saved.emit("Gerber", filename)
  8331. self.inform.emit('[success] %s: %s' %
  8332. (_("Gerber file exported to"), filename))
  8333. else:
  8334. return exported_gerber
  8335. except Exception as e:
  8336. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8337. return 'fail'
  8338. if use_thread is True:
  8339. with self.proc_container.new(_("Exporting Gerber")) as proc:
  8340. def job_thread_grb(app_obj):
  8341. ret = make_gerber()
  8342. if ret == 'fail':
  8343. self.inform.emit('[ERROR_NOTCL] %s' %
  8344. _('Could not export Gerber file.'))
  8345. return
  8346. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8347. else:
  8348. ret = make_gerber()
  8349. if ret == 'fail':
  8350. self.inform.emit('[ERROR_NOTCL] %s' %
  8351. _('Could not export Gerber file.'))
  8352. return 'fail'
  8353. if local_use is not None:
  8354. return ret
  8355. def export_dxf(self, obj_name, filename, use_thread=True):
  8356. """
  8357. Exports a Geometry Object to an DXF file.
  8358. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8359. :param filename: Path to the DXF file to save to.
  8360. :param use_thread: if to be run in a separate thread
  8361. :return:
  8362. """
  8363. self.report_usage("export_dxf()")
  8364. if filename is None:
  8365. filename = self.defaults["global_last_save_folder"]
  8366. self.log.debug("export_dxf()")
  8367. format_exc = ''
  8368. units = ''
  8369. try:
  8370. obj = self.collection.get_by_name(str(obj_name))
  8371. except:
  8372. # TODO: The return behavior has not been established... should raise exception?
  8373. return "Could not retrieve object: %s" % obj_name
  8374. # updated units
  8375. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8376. if units == 'IN' or units == 'INCH':
  8377. units = 'INCH'
  8378. elif units == 'MM' or units == 'METIRC':
  8379. units ='METRIC'
  8380. def make_dxf():
  8381. try:
  8382. dxf_code = obj.export_dxf()
  8383. dxf_code.saveas(filename)
  8384. if self.defaults["global_open_style"] is False:
  8385. self.file_opened.emit("DXF", filename)
  8386. self.file_saved.emit("DXF", filename)
  8387. self.inform.emit('[success] %s: %s' %
  8388. (_("DXF file exported to"), filename))
  8389. except:
  8390. return 'fail'
  8391. if use_thread is True:
  8392. with self.proc_container.new(_("Exporting DXF")) as proc:
  8393. def job_thread_exc(app_obj):
  8394. ret = make_dxf()
  8395. if ret == 'fail':
  8396. app_obj.inform.emit('[WARNING_NOTCL] %s' %
  8397. _('Could not export DXF file.'))
  8398. return
  8399. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8400. else:
  8401. ret = make_dxf()
  8402. if ret == 'fail':
  8403. self.inform.emit('[WARNING_NOTCL] %s' %
  8404. _('Could not export DXF file.'))
  8405. return
  8406. def import_svg(self, filename, geo_type='geometry', outname=None):
  8407. """
  8408. Adds a new Geometry Object to the projects and populates
  8409. it with shapes extracted from the SVG file.
  8410. :param filename: Path to the SVG file.
  8411. :param outname:
  8412. :return:
  8413. """
  8414. self.report_usage("import_svg()")
  8415. obj_type = ""
  8416. if geo_type is None or geo_type == "geometry":
  8417. obj_type = "geometry"
  8418. elif geo_type == "gerber":
  8419. obj_type = geo_type
  8420. else:
  8421. self.inform.emit('[ERROR_NOTCL] %s' %
  8422. _("Not supported type is picked as parameter. "
  8423. "Only Geometry and Gerber are supported"))
  8424. return
  8425. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8426. def obj_init(geo_obj, app_obj):
  8427. geo_obj.import_svg(filename, obj_type, units=units)
  8428. geo_obj.multigeo = False
  8429. with self.proc_container.new(_("Importing SVG")) as proc:
  8430. # Object name
  8431. name = outname or filename.split('/')[-1].split('\\')[-1]
  8432. self.new_object(obj_type, name, obj_init, autoselected=False)
  8433. self.progress.emit(20)
  8434. # Register recent file
  8435. self.file_opened.emit("svg", filename)
  8436. # GUI feedback
  8437. self.inform.emit('[success] %s: %s' %
  8438. (_("Opened"), filename))
  8439. self.progress.emit(100)
  8440. def import_dxf(self, filename, geo_type='geometry', outname=None):
  8441. """
  8442. Adds a new Geometry Object to the projects and populates
  8443. it with shapes extracted from the DXF file.
  8444. :param filename: Path to the DXF file.
  8445. :param outname:
  8446. :type putname: str
  8447. :return:
  8448. """
  8449. self.report_usage("import_dxf()")
  8450. obj_type = ""
  8451. if geo_type is None or geo_type == "geometry":
  8452. obj_type = "geometry"
  8453. elif geo_type == "gerber":
  8454. obj_type = geo_type
  8455. else:
  8456. self.inform.emit('[ERROR_NOTCL] %s' %
  8457. _("Not supported type is picked as parameter. "
  8458. "Only Geometry and Gerber are supported"))
  8459. return
  8460. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8461. def obj_init(geo_obj, app_obj):
  8462. geo_obj.import_dxf(filename, obj_type, units=units)
  8463. geo_obj.multigeo = False
  8464. with self.proc_container.new(_("Importing DXF")) as proc:
  8465. # Object name
  8466. name = outname or filename.split('/')[-1].split('\\')[-1]
  8467. self.new_object(obj_type, name, obj_init, autoselected=False)
  8468. self.progress.emit(20)
  8469. # Register recent file
  8470. self.file_opened.emit("dxf", filename)
  8471. # GUI feedback
  8472. self.inform.emit('[success] %s: %s' %
  8473. (_("Opened"), filename))
  8474. self.progress.emit(100)
  8475. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  8476. """
  8477. Adds a new Geometry Object to the projects and populates
  8478. it with shapes extracted from the SVG file.
  8479. :param filename: Path to the SVG file.
  8480. :param o_type: type of FlatCAM objeect
  8481. :param dpi: dot per inch
  8482. :param mode: black or color
  8483. :param mask: dictate the level of detail
  8484. :param outname: name for the resulting file
  8485. :return:
  8486. """
  8487. self.report_usage("import_image()")
  8488. if o_type is None or o_type == "geometry":
  8489. obj_type = "geometry"
  8490. elif o_type == "gerber":
  8491. obj_type = o_type
  8492. else:
  8493. self.inform.emit('[ERROR_NOTCL] %s' %
  8494. _("Not supported type is picked as parameter. "
  8495. "Only Geometry and Gerber are supported"))
  8496. return
  8497. def obj_init(geo_obj, app_obj):
  8498. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  8499. geo_obj.multigeo = False
  8500. with self.proc_container.new(_("Importing Image")) as proc:
  8501. # Object name
  8502. name = outname or filename.split('/')[-1].split('\\')[-1]
  8503. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  8504. self.new_object(obj_type, name, obj_init)
  8505. self.progress.emit(20)
  8506. # Register recent file
  8507. self.file_opened.emit("image", filename)
  8508. # GUI feedback
  8509. self.inform.emit('[success] %s: %s' %
  8510. (_("Opened"), filename))
  8511. self.progress.emit(100)
  8512. def open_gerber(self, filename, outname=None):
  8513. """
  8514. Opens a Gerber file, parses it and creates a new object for
  8515. it in the program. Thread-safe.
  8516. :param outname: Name of the resulting object. None causes the
  8517. name to be that of the file.
  8518. :param filename: Gerber file filename
  8519. :type filename: str
  8520. :param follow: If true, the parser will not create polygons, just lines
  8521. following the gerber path.
  8522. :type follow: bool
  8523. :return: None
  8524. """
  8525. # How the object should be initialized
  8526. def obj_init(gerber_obj, app_obj):
  8527. assert isinstance(gerber_obj, FlatCAMGerber), \
  8528. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  8529. # Opening the file happens here
  8530. self.progress.emit(30)
  8531. try:
  8532. gerber_obj.parse_file(filename)
  8533. except IOError:
  8534. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8535. (_("Failed to open file"), filename))
  8536. app_obj.progress.emit(0)
  8537. return "fail"
  8538. except ParseError as err:
  8539. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' %
  8540. (_("Failed to parse file"), filename, str(err)))
  8541. app_obj.progress.emit(0)
  8542. self.log.error(str(err))
  8543. return "fail"
  8544. except Exception as e:
  8545. log.debug("App.open_gerber() --> %s" % str(e))
  8546. msg = '[ERROR] %s' % \
  8547. _("An internal error has occurred. See shell.\n")
  8548. msg += traceback.format_exc()
  8549. app_obj.inform.emit(msg)
  8550. return "fail"
  8551. if gerber_obj.is_empty():
  8552. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  8553. # self.collection.set_active(gerber_obj.options["name"])
  8554. # self.collection.delete_active()
  8555. self.inform.emit('[ERROR_NOTCL] %s' %
  8556. _("Object is not Gerber file or empty. Aborting object creation."))
  8557. return "fail"
  8558. # Further parsing
  8559. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  8560. App.log.debug("open_gerber()")
  8561. with self.proc_container.new(_("Opening Gerber")) as proc:
  8562. self.progress.emit(10)
  8563. # Object name
  8564. name = outname or filename.split('/')[-1].split('\\')[-1]
  8565. # # ## Object creation # ##
  8566. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  8567. if ret == 'fail':
  8568. self.inform.emit('[ERROR_NOTCL]%s' %
  8569. _(' Open Gerber failed. Probable not a Gerber file.'))
  8570. return
  8571. # Register recent file
  8572. self.file_opened.emit("gerber", filename)
  8573. self.progress.emit(100)
  8574. # GUI feedback
  8575. self.inform.emit('[success] %s: %s' %
  8576. (_("Opened"), filename))
  8577. def open_excellon(self, filename, outname=None, plot=True):
  8578. """
  8579. Opens an Excellon file, parses it and creates a new object for
  8580. it in the program. Thread-safe.
  8581. :param outname: Name of the resulting object. None causes the
  8582. name to be that of the file.
  8583. :param filename: Excellon file filename
  8584. :type filename: str
  8585. :return: None
  8586. """
  8587. App.log.debug("open_excellon()")
  8588. # How the object should be initialized
  8589. def obj_init(excellon_obj, app_obj):
  8590. # self.progress.emit(20)
  8591. try:
  8592. ret = excellon_obj.parse_file(filename=filename)
  8593. if ret == "fail":
  8594. log.debug("Excellon parsing failed.")
  8595. self.inform.emit('[ERROR_NOTCL] %s' %
  8596. _("This is not Excellon file."))
  8597. return "fail"
  8598. except IOError:
  8599. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8600. (_("Cannot open file"), filename))
  8601. log.debug("Could not open Excellon object.")
  8602. self.progress.emit(0) # TODO: self and app_bjj mixed
  8603. return "fail"
  8604. except:
  8605. msg = '[ERROR_NOTCL] %s' % \
  8606. _("An internal error has occurred. See shell.\n")
  8607. msg += traceback.format_exc()
  8608. app_obj.inform.emit(msg)
  8609. return "fail"
  8610. ret = excellon_obj.create_geometry()
  8611. if ret == 'fail':
  8612. log.debug("Could not create geometry for Excellon object.")
  8613. return "fail"
  8614. for tool in excellon_obj.tools:
  8615. if excellon_obj.tools[tool]['solid_geometry']:
  8616. return
  8617. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8618. (_("No geometry found in file"), filename))
  8619. return "fail"
  8620. with self.proc_container.new(_("Opening Excellon.")):
  8621. # Object name
  8622. name = outname or filename.split('/')[-1].split('\\')[-1]
  8623. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8624. if ret_val == 'fail':
  8625. self.inform.emit('[ERROR_NOTCL] %s' %
  8626. _('Open Excellon file failed. Probable not an Excellon file.'))
  8627. return
  8628. # Register recent file
  8629. self.file_opened.emit("excellon", filename)
  8630. # GUI feedback
  8631. self.inform.emit('[success] %s: %s' %
  8632. (_("Opened"), filename))
  8633. def open_gcode(self, filename, outname=None, plot=True):
  8634. """
  8635. Opens a G-gcode file, parses it and creates a new object for
  8636. it in the program. Thread-safe.
  8637. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8638. :param filename: G-code file filename
  8639. :type filename: str
  8640. :return: None
  8641. """
  8642. App.log.debug("open_gcode()")
  8643. # How the object should be initialized
  8644. def obj_init(job_obj, app_obj_):
  8645. """
  8646. :param job_obj: the resulting object
  8647. :type app_obj_: App
  8648. """
  8649. assert isinstance(app_obj_, App), \
  8650. "Initializer expected App, got %s" % type(app_obj_)
  8651. self.progress.emit(10)
  8652. try:
  8653. f = open(filename)
  8654. gcode = f.read()
  8655. f.close()
  8656. except IOError:
  8657. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  8658. (_("Failed to open"), filename))
  8659. self.progress.emit(0)
  8660. return "fail"
  8661. job_obj.gcode = gcode
  8662. self.progress.emit(20)
  8663. ret = job_obj.gcode_parse()
  8664. if ret == "fail":
  8665. self.inform.emit('[ERROR_NOTCL] %s' %
  8666. _("This is not GCODE"))
  8667. return "fail"
  8668. self.progress.emit(60)
  8669. job_obj.create_geometry()
  8670. with self.proc_container.new(_("Opening G-Code.")):
  8671. # Object name
  8672. name = outname or filename.split('/')[-1].split('\\')[-1]
  8673. # New object creation and file processing
  8674. ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8675. if ret == 'fail':
  8676. self.inform.emit('[ERROR_NOTCL] %s' %
  8677. _("Failed to create CNCJob Object. Probable not a GCode file.\n "
  8678. "Attempting to create a FlatCAM CNCJob Object from "
  8679. "G-Code file failed during processing"))
  8680. return "fail"
  8681. # Register recent file
  8682. self.file_opened.emit("cncjob", filename)
  8683. # GUI feedback
  8684. self.inform.emit('[success] %s: %s' %
  8685. (_("Opened"), filename))
  8686. self.progress.emit(100)
  8687. def open_config_file(self, filename, run_from_arg=None):
  8688. """
  8689. Loads a config file from the specified file.
  8690. :param filename: Name of the file from which to load.
  8691. :type filename: str
  8692. :return: None
  8693. """
  8694. App.log.debug("Opening config file: " + filename)
  8695. if run_from_arg:
  8696. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8697. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8698. _("Opening FlatCAM Config file.")),
  8699. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8700. color=QtGui.QColor("gray"))
  8701. # add the tab if it was closed
  8702. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  8703. # first clear previous text in text editor (if any)
  8704. self.ui.code_editor.clear()
  8705. # Switch plot_area to CNCJob tab
  8706. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  8707. try:
  8708. if filename:
  8709. f = QtCore.QFile(filename)
  8710. if f.open(QtCore.QIODevice.ReadOnly):
  8711. stream = QtCore.QTextStream(f)
  8712. gcode_edited = stream.readAll()
  8713. self.ui.code_editor.setPlainText(gcode_edited)
  8714. f.close()
  8715. except IOError:
  8716. App.log.error("Failed to open config file: %s" % filename)
  8717. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8718. (_("Failed to open config file"), filename))
  8719. return
  8720. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  8721. """
  8722. Loads a project from the specified file.
  8723. 1) Loads and parses file
  8724. 2) Registers the file as recently opened.
  8725. 3) Calls on_file_new()
  8726. 4) Updates options
  8727. 5) Calls new_object() with the object's from_dict() as init method.
  8728. 6) Calls plot_all() if plot=True
  8729. :param filename: Name of the file from which to load.
  8730. :type filename: str
  8731. :param run_from_arg: True if run for arguments
  8732. :param plot: If True plot all objects in the project
  8733. :param cli: run from command line
  8734. :return: None
  8735. """
  8736. App.log.debug("Opening project: " + filename)
  8737. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8738. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8739. if cli is None:
  8740. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8741. if run_from_arg:
  8742. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8743. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8744. _("Opening FlatCAM Project file.")),
  8745. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8746. color=QtGui.QColor("gray"))
  8747. # Open and parse an uncompressed Project file
  8748. try:
  8749. f = open(filename, 'r')
  8750. except IOError:
  8751. App.log.error("Failed to open project file: %s" % filename)
  8752. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8753. (_("Failed to open project file"), filename))
  8754. return
  8755. try:
  8756. d = json.load(f, object_hook=dict2obj)
  8757. except Exception as e:
  8758. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8759. (filename, str(e)))
  8760. f.close()
  8761. # Open and parse a compressed Project file
  8762. try:
  8763. with lzma.open(filename) as f:
  8764. file_content = f.read().decode('utf-8')
  8765. d = json.loads(file_content, object_hook=dict2obj)
  8766. except Exception as e:
  8767. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8768. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8769. (_("Failed to open project file"), filename))
  8770. return
  8771. # Clear the current project
  8772. # # NOT THREAD SAFE # ##
  8773. if run_from_arg is True:
  8774. pass
  8775. elif cli is True:
  8776. self.delete_selection_shape()
  8777. else:
  8778. self.on_file_new()
  8779. # Project options
  8780. self.options.update(d['options'])
  8781. self.project_filename = filename
  8782. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8783. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8784. if cli is None:
  8785. self.set_screen_units(self.options["units"])
  8786. # Re create objects
  8787. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8788. for obj in d['objs']:
  8789. def obj_init(obj_inst, app_inst):
  8790. obj_inst.from_dict(obj)
  8791. App.log.debug("Recreating from opened project an %s object: %s" %
  8792. (obj['kind'].capitalize(), obj['options']['name']))
  8793. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8794. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8795. if cli is None:
  8796. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8797. obj['kind'].upper(),
  8798. obj['options']['name']
  8799. )
  8800. )
  8801. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  8802. self.inform.emit('[success] %s: %s' %
  8803. (_("Project loaded from"), filename))
  8804. self.should_we_save = False
  8805. self.file_opened.emit("project", filename)
  8806. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8807. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8808. if cli is None:
  8809. self.set_ui_title(name=self.project_filename)
  8810. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8811. def propagate_defaults(self, silent=False):
  8812. """
  8813. This method is used to set default values in classes. It's
  8814. an alternative to project options but allows the use
  8815. of values invisible to the user.
  8816. :return: None
  8817. """
  8818. if silent is False:
  8819. self.log.debug("propagate_defaults()")
  8820. # Which objects to update the given parameters.
  8821. routes = {
  8822. "global_zdownrate": CNCjob,
  8823. "excellon_zeros": Excellon,
  8824. "excellon_format_upper_in": Excellon,
  8825. "excellon_format_lower_in": Excellon,
  8826. "excellon_format_upper_mm": Excellon,
  8827. "excellon_format_lower_mm": Excellon,
  8828. "excellon_units": Excellon,
  8829. "gerber_use_buffer_for_union": Gerber,
  8830. "geometry_multidepth": Geometry
  8831. }
  8832. for param in routes:
  8833. if param in routes[param].defaults:
  8834. try:
  8835. routes[param].defaults[param] = self.defaults[param]
  8836. if silent is False:
  8837. self.log.debug(" " + param + " OK")
  8838. except KeyError:
  8839. if silent is False:
  8840. self.log.debug(" ERROR: " + param + " not in defaults.")
  8841. else:
  8842. # Try extracting the name:
  8843. # classname_param here is param in the object
  8844. if param.find(routes[param].__name__.lower() + "_") == 0:
  8845. p = param[len(routes[param].__name__) + 1:]
  8846. if p in routes[param].defaults:
  8847. routes[param].defaults[p] = self.defaults[param]
  8848. if silent is False:
  8849. self.log.debug(" " + param + " OK!")
  8850. def plot_all(self, zoom=True):
  8851. """
  8852. Re-generates all plots from all objects.
  8853. :return: None
  8854. """
  8855. self.log.debug("Plot_all()")
  8856. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  8857. for obj in self.collection.get_list():
  8858. def worker_task(obj):
  8859. with self.proc_container.new("Plotting"):
  8860. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8861. if zoom:
  8862. self.object_plotted.emit(obj)
  8863. # Send to worker
  8864. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  8865. def register_folder(self, filename):
  8866. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8867. def register_save_folder(self, filename):
  8868. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8869. def set_progress_bar(self, percentage, text=""):
  8870. self.ui.progress_bar.setValue(int(percentage))
  8871. def setup_shell(self):
  8872. """
  8873. Creates shell functions. Runs once at startup.
  8874. :return: None
  8875. """
  8876. self.log.debug("setup_shell()")
  8877. def shelp(p=None):
  8878. if not p:
  8879. return _("Available commands:\n") + \
  8880. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  8881. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  8882. if p not in commands:
  8883. return "Unknown command: %s" % p
  8884. return commands[p]["help"]
  8885. # --- Migrated to new architecture ---
  8886. # def options(name):
  8887. # ops = self.collection.get_by_name(str(name)).options
  8888. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  8889. def h(*args):
  8890. """
  8891. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  8892. and standalone parameters into list.
  8893. """
  8894. kwa = {}
  8895. a = []
  8896. n = len(args)
  8897. name = None
  8898. for i in range(n):
  8899. match = re.search(r'^-([a-zA-Z].*)', args[i])
  8900. if match:
  8901. assert name is None
  8902. name = match.group(1)
  8903. continue
  8904. if name is None:
  8905. a.append(args[i])
  8906. else:
  8907. kwa[name] = args[i]
  8908. name = None
  8909. return a, kwa
  8910. @contextmanager
  8911. def wait_signal(signal, timeout=10000):
  8912. """
  8913. Block loop until signal emitted, timeout (ms) elapses
  8914. or unhandled exception happens in a thread.
  8915. :param timeout: time after which the loop is exited
  8916. :param signal: Signal to wait for.
  8917. """
  8918. loop = QtCore.QEventLoop()
  8919. # Normal termination
  8920. signal.connect(loop.quit)
  8921. # Termination by exception in thread
  8922. self.thread_exception.connect(loop.quit)
  8923. status = {'timed_out': False}
  8924. def report_quit():
  8925. status['timed_out'] = True
  8926. loop.quit()
  8927. yield
  8928. # Temporarily change how exceptions are managed.
  8929. oeh = sys.excepthook
  8930. ex = []
  8931. def except_hook(type_, value, traceback_):
  8932. ex.append(value)
  8933. oeh(type_, value, traceback_)
  8934. sys.excepthook = except_hook
  8935. # Terminate on timeout
  8936. if timeout is not None:
  8937. QtCore.QTimer.singleShot(timeout, report_quit)
  8938. # # ## Block ## ##
  8939. loop.exec_()
  8940. # Restore exception management
  8941. sys.excepthook = oeh
  8942. if ex:
  8943. self.raiseTclError(str(ex[0]))
  8944. if status['timed_out']:
  8945. raise Exception('Timed out!')
  8946. def make_docs():
  8947. output = ''
  8948. import collections
  8949. od = collections.OrderedDict(sorted(commands.items()))
  8950. for cmd_, val in od.items():
  8951. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  8952. t = val['help']
  8953. usage_i = t.find('>')
  8954. if usage_i < 0:
  8955. expl = t
  8956. output += expl + '\n\n'
  8957. continue
  8958. expl = t[:usage_i - 1]
  8959. output += expl + '\n\n'
  8960. end_usage_i = t[usage_i:].find('\n')
  8961. if end_usage_i < 0:
  8962. end_usage_i = len(t[usage_i:])
  8963. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  8964. else:
  8965. extras = t[usage_i+end_usage_i+1:]
  8966. parts = [s.strip() for s in extras.split('\n')]
  8967. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  8968. for p in parts:
  8969. output += ' ' + p + '\n\n'
  8970. return output
  8971. '''
  8972. Howto implement TCL shell commands:
  8973. All parameters passed to command should be possible to set as None and test it afterwards.
  8974. This is because we need to see error caused in tcl,
  8975. if None value as default parameter is not allowed TCL will return empty error.
  8976. Use:
  8977. def mycommand(name=None,...):
  8978. Test it like this:
  8979. if name is None:
  8980. self.raise_tcl_error('Argument name is missing.')
  8981. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  8982. otherwise we will miss it and processing will silently continue.
  8983. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  8984. which is catched in exec_command and displayed in TCL shell console with red background.
  8985. Error in console is displayed with TCL trace.
  8986. This behavior works only within main thread,
  8987. errors with promissed tasks can be catched and detected only with log.
  8988. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  8989. TCL shell.
  8990. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  8991. '''
  8992. commands = {
  8993. 'help': {
  8994. 'fcn': shelp,
  8995. 'help': _("Shows list of commands.")
  8996. },
  8997. }
  8998. # Import/overwrite tcl commands as objects of TclCommand descendants
  8999. # This modifies the variable 'commands'.
  9000. tclCommands.register_all_commands(self, commands)
  9001. # Add commands to the tcl interpreter
  9002. for cmd in commands:
  9003. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  9004. # Make the tcl puts function return instead of print to stdout
  9005. self.tcl.eval('''
  9006. rename puts original_puts
  9007. proc puts {args} {
  9008. if {[llength $args] == 1} {
  9009. return "[lindex $args 0]"
  9010. } else {
  9011. eval original_puts $args
  9012. }
  9013. }
  9014. ''')
  9015. def setup_recent_items(self):
  9016. # TODO: Move this to constructor
  9017. icons = {
  9018. "gerber": "share/flatcam_icon16.png",
  9019. "excellon": "share/drill16.png",
  9020. 'geometry': "share/geometry16.png",
  9021. "cncjob": "share/cnc16.png",
  9022. "project": "share/project16.png",
  9023. "svg": "share/geometry16.png",
  9024. "dxf": "share/dxf16.png",
  9025. "pdf": "share/pdf32.png",
  9026. "image": "share/image16.png"
  9027. }
  9028. openers = {
  9029. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  9030. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  9031. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  9032. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  9033. 'project': self.open_project,
  9034. 'svg': self.import_svg,
  9035. 'dxf': self.import_dxf,
  9036. 'image': self.import_image,
  9037. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  9038. }
  9039. # Open recent file for files
  9040. try:
  9041. f = open(self.data_path + '/recent.json')
  9042. except IOError:
  9043. App.log.error("Failed to load recent item list.")
  9044. self.inform.emit('[ERROR_NOTCL] %s' %
  9045. _("Failed to load recent item list."))
  9046. return
  9047. try:
  9048. self.recent = json.load(f)
  9049. except json.scanner.JSONDecodeError:
  9050. App.log.error("Failed to parse recent item list.")
  9051. self.inform.emit('[ERROR_NOTCL] %s' %
  9052. _("Failed to parse recent item list."))
  9053. f.close()
  9054. return
  9055. f.close()
  9056. # Open recent file for projects
  9057. try:
  9058. fp = open(self.data_path + '/recent_projects.json')
  9059. except IOError:
  9060. App.log.error("Failed to load recent project item list.")
  9061. self.inform.emit('[ERROR_NOTCL] %s' %
  9062. _("Failed to load recent projects item list."))
  9063. return
  9064. try:
  9065. self.recent_projects = json.load(fp)
  9066. except json.scanner.JSONDecodeError:
  9067. App.log.error("Failed to parse recent project item list.")
  9068. self.inform.emit('[ERROR_NOTCL] %s' %
  9069. _("Failed to parse recent project item list."))
  9070. fp.close()
  9071. return
  9072. fp.close()
  9073. # Closure needed to create callbacks in a loop.
  9074. # Otherwise late binding occurs.
  9075. def make_callback(func, fname):
  9076. def opener():
  9077. func(fname)
  9078. return opener
  9079. def reset_recent_files():
  9080. # Reset menu
  9081. self.ui.recent.clear()
  9082. self.recent = []
  9083. try:
  9084. f = open(self.data_path + '/recent.json', 'w')
  9085. except IOError:
  9086. App.log.error("Failed to open recent items file for writing.")
  9087. return
  9088. json.dump(self.recent, f)
  9089. def reset_recent_projects():
  9090. # Reset menu
  9091. self.ui.recent_projects.clear()
  9092. self.recent_projects = []
  9093. try:
  9094. fp = open(self.data_path + '/recent_projects.json', 'w')
  9095. except IOError:
  9096. App.log.error("Failed to open recent projects items file for writing.")
  9097. return
  9098. json.dump(self.recent, fp)
  9099. # Reset menu
  9100. self.ui.recent.clear()
  9101. self.ui.recent_projects.clear()
  9102. # Create menu items for projects
  9103. for recent in self.recent_projects:
  9104. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9105. if recent['kind'] == 'project':
  9106. try:
  9107. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9108. # Attach callback
  9109. o = make_callback(openers[recent["kind"]], recent['filename'])
  9110. action.triggered.connect(o)
  9111. self.ui.recent_projects.addAction(action)
  9112. except KeyError:
  9113. App.log.error("Unsupported file type: %s" % recent["kind"])
  9114. # Last action in Recent Files menu is one that Clear the content
  9115. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  9116. clear_action_proj.triggered.connect(reset_recent_projects)
  9117. self.ui.recent_projects.addSeparator()
  9118. self.ui.recent_projects.addAction(clear_action_proj)
  9119. # Create menu items for files
  9120. for recent in self.recent:
  9121. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9122. if recent['kind'] != 'project':
  9123. try:
  9124. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9125. # Attach callback
  9126. o = make_callback(openers[recent["kind"]], recent['filename'])
  9127. action.triggered.connect(o)
  9128. self.ui.recent.addAction(action)
  9129. except KeyError:
  9130. App.log.error("Unsupported file type: %s" % recent["kind"])
  9131. # Last action in Recent Files menu is one that Clear the content
  9132. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  9133. clear_action.triggered.connect(reset_recent_files)
  9134. self.ui.recent.addSeparator()
  9135. self.ui.recent.addAction(clear_action)
  9136. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  9137. # self.ui.menufilerecent.set_submenu(recent_menu)
  9138. # recent_menu.show_all()
  9139. # self.ui.recent.show()
  9140. self.log.debug("Recent items list has been populated.")
  9141. def setup_component_editor(self):
  9142. # label = QtWidgets.QLabel("Choose an item from Project")
  9143. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  9144. sel_title = QtWidgets.QTextEdit(
  9145. _('<b>Shortcut Key List</b>'))
  9146. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  9147. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  9148. settings = QSettings("Open Source", "FlatCAM")
  9149. if settings.contains("notebook_font_size"):
  9150. fsize = settings.value('notebook_font_size', type=int)
  9151. else:
  9152. fsize = 12
  9153. tsize = fsize + int(fsize / 2)
  9154. # selected_text = (_('''
  9155. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  9156. #
  9157. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  9158. # The normal flow when working in FlatCAM is the following:</span></p>
  9159. #
  9160. # <ol>
  9161. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  9162. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  9163. # even dragging and dropping the files on the GUI.<br />
  9164. # <br />
  9165. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  9166. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  9167. # &nbsp;</li>
  9168. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  9169. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  9170. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  9171. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  9172. # <br />
  9173. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  9174. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  9175. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  9176. # it even if it was out of focus.<br />
  9177. # <br />
  9178. # You can change the parameters in this screen and the flow direction is like this:<br />
  9179. # <br />
  9180. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  9181. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  9182. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  9183. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  9184. # </ol>
  9185. #
  9186. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  9187. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  9188. # <strong>F3</strong>.</span></p>
  9189. #
  9190. # ''').format(fsize=fsize, tsize=tsize))
  9191. selected_text = '''
  9192. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  9193. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  9194. {s1}</span></p>
  9195. <ol>
  9196. <li><span style="font-size:{fsize}px">{s2}<br />
  9197. <br />
  9198. {s3}</span><br />
  9199. &nbsp;</li>
  9200. <li><span style="font-size:{fsize}px">{s4}<br />
  9201. &nbsp;</li>
  9202. <br />
  9203. <li><span style="font-size:{fsize}px">{s5}<br />
  9204. &nbsp;</li>
  9205. <br />
  9206. <li><span style="font-size:{fsize}px">{s6}<br />
  9207. <br />
  9208. {s7}</span></li>
  9209. </ol>
  9210. <p><span style="font-size:{fsize}px">{s8}</span></p>
  9211. '''.format(
  9212. title=_("Selected Tab - Choose an Item from Project Tab"),
  9213. subtitle=_("Details"),
  9214. s1=_("The normal flow when working in FlatCAM is the following:"),
  9215. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  9216. "using either the toolbars, key shortcuts or even dragging and dropping the "
  9217. "files on the GUI."),
  9218. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  9219. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  9220. "actions offered within the app."),
  9221. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  9222. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  9223. "SELECTED TAB will be updated with the object properties according to its kind: "
  9224. "Gerber, Excellon, Geometry or CNCJob object."),
  9225. s5=_("If the selection of the object is done on the canvas by single click instead, "
  9226. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  9227. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  9228. "the SELECTED TAB and populate it even if it was out of focus."),
  9229. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  9230. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  9231. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  9232. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  9233. "(again, done in SELECTED TAB) --> Save GCode."),
  9234. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  9235. "or through its own key shortcut: <b>F3</b>."),
  9236. tsize=tsize,
  9237. fsize=fsize
  9238. )
  9239. sel_title.setText(selected_text)
  9240. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  9241. self.ui.selected_scroll_area.setWidget(sel_title)
  9242. def setup_obj_classes(self):
  9243. """
  9244. Sets up application specifics on the FlatCAMObj class.
  9245. :return: None
  9246. """
  9247. FlatCAMObj.app = self
  9248. ObjectCollection.app = self
  9249. Gerber.app = self
  9250. Excellon.app = self
  9251. Geometry.app = self
  9252. CNCjob.app = self
  9253. FCProcess.app = self
  9254. FCProcessContainer.app = self
  9255. def version_check(self):
  9256. """
  9257. Checks for the latest version of the program. Alerts the
  9258. user if theirs is outdated. This method is meant to be run
  9259. in a separate thread.
  9260. :return: None
  9261. """
  9262. self.log.debug("version_check()")
  9263. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  9264. full_url = App.version_url + \
  9265. "?s=" + str(self.defaults['global_serial']) + \
  9266. "&v=" + str(self.version) + \
  9267. "&os=" + str(self.os) + \
  9268. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  9269. else:
  9270. # no_stats dict; just so it won't break things on website
  9271. no_ststs_dict = {}
  9272. no_ststs_dict["global_ststs"] = {}
  9273. full_url = App.version_url + \
  9274. "?s=" + str(self.defaults['global_serial']) + \
  9275. "&v=" + str(self.version) + \
  9276. "&os=" + str(self.os) + \
  9277. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  9278. App.log.debug("Checking for updates @ %s" % full_url)
  9279. # ## Get the data
  9280. try:
  9281. f = urllib.request.urlopen(full_url)
  9282. except:
  9283. # App.log.warning("Failed checking for latest version. Could not connect.")
  9284. self.log.warning("Failed checking for latest version. Could not connect.")
  9285. self.inform.emit('[WARNING_NOTCL] %s' %
  9286. _("Failed checking for latest version. Could not connect."))
  9287. return
  9288. try:
  9289. data = json.load(f)
  9290. except Exception as e:
  9291. App.log.error("Could not parse information about latest version.")
  9292. self.inform.emit('[ERROR_NOTCL] %s' %
  9293. _("Could not parse information about latest version."))
  9294. App.log.debug("json.load(): %s" % str(e))
  9295. f.close()
  9296. return
  9297. f.close()
  9298. # ## Latest version?
  9299. if self.version >= data["version"]:
  9300. App.log.debug("FlatCAM is up to date!")
  9301. self.inform.emit('[success] %s' %
  9302. _("FlatCAM is up to date!"))
  9303. return
  9304. App.log.debug("Newer version available.")
  9305. self.message.emit(
  9306. _("Newer Version Available"),
  9307. _("There is a newer version of FlatCAM available for download:\n\n") +
  9308. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  9309. _("info")
  9310. )
  9311. def on_plotcanvas_setup(self, container=None):
  9312. """
  9313. This is doing the setup for the plot area (VisPy canvas)
  9314. :param container: widget where to install the canvas
  9315. :return: None
  9316. """
  9317. if container:
  9318. plot_container = container
  9319. else:
  9320. plot_container = self.ui.right_layout
  9321. if self.is_legacy is False:
  9322. self.plotcanvas = PlotCanvas(plot_container, self)
  9323. else:
  9324. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  9325. # So it can receive key presses
  9326. self.plotcanvas.native.setFocus()
  9327. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  9328. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  9329. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  9330. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_double_click_over_plot)
  9331. # Keys over plot enabled
  9332. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  9333. self.app_cursor = self.plotcanvas.new_cursor()
  9334. if self.ui.grid_snap_btn.isChecked():
  9335. self.app_cursor.enabled = True
  9336. else:
  9337. self.app_cursor.enabled = False
  9338. if self.is_legacy is False:
  9339. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  9340. else:
  9341. # will use the default Matplotlib axes
  9342. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  9343. def on_zoom_fit(self, event):
  9344. """
  9345. Callback for zoom-out request. This can be either from the corresponding
  9346. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  9347. with axes limits from the geometry bounds of all objects.
  9348. :param event: Ignored.
  9349. :return: None
  9350. """
  9351. if self.is_legacy is False:
  9352. self.plotcanvas.fit_view()
  9353. else:
  9354. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  9355. width = xmax - xmin
  9356. height = ymax - ymin
  9357. xmin -= 0.05 * width
  9358. xmax += 0.05 * width
  9359. ymin -= 0.05 * height
  9360. ymax += 0.05 * height
  9361. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  9362. def on_zoom_in(self):
  9363. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  9364. def on_zoom_out(self):
  9365. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  9366. def disable_all_plots(self):
  9367. self.report_usage("disable_all_plots()")
  9368. self.disable_plots(self.collection.get_list())
  9369. self.inform.emit('[success] %s' %
  9370. _("All plots disabled."))
  9371. def disable_other_plots(self):
  9372. self.report_usage("disable_other_plots()")
  9373. self.disable_plots(self.collection.get_non_selected())
  9374. self.inform.emit('[success] %s' %
  9375. _("All non selected plots disabled."))
  9376. def enable_all_plots(self):
  9377. self.report_usage("enable_all_plots()")
  9378. self.enable_plots(self.collection.get_list())
  9379. self.inform.emit('[success] %s' %
  9380. _("All plots enabled."))
  9381. def on_enable_sel_plots(self):
  9382. log.debug("App.on_enable_sel_plot()")
  9383. object_list = self.collection.get_selected()
  9384. self.enable_plots(objects=object_list)
  9385. self.inform.emit('[success] %s' %
  9386. _("Selected plots enabled..."))
  9387. def on_disable_sel_plots(self):
  9388. log.debug("App.on_disable_sel_plot()")
  9389. # self.inform.emit(_("Disabling plots ..."))
  9390. object_list = self.collection.get_selected()
  9391. self.disable_plots(objects=object_list)
  9392. self.inform.emit('[success] %s' %
  9393. _("Selected plots disabled..."))
  9394. def enable_plots(self, objects):
  9395. """
  9396. Disables plots
  9397. :param objects: list of Objects to be enabled
  9398. :return:
  9399. """
  9400. log.debug("Enabling plots ...")
  9401. # self.inform.emit(_("Working ..."))
  9402. for obj in objects:
  9403. if obj.options['plot'] is False:
  9404. obj.options.set_change_callback(lambda x: None)
  9405. obj.options['plot'] = True
  9406. obj.options.set_change_callback(obj.on_options_change)
  9407. def worker_task(objects):
  9408. with self.proc_container.new(_("Enabling plots ...")):
  9409. for obj in objects:
  9410. # obj.options['plot'] = True
  9411. if isinstance(obj, FlatCAMCNCjob):
  9412. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  9413. else:
  9414. obj.plot(visible=True)
  9415. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9416. # self.plots_updated.emit()
  9417. def disable_plots(self, objects):
  9418. """
  9419. Disables plots
  9420. :param objects: list of Objects to be disabled
  9421. :return:
  9422. """
  9423. # if no objects selected then do nothing
  9424. if not self.collection.get_selected():
  9425. return
  9426. log.debug("Disabling plots ...")
  9427. # self.inform.emit(_("Working ..."))
  9428. for obj in objects:
  9429. if obj.options['plot'] is True:
  9430. obj.options.set_change_callback(lambda x: None)
  9431. obj.options['plot'] = False
  9432. obj.options.set_change_callback(obj.on_options_change)
  9433. try:
  9434. self.delete_selection_shape()
  9435. except Exception as e:
  9436. log.debug("App.disable_plots() --> %s" % str(e))
  9437. # self.plots_updated.emit()
  9438. def worker_task(objects):
  9439. with self.proc_container.new(_("Disabling plots ...")):
  9440. for obj in objects:
  9441. # obj.options['plot'] = True
  9442. if isinstance(obj, FlatCAMCNCjob):
  9443. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  9444. else:
  9445. obj.plot(visible=False)
  9446. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9447. def toggle_plots(self, objects):
  9448. """
  9449. Toggle plots visibility
  9450. :param objects: list of Objects for which to be toggled the visibility
  9451. :return:
  9452. """
  9453. # if no objects selected then do nothing
  9454. if not self.collection.get_selected():
  9455. return
  9456. log.debug("Toggling plots ...")
  9457. self.inform.emit(_("Working ..."))
  9458. for obj in objects:
  9459. if obj.options['plot'] is False:
  9460. obj.options['plot'] = True
  9461. else:
  9462. obj.options['plot'] = False
  9463. self.plots_updated.emit()
  9464. def clear_plots(self):
  9465. objects = self.collection.get_list()
  9466. for obj in objects:
  9467. obj.clear(obj == objects[-1])
  9468. # Clear pool to free memory
  9469. self.clear_pool()
  9470. def generate_cnc_job(self, objects):
  9471. self.report_usage("generate_cnc_job()")
  9472. # for obj in objects:
  9473. # obj.generatecncjob()
  9474. for obj in objects:
  9475. obj.on_generatecnc_button_click()
  9476. def save_project(self, filename, quit_action=False, silent=False):
  9477. """
  9478. Saves the current project to the specified file.
  9479. :param filename: Name of the file in which to save.
  9480. :type filename: str
  9481. :param quit_action: if the project saving will be followed by an app quit; boolean
  9482. :param silent: if True will not display status messages
  9483. :return: None
  9484. """
  9485. self.log.debug("save_project()")
  9486. self.save_in_progress = True
  9487. with self.proc_container.new(_("Saving FlatCAM Project")):
  9488. # Capture the latest changes
  9489. # Current object
  9490. try:
  9491. self.collection.get_active().read_form()
  9492. except:
  9493. self.log.debug("There was no active object")
  9494. pass
  9495. # Project options
  9496. self.options_read_form()
  9497. # Serialize the whole project
  9498. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  9499. "options": self.options,
  9500. "version": self.version}
  9501. if self.defaults["global_save_compressed"] is True:
  9502. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  9503. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  9504. # # Write
  9505. f.write(g)
  9506. self.inform.emit('[success] %s: %s' %
  9507. (_("Project saved to"), filename))
  9508. else:
  9509. # Open file
  9510. try:
  9511. f = open(filename, 'w')
  9512. except IOError:
  9513. App.log.error("Failed to open file for saving: %s", filename)
  9514. return
  9515. # Write
  9516. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  9517. f.close()
  9518. # verification of the saved project
  9519. # Open and parse
  9520. try:
  9521. saved_f = open(filename, 'r')
  9522. except IOError:
  9523. if silent is False:
  9524. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9525. (_("Failed to verify project file"), filename, _("Retry to save it."))
  9526. )
  9527. return
  9528. try:
  9529. saved_d = json.load(saved_f, object_hook=dict2obj)
  9530. except:
  9531. if silent is False:
  9532. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9533. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9534. )
  9535. f.close()
  9536. return
  9537. saved_f.close()
  9538. if silent is False:
  9539. if 'version' in saved_d:
  9540. self.inform.emit('[success] %s: %s' %
  9541. (_("Project saved to"), filename))
  9542. else:
  9543. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9544. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9545. )
  9546. settings = QSettings("Open Source", "FlatCAM")
  9547. lock_state = self.ui.lock_action.isChecked()
  9548. settings.setValue('toolbar_lock', lock_state)
  9549. # This will write the setting to the platform specific storage.
  9550. del settings
  9551. # if quit:
  9552. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  9553. # t.start()
  9554. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  9555. def start_delayed_quit(self, delay, filename, should_quit=None):
  9556. """
  9557. :param delay: period of checking if project file size is more than zero; in seconds
  9558. :param filename: the name of the project file to be checked periodically for size more than zero
  9559. :param should_quit: if the task finished will be followed by an app quit; boolean
  9560. :return:
  9561. """
  9562. to_quit = should_quit
  9563. self.save_timer = QtCore.QTimer()
  9564. self.save_timer.setInterval(delay)
  9565. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  9566. self.save_timer.start()
  9567. def check_project_file_size(self, filename, should_quit=None):
  9568. """
  9569. :param filename: the name of the project file to be checked periodically for size more than zero
  9570. :param should_quit: will quit the app if True; boolean
  9571. :return:
  9572. """
  9573. try:
  9574. if os.stat(filename).st_size > 0:
  9575. self.save_in_progress = False
  9576. self.save_timer.stop()
  9577. if should_quit:
  9578. self.app_quit.emit()
  9579. except Exception as e:
  9580. traceback.print_exc()
  9581. def on_options_app2project(self):
  9582. """
  9583. Callback for Options->Transfer Options->App=>Project. Copies options
  9584. from application defaults to project defaults.
  9585. :return: None
  9586. """
  9587. self.report_usage("on_options_app2project")
  9588. self.defaults_read_form()
  9589. self.options.update(self.defaults)
  9590. self.options_write_form()
  9591. def on_options_project2app(self):
  9592. """
  9593. Callback for Options->Transfer Options->Project=>App. Copies options
  9594. from project defaults to application defaults.
  9595. :return: None
  9596. """
  9597. self.report_usage("on_options_project2app")
  9598. self.options_read_form()
  9599. self.defaults.update(self.options)
  9600. self.defaults_write_form()
  9601. def on_options_project2object(self):
  9602. """
  9603. Callback for Options->Transfer Options->Project=>Object. Copies options
  9604. from project defaults to the currently selected object.
  9605. :return: None
  9606. """
  9607. self.report_usage("on_options_project2object")
  9608. self.options_read_form()
  9609. obj = self.collection.get_active()
  9610. if obj is None:
  9611. self.inform.emit('[WARNING_NOTCL] %s' %
  9612. _("No object selected."))
  9613. return
  9614. for option in self.options:
  9615. if option.find(obj.kind + "_") == 0:
  9616. oname = option[len(obj.kind) + 1:]
  9617. obj.options[oname] = self.options[option]
  9618. obj.to_form() # Update UI
  9619. def on_options_object2project(self):
  9620. """
  9621. Callback for Options->Transfer Options->Object=>Project. Copies options
  9622. from the currently selected object to project defaults.
  9623. :return: None
  9624. """
  9625. self.report_usage("on_options_object2project")
  9626. obj = self.collection.get_active()
  9627. if obj is None:
  9628. self.inform.emit('[WARNING_NOTCL] %s' %
  9629. _("No object selected."))
  9630. return
  9631. obj.read_form()
  9632. for option in obj.options:
  9633. if option in ['name']: # TODO: Handle this better...
  9634. continue
  9635. self.options[obj.kind + "_" + option] = obj.options[option]
  9636. self.options_write_form()
  9637. def on_options_object2app(self):
  9638. """
  9639. Callback for Options->Transfer Options->Object=>App. Copies options
  9640. from the currently selected object to application defaults.
  9641. :return: None
  9642. """
  9643. self.report_usage("on_options_object2app")
  9644. obj = self.collection.get_active()
  9645. if obj is None:
  9646. self.inform.emit('[WARNING_NOTCL] %s' %
  9647. _("No object selected."))
  9648. return
  9649. obj.read_form()
  9650. for option in obj.options:
  9651. if option in ['name']: # TODO: Handle this better...
  9652. continue
  9653. self.defaults[obj.kind + "_" + option] = obj.options[option]
  9654. self.defaults_write_form()
  9655. def on_options_app2object(self):
  9656. """
  9657. Callback for Options->Transfer Options->App=>Object. Copies options
  9658. from application defaults to the currently selected object.
  9659. :return: None
  9660. """
  9661. self.report_usage("on_options_app2object")
  9662. self.defaults_read_form()
  9663. obj = self.collection.get_active()
  9664. if obj is None:
  9665. self.inform.emit('[WARNING_NOTCL] %s' %
  9666. _("No object selected."))
  9667. return
  9668. for option in self.defaults:
  9669. if option.find(obj.kind + "_") == 0:
  9670. oname = option[len(obj.kind) + 1:]
  9671. obj.options[oname] = self.defaults[option]
  9672. obj.to_form() # Update UI
  9673. class ArgsThread(QtCore.QObject):
  9674. open_signal = pyqtSignal(list)
  9675. start = pyqtSignal()
  9676. if sys.platform == 'win32':
  9677. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  9678. else:
  9679. address = ('/tmp/testipc', 'AF_UNIX')
  9680. def __init__(self):
  9681. super(ArgsThread, self).__init__()
  9682. self.start.connect(self.run)
  9683. def my_loop(self, address):
  9684. try:
  9685. listener = Listener(*address)
  9686. while True:
  9687. conn = listener.accept()
  9688. self.serve(conn)
  9689. except socket.error as e:
  9690. conn = Client(*address)
  9691. conn.send(sys.argv)
  9692. conn.send('close')
  9693. # close the current instance only if there are args
  9694. if len(sys.argv) > 1:
  9695. sys.exit()
  9696. def serve(self, conn):
  9697. while True:
  9698. msg = conn.recv()
  9699. if msg == 'close':
  9700. break
  9701. self.open_signal.emit(msg)
  9702. conn.close()
  9703. # the decorator is a must; without it this technique will not work unless the start signal is connected
  9704. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  9705. @pyqtSlot()
  9706. def run(self):
  9707. self.my_loop(self.address)
  9708. class GracefulException(Exception):
  9709. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  9710. def __init__(self):
  9711. super().__init__()
  9712. def __str__(self):
  9713. return ('\n\n%s' % _("The user requested a graceful exit of the current task."))
  9714. # end of file