FlatCAMApp.py 561 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457
  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 webbrowser
  12. import getopt
  13. import random
  14. import simplejson as json
  15. import lzma
  16. import threading
  17. import shutil
  18. from stat import S_IREAD, S_IRGRP, S_IROTH
  19. import subprocess
  20. import ctypes
  21. import tkinter as tk
  22. from PyQt5 import QtPrintSupport
  23. from contextlib import contextmanager
  24. import gc
  25. from xml.dom.minidom import parseString as parse_xml_string
  26. from multiprocessing.connection import Listener, Client
  27. from multiprocessing import Pool, cpu_count
  28. import socket
  29. from array import array
  30. import vispy.scene as scene
  31. # #######################################
  32. # # Imports part of FlatCAM ##
  33. # #######################################
  34. from ObjectCollection import *
  35. from FlatCAMObj import *
  36. from camlib import to_dict, dict2obj, ET, ParseError
  37. from flatcamGUI.PlotCanvas import *
  38. from flatcamGUI.PlotCanvasLegacy import *
  39. from flatcamGUI.FlatCAMGUI import *
  40. from FlatCAMCommon import LoudDict
  41. from FlatCAMPostProc import load_postprocessors
  42. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  43. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  44. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  45. from flatcamEditors.FlatCAMTextEditor import TextEditor
  46. from FlatCAMProcess import *
  47. from FlatCAMWorkerStack import WorkerStack
  48. # from flatcamGUI.VisPyVisuals import Color
  49. from vispy.gloo.util import _screenshot
  50. from vispy.io import write_png
  51. from flatcamTools import *
  52. import tclCommands
  53. import gettext
  54. import FlatCAMTranslation as fcTranslate
  55. import builtins
  56. if sys.platform == 'win32':
  57. import winreg
  58. fcTranslate.apply_language('strings')
  59. if '_' not in builtins.__dict__:
  60. _ = gettext.gettext
  61. class App(QtCore.QObject):
  62. # ########################################
  63. # # App ###
  64. # ########################################
  65. """
  66. The main application class. The constructor starts the GUI.
  67. """
  68. # Get Cmd Line Options
  69. cmd_line_shellfile = ''
  70. cmd_line_shellvar = ''
  71. cmd_line_headless = None
  72. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  73. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  74. "FlatCam.py --headless=1"
  75. try:
  76. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  77. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  78. "shellvar=",
  79. "headless=",
  80. "multiprocessing-fork="])
  81. except getopt.GetoptError:
  82. print(cmd_line_help)
  83. sys.exit(2)
  84. for opt, arg in cmd_line_options:
  85. if opt == '-h':
  86. print(cmd_line_help)
  87. sys.exit()
  88. elif opt == '--shellfile':
  89. cmd_line_shellfile = arg
  90. elif opt == '--shellvar':
  91. cmd_line_shellvar = arg
  92. elif opt == '--headless':
  93. try:
  94. cmd_line_headless = eval(arg)
  95. except NameError:
  96. pass
  97. # ## Logging ###
  98. log = logging.getLogger('base')
  99. log.setLevel(logging.DEBUG)
  100. # log.setLevel(logging.WARNING)
  101. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  102. handler = logging.StreamHandler()
  103. handler.setFormatter(formatter)
  104. log.addHandler(handler)
  105. # ##########################################################################
  106. # ################## Version and VERSION DATE ##############################
  107. # ##########################################################################
  108. version = 8.99
  109. version_date = "2019/10/30"
  110. beta = True
  111. engine = '3D'
  112. # current date now
  113. date = str(datetime.today()).rpartition('.')[0]
  114. date = ''.join(c for c in date if c not in ':-')
  115. date = date.replace(' ', '_')
  116. # URL for update checks and statistics
  117. version_url = "http://flatcam.org/version"
  118. # App URL
  119. app_url = "http://flatcam.org"
  120. # Manual URL
  121. manual_url = "http://flatcam.org/manual/index.html"
  122. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  123. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  124. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  125. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  126. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  127. # this variable will hold the project status
  128. # if True it will mean that the project was modified and not saved
  129. should_we_save = False
  130. # flag is True if saving action has been triggered
  131. save_in_progress = False
  132. # ###########################################################################
  133. # ############################# Signals ################################
  134. # ###########################################################################
  135. # Inform the user
  136. # Handled by:
  137. # * App.info() --> Print on the status bar
  138. inform = QtCore.pyqtSignal(str)
  139. app_quit = QtCore.pyqtSignal()
  140. # General purpose background task
  141. worker_task = QtCore.pyqtSignal(dict)
  142. # File opened
  143. # Handled by:
  144. # * register_folder()
  145. # * register_recent()
  146. # Note: Setting the parameters to unicode does not seem
  147. # to have an effect. Then are received as Qstring
  148. # anyway.
  149. # File type and filename
  150. file_opened = QtCore.pyqtSignal(str, str)
  151. # File type and filename
  152. file_saved = QtCore.pyqtSignal(str, str)
  153. # Percentage of progress
  154. progress = QtCore.pyqtSignal(int)
  155. plots_updated = QtCore.pyqtSignal()
  156. # Emitted by new_object() and passes the new object as argument, plot flag.
  157. # on_object_created() adds the object to the collection, plots on appropriate flag
  158. # and emits new_object_available.
  159. object_created = QtCore.pyqtSignal(object, bool, bool)
  160. # Emitted when a object has been changed (like scaled, mirrored)
  161. object_changed = QtCore.pyqtSignal(object)
  162. # Emitted after object has been plotted.
  163. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  164. object_plotted = QtCore.pyqtSignal(object)
  165. # Emitted when a new object has been added or deleted from/to the collection
  166. object_status_changed = QtCore.pyqtSignal(object, str, str)
  167. message = QtCore.pyqtSignal(str, str, str)
  168. # Emmited when shell command is finished(one command only)
  169. shell_command_finished = QtCore.pyqtSignal(object)
  170. # Emitted when multiprocess pool has been recreated
  171. pool_recreated = QtCore.pyqtSignal(object)
  172. # Emitted when an unhandled exception happens
  173. # in the worker task.
  174. thread_exception = QtCore.pyqtSignal(object)
  175. # used to signal that there are arguments for the app
  176. args_at_startup = QtCore.pyqtSignal(list)
  177. # a reusable signal to replot a list of objects
  178. # should be disconnected after use so it can be reused
  179. replot_signal = pyqtSignal(list)
  180. def __init__(self, user_defaults=True, post_gui=None):
  181. """
  182. Starts the application.
  183. :return: app
  184. :rtype: App
  185. """
  186. App.log.info("FlatCAM Starting...")
  187. self.main_thread = QtWidgets.QApplication.instance().thread()
  188. # ############################################################################
  189. # # ################# OS-specific ############################################
  190. # ############################################################################
  191. portable = False
  192. # Folder for user settings.
  193. if sys.platform == 'win32':
  194. # #########################################################################
  195. # Setup the listening thread for another instance launching with args #####
  196. # #########################################################################
  197. # make sure the thread is stored by using a self. otherwise it's garbage collected
  198. self.th = QtCore.QThread()
  199. self.th.start(priority=QtCore.QThread.LowestPriority)
  200. self.new_launch = ArgsThread()
  201. self.new_launch.open_signal[list].connect(self.on_startup_args)
  202. self.new_launch.moveToThread(self.th)
  203. self.new_launch.start.emit()
  204. from win32com.shell import shell, shellcon
  205. if platform.architecture()[0] == '32bit':
  206. App.log.debug("Win32!")
  207. else:
  208. App.log.debug("Win64!")
  209. # #########################################################################
  210. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  211. # #########################################################################
  212. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  213. try:
  214. with open(config_file, 'r'):
  215. pass
  216. except FileNotFoundError:
  217. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  218. try:
  219. with open(config_file, 'r') as f:
  220. try:
  221. for line in f:
  222. param = str(line).replace('\n', '').rpartition('=')
  223. if param[0] == 'portable':
  224. try:
  225. portable = eval(param[2])
  226. except NameError:
  227. portable = False
  228. if param[0] == 'headless':
  229. if param[2].lower() == 'true':
  230. self.cmd_line_headless = 1
  231. else:
  232. self.cmd_line_headless = None
  233. except Exception as e:
  234. log.debug('App.__init__() -->%s' % str(e))
  235. return
  236. except FileNotFoundError as e:
  237. log.debug(str(e))
  238. pass
  239. if portable is False:
  240. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  241. else:
  242. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  243. self.os = 'windows'
  244. else: # Linux/Unix/MacOS
  245. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  246. self.os = 'unix'
  247. # ##########################################################################
  248. # ################## Setup folders and files ###############################
  249. # ##########################################################################
  250. if not os.path.exists(self.data_path):
  251. os.makedirs(self.data_path)
  252. App.log.debug('Created data folder: ' + self.data_path)
  253. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  254. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  255. self.postprocessorpaths = os.path.join(self.data_path, 'postprocessors')
  256. if not os.path.exists(self.postprocessorpaths):
  257. os.makedirs(self.postprocessorpaths)
  258. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  259. # create current_defaults.FlatConfig file if there is none
  260. try:
  261. f = open(self.data_path + '/current_defaults.FlatConfig')
  262. f.close()
  263. except IOError:
  264. App.log.debug('Creating empty current_defaults.FlatConfig')
  265. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  266. json.dump({}, f)
  267. f.close()
  268. # create factory_defaults.FlatConfig file if there is none
  269. try:
  270. f = open(self.data_path + '/factory_defaults.FlatConfig')
  271. f.close()
  272. except IOError:
  273. App.log.debug('Creating empty factory_defaults.FlatConfig')
  274. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  275. json.dump({}, f)
  276. f.close()
  277. # create a recent files json file if there is none
  278. try:
  279. f = open(self.data_path + '/recent.json')
  280. f.close()
  281. except IOError:
  282. App.log.debug('Creating empty recent.json')
  283. f = open(self.data_path + '/recent.json', 'w')
  284. json.dump([], f)
  285. f.close()
  286. # create a recent projects json file if there is none
  287. try:
  288. fp = open(self.data_path + '/recent_projects.json')
  289. fp.close()
  290. except IOError:
  291. App.log.debug('Creating empty recent_projects.json')
  292. fp = open(self.data_path + '/recent_projects.json', 'w')
  293. json.dump([], fp)
  294. fp.close()
  295. # Application directory. CHDIR to it. Otherwise, trying to load
  296. # GUI icons will fail as their path is relative.
  297. # This will fail under cx_freeze ...
  298. self.app_home = os.path.dirname(os.path.realpath(__file__))
  299. App.log.debug("Application path is " + self.app_home)
  300. App.log.debug("Started in " + os.getcwd())
  301. # cx_freeze workaround
  302. if os.path.isfile(self.app_home):
  303. self.app_home = os.path.dirname(self.app_home)
  304. os.chdir(self.app_home)
  305. # #############################################################################
  306. # ##################### CREATE MULTIPROCESSING POOL ###########################
  307. # #############################################################################
  308. self.pool = Pool(processes=cpu_count())
  309. # ##########################################################################
  310. # ################## Setting the Splash Screen #############################
  311. # ##########################################################################
  312. settings = QSettings("Open Source", "FlatCAM")
  313. if settings.contains("splash_screen"):
  314. show_splash = settings.value("splash_screen")
  315. else:
  316. settings.setValue('splash_screen', 1)
  317. # This will write the setting to the platform specific storage.
  318. del settings
  319. show_splash = 1
  320. if show_splash and self.cmd_line_headless != 1:
  321. splash_pix = QtGui.QPixmap('share/splash.png')
  322. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  323. # self.splash.setMask(splash_pix.mask())
  324. # move splashscreen to the current monitor
  325. desktop = QtWidgets.QApplication.desktop()
  326. screen = desktop.screenNumber(QtGui.QCursor.pos())
  327. current_screen_center = desktop.availableGeometry(screen).center()
  328. self.splash.move(current_screen_center - self.splash.rect().center())
  329. self.splash.show()
  330. self.splash.showMessage(_("FlatCAM is initializing ..."),
  331. alignment=Qt.AlignBottom | Qt.AlignLeft,
  332. color=QtGui.QColor("gray"))
  333. else:
  334. show_splash = 0
  335. # #############################################################################
  336. # ##################### Initialize GUI ########################################
  337. # #############################################################################
  338. # FlatCAM colors used in plotting
  339. self.FC_light_green = '#BBF268BF'
  340. self.FC_dark_green = '#006E20BF'
  341. self.FC_light_blue = '#a5a5ffbf'
  342. self.FC_dark_blue = '#0000ffbf'
  343. QtCore.QObject.__init__(self)
  344. self.ui = FlatCAMGUI(self.version, self.beta, self)
  345. settings = QtCore.QSettings("Open Source", "FlatCAM")
  346. if settings.contains("theme"):
  347. theme = settings.value('theme', type=str)
  348. else:
  349. theme = 'white'
  350. if theme == 'white':
  351. self.cursor_color_3D = 'black'
  352. else:
  353. self.cursor_color_3D = 'gray'
  354. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  355. self.ui.final_save.connect(self.final_save)
  356. # #############################################################################
  357. # ############################## Data #########################################
  358. # #############################################################################
  359. self.recent = []
  360. self.recent_projects = []
  361. self.clipboard = QtWidgets.QApplication.clipboard()
  362. self.project_filename = None
  363. self.toggle_units_ignore = False
  364. # self.defaults_form = PreferencesUI()
  365. # when adding entries here read the comments in the method found bellow named:
  366. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  367. self.defaults_form_fields = {
  368. # General App
  369. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  370. "global_graphic_engine": self.ui.general_defaults_form.general_app_group.ge_radio,
  371. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  372. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  373. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  374. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  375. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  376. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  377. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  378. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  379. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  380. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  381. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_spinner,
  382. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  383. "global_bookmarks_limit": self.ui.general_defaults_form.general_app_group.bm_limit_spinner,
  384. # General GUI Preferences
  385. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  386. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  387. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  388. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  389. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  390. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  391. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  392. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  393. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  394. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  395. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  396. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  397. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  398. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  399. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  400. "global_activity_icon": self.ui.general_defaults_form.general_gui_group.activity_combo,
  401. # General GUI Settings
  402. "global_theme": self.ui.general_defaults_form.general_gui_set_group.theme_radio,
  403. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  404. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  405. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  406. "global_systray_icon": self.ui.general_defaults_form.general_gui_set_group.systray_cb,
  407. "global_shell_at_startup": self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb,
  408. "global_project_at_startup": self.ui.general_defaults_form.general_gui_set_group.project_startup_cb,
  409. "global_project_autohide": self.ui.general_defaults_form.general_gui_set_group.project_autohide_cb,
  410. "global_toggle_tooltips": self.ui.general_defaults_form.general_gui_set_group.toggle_tooltips_cb,
  411. "global_delete_confirmation": self.ui.general_defaults_form.general_gui_set_group.delete_conf_cb,
  412. "global_cursor_type": self.ui.general_defaults_form.general_gui_set_group.cursor_radio,
  413. "global_cursor_size": self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry,
  414. # Gerber General
  415. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  416. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  417. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  418. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  419. "gerber_def_units": self.ui.gerber_defaults_form.gerber_gen_group.gerber_units_radio,
  420. "gerber_def_zeros": self.ui.gerber_defaults_form.gerber_gen_group.gerber_zeros_radio,
  421. # Gerber Options
  422. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  423. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  424. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  425. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  426. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  427. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  428. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  429. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  430. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  431. # Gerber Advanced Options
  432. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  433. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  434. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  435. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  436. "gerber_tool_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.tool_type_radio,
  437. "gerber_vtipdia": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipdia_spinner,
  438. "gerber_vtipangle": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipangle_spinner,
  439. "gerber_vcutz": self.ui.gerber_defaults_form.gerber_adv_opt_group.cutz_spinner,
  440. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  441. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  442. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  443. # Gerber Export
  444. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  445. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  446. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  447. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  448. # Gerber Editor
  449. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  450. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  451. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  452. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  453. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  454. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  455. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  456. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  457. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  458. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  459. "gerber_editor_circ_angle":
  460. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  461. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  462. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  463. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  464. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  465. # Excellon General
  466. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  467. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  468. "excellon_format_upper_in":
  469. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  470. "excellon_format_lower_in":
  471. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  472. "excellon_format_upper_mm":
  473. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  474. "excellon_format_lower_mm":
  475. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  476. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  477. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  478. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  479. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  480. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  481. # Excellon Options
  482. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  483. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  484. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.eendz_entry,
  485. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  486. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  487. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  488. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  489. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  490. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  491. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  492. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  493. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  494. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  495. # Excellon Advanced Options
  496. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  497. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  498. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  499. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  500. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  501. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  502. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  503. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  504. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  505. # Excellon Export
  506. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  507. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  508. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  509. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  510. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  511. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  512. # Excellon Editor
  513. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  514. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  515. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  516. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  517. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  518. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  519. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  520. "excellon_editor_circ_angle":
  521. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  522. # Excellon Slots
  523. "excellon_editor_slot_direction":
  524. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  525. "excellon_editor_slot_angle":
  526. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  527. "excellon_editor_slot_length":
  528. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  529. # Excellon Slots
  530. "excellon_editor_slot_array_size":
  531. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  532. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  533. "excellon_editor_slot_lin_pitch":
  534. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  535. "excellon_editor_slot_lin_angle":
  536. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  537. "excellon_editor_slot_circ_dir":
  538. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  539. "excellon_editor_slot_circ_angle":
  540. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  541. # Geometry General
  542. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  543. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  544. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  545. # Geometry Options
  546. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  547. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  548. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  549. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  550. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  551. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  552. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  553. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  554. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  555. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  556. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.gendz_entry,
  557. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  558. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  559. # Geometry Advanced Options
  560. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  561. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  562. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  563. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  564. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  565. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  566. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  567. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  568. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  569. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  570. # Geometry Editor
  571. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  572. "geometry_editor_milling_type": self.ui.geometry_defaults_form.geometry_editor_group.milling_type_radio,
  573. # CNCJob General
  574. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  575. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  576. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  577. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  578. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  579. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  580. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  581. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  582. # CNC Job Options
  583. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  584. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  585. # CNC Job Advanced Options
  586. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  587. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  588. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  589. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  590. # NCC Tool
  591. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  592. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  593. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  594. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  595. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  596. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  597. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  598. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  599. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  600. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  601. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  602. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  603. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  604. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  605. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  606. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  607. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  608. # CutOut Tool
  609. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  610. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  611. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  612. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  613. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  614. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  615. # Paint Area Tool
  616. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  617. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  618. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  619. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  620. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  621. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  622. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  623. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  624. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  625. # 2-sided Tool
  626. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  627. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  628. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  629. # Film Tool
  630. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  631. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  632. "tools_film_scale_stroke": self.ui.tools_defaults_form.tools_film_group.film_scale_stroke_entry,
  633. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  634. "tools_film_scale_cb": self.ui.tools_defaults_form.tools_film_group.film_scale_cb,
  635. "tools_film_scale_x_entry": self.ui.tools_defaults_form.tools_film_group.film_scalex_entry,
  636. "tools_film_scale_y_entry": self.ui.tools_defaults_form.tools_film_group.film_scaley_entry,
  637. "tools_film_skew_cb": self.ui.tools_defaults_form.tools_film_group.film_skew_cb,
  638. "tools_film_skew_x_entry": self.ui.tools_defaults_form.tools_film_group.film_skewx_entry,
  639. "tools_film_skew_y_entry": self.ui.tools_defaults_form.tools_film_group.film_skewy_entry,
  640. "tools_film_skew_ref_radio": self.ui.tools_defaults_form.tools_film_group.film_skew_reference,
  641. "tools_film_mirror_cb": self.ui.tools_defaults_form.tools_film_group.film_mirror_cb,
  642. "tools_film_mirror_axis_radio": self.ui.tools_defaults_form.tools_film_group.film_mirror_axis,
  643. # Panelize Tool
  644. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  645. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  646. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  647. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  648. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  649. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  650. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  651. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  652. # Calculators Tool
  653. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  654. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  655. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  656. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  657. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  658. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  659. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  660. # Transformations Tool
  661. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  662. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  663. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  664. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  665. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  666. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  667. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  668. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  669. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  670. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  671. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  672. # SolderPaste Dispensing Tool
  673. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  674. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  675. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  676. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  677. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  678. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  679. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  680. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  681. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  682. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  683. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  684. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  685. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  686. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  687. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  688. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  689. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  690. # ###################################################################################
  691. # ################################ TOOLS 2 ##########################################
  692. # ###################################################################################
  693. # Optimal Tool
  694. "tools_opt_precision": self.ui.tools2_defaults_form.tools2_optimal_group.precision_sp,
  695. # Check Rules Tool
  696. "tools_cr_trace_size": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_cb,
  697. "tools_cr_trace_size_val": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_entry,
  698. "tools_cr_c2c": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_cb,
  699. "tools_cr_c2c_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_entry,
  700. "tools_cr_c2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_cb,
  701. "tools_cr_c2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_entry,
  702. "tools_cr_s2s": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_cb,
  703. "tools_cr_s2s_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_entry,
  704. "tools_cr_s2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_cb,
  705. "tools_cr_s2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_entry,
  706. "tools_cr_s2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_cb,
  707. "tools_cr_s2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_entry,
  708. "tools_cr_sm2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_cb,
  709. "tools_cr_sm2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_entry,
  710. "tools_cr_ri": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_cb,
  711. "tools_cr_ri_val": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_entry,
  712. "tools_cr_h2h": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_cb,
  713. "tools_cr_h2h_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_entry,
  714. "tools_cr_dh": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_cb,
  715. "tools_cr_dh_val": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_entry,
  716. # QRCode Tool
  717. "tools_qrcode_version": self.ui.tools2_defaults_form.tools2_qrcode_group.version_entry,
  718. "tools_qrcode_error": self.ui.tools2_defaults_form.tools2_qrcode_group.error_radio,
  719. "tools_qrcode_box_size": self.ui.tools2_defaults_form.tools2_qrcode_group.bsize_entry,
  720. "tools_qrcode_border_size": self.ui.tools2_defaults_form.tools2_qrcode_group.border_size_entry,
  721. "tools_qrcode_qrdata": self.ui.tools2_defaults_form.tools2_qrcode_group.text_data,
  722. "tools_qrcode_polarity": self.ui.tools2_defaults_form.tools2_qrcode_group.pol_radio,
  723. "tools_qrcode_rounded": self.ui.tools2_defaults_form.tools2_qrcode_group.bb_radio,
  724. "tools_qrcode_fill_color": self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry,
  725. "tools_qrcode_back_color": self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry,
  726. "tools_qrcode_sel_limit": self.ui.tools2_defaults_form.tools2_qrcode_group.sel_limit_entry,
  727. # Copper Fill Tool
  728. "tools_copperfill_clearance": self.ui.tools2_defaults_form.tools2_cfill_group.clearance_entry,
  729. "tools_copperfill_margin": self.ui.tools2_defaults_form.tools2_cfill_group.margin_entry,
  730. "tools_copperfill_reference": self.ui.tools2_defaults_form.tools2_cfill_group.reference_radio,
  731. "tools_copperfill_box_type": self.ui.tools2_defaults_form.tools2_cfill_group.bbox_type_radio,
  732. "tools_copperfill_circle_steps": self.ui.tools2_defaults_form.tools2_cfill_group.circlesteps_entry,
  733. # Utilities
  734. # File associations
  735. "fa_excellon": self.ui.util_defaults_form.fa_excellon_group.exc_list_text,
  736. "fa_gcode": self.ui.util_defaults_form.fa_gcode_group.gco_list_text,
  737. # "fa_geometry": self.ui.util_defaults_form.fa_geometry_group.close_paths_cb,
  738. "fa_gerber": self.ui.util_defaults_form.fa_gerber_group.grb_list_text,
  739. "util_autocomplete_keywords": self.ui.util_defaults_form.kw_group.kw_list_text,
  740. }
  741. # ############################
  742. # ### LOAD POSTPROCESSORS ####
  743. # ############################
  744. self.postprocessors = load_postprocessors(self)
  745. for name in list(self.postprocessors.keys()):
  746. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  747. if name.partition('_')[0] == 'Paste':
  748. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  749. continue
  750. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  751. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  752. if name == 'hpgl':
  753. continue
  754. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  755. # ############################
  756. # ### LOAD LANGUAGES ####
  757. # ############################
  758. self.languages = fcTranslate.load_languages()
  759. for name in sorted(self.languages.values()):
  760. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  761. # #################################################################################
  762. # #################### DEFAULTS - PREFERENCES STORAGE #############################
  763. # #################################################################################
  764. self.defaults = LoudDict()
  765. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  766. self.defaults.update({
  767. # Global APP Preferences
  768. "first_run": True,
  769. "units": "IN",
  770. "global_serial": 0,
  771. "global_stats": {},
  772. "global_tabs_detachable": True,
  773. "global_graphic_engine": '3D',
  774. "global_app_level": 'b',
  775. "global_portable": False,
  776. "global_language": 'English',
  777. "global_version_check": True,
  778. "global_send_stats": True,
  779. "global_pan_button": '2',
  780. "global_mselect_key": 'Control',
  781. "global_project_at_startup": False,
  782. "global_systray_icon": True,
  783. "global_project_autohide": True,
  784. "global_toggle_tooltips": True,
  785. "global_worker_number": 2,
  786. "global_tolerance": 0.0002,
  787. "global_open_style": True,
  788. "global_delete_confirmation": True,
  789. "global_compression_level": 3,
  790. "global_save_compressed": True,
  791. # Global GUI Preferences
  792. "global_gridx": 0.0393701,
  793. "global_gridy": 0.0393701,
  794. "global_snap_max": 0.001968504,
  795. "global_workspace": False,
  796. "global_workspaceT": "A4P",
  797. "global_grid_context_menu": {
  798. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  799. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  800. },
  801. "global_plot_fill": '#BBF268BF',
  802. "global_plot_line": '#006E20BF',
  803. "global_sel_fill": '#a5a5ffbf',
  804. "global_sel_line": '#0000ffbf',
  805. "global_alt_sel_fill": '#BBF268BF',
  806. "global_alt_sel_line": '#006E20BF',
  807. "global_draw_color": '#FF0000',
  808. "global_sel_draw_color": '#0000FF',
  809. "global_proj_item_color": '#000000',
  810. "global_proj_item_dis_color": '#b7b7cb',
  811. "global_activity_icon": 'Ball green',
  812. "global_toolbar_view": 511,
  813. "global_background_timeout": 300000, # Default value is 5 minutes
  814. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  815. # (python trace only for unknown errors),
  816. # 1 = show trace(show trace always),
  817. # 2 = (For the future).
  818. # Persistence
  819. "global_last_folder": None,
  820. "global_last_save_folder": None,
  821. # Default window geometry
  822. "global_def_win_x": 100,
  823. "global_def_win_y": 100,
  824. "global_def_win_w": 1024,
  825. "global_def_win_h": 650,
  826. "global_def_notebook_width": 1,
  827. # Constants...
  828. "global_defaults_save_period_ms": 20000, # Time between default saves.
  829. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  830. "global_shell_at_startup": False, # Show the shell at startup.
  831. "global_recent_limit": 10, # Max. items in recent list.
  832. "global_bookmarks": dict(),
  833. "global_bookmarks_limit": 10,
  834. "fit_key": 'V',
  835. "zoom_out_key": '-',
  836. "zoom_in_key": '=',
  837. "grid_toggle_key": 'G',
  838. "global_zoom_ratio": 1.5,
  839. "global_point_clipboard_format": "(%.4f, %.4f)",
  840. "global_zdownrate": None,
  841. # General GUI Settings
  842. "global_theme": 'white',
  843. "global_hover": False,
  844. "global_selection_shape": True,
  845. "global_layout": "compact",
  846. "global_cursor_type": "small",
  847. "global_cursor_size": 20,
  848. # Gerber General
  849. "gerber_plot": True,
  850. "gerber_solid": True,
  851. "gerber_multicolored": False,
  852. "gerber_circle_steps": 128,
  853. "gerber_use_buffer_for_union": True,
  854. "gerber_def_units": 'IN',
  855. "gerber_def_zeros": 'L',
  856. # Gerber Options
  857. "gerber_isotooldia": 0.00787402,
  858. "gerber_isopasses": 1,
  859. "gerber_isooverlap": 0.00393701,
  860. "gerber_milling_type": "cl",
  861. "gerber_combine_passes": False,
  862. "gerber_noncoppermargin": 0.00393701,
  863. "gerber_noncopperrounded": False,
  864. "gerber_bboxmargin": 0.00393701,
  865. "gerber_bboxrounded": False,
  866. # Gerber Advanced Options
  867. "gerber_aperture_display": False,
  868. "gerber_aperture_scale_factor": 1.0,
  869. "gerber_aperture_buffer_factor": 0.0,
  870. "gerber_follow": False,
  871. "gerber_tool_type": 'circular',
  872. "gerber_vtipdia": 0.1,
  873. "gerber_vtipangle": 30,
  874. "gerber_vcutz": -0.05,
  875. "gerber_buffering": "full",
  876. "gerber_simplification": False,
  877. "gerber_simp_tolerance": 0.0005,
  878. # Gerber Export
  879. "gerber_exp_units": 'IN',
  880. "gerber_exp_integer": 2,
  881. "gerber_exp_decimals": 4,
  882. "gerber_exp_zeros": 'L',
  883. # Gerber Editor
  884. "gerber_editor_sel_limit": 30,
  885. "gerber_editor_newcode": 10,
  886. "gerber_editor_newsize": 0.031496,
  887. "gerber_editor_newtype": 'C',
  888. "gerber_editor_newdim": "0.5, 0.5",
  889. "gerber_editor_array_size": 5,
  890. "gerber_editor_lin_axis": 'X',
  891. "gerber_editor_lin_pitch": 1,
  892. "gerber_editor_lin_angle": 0.0,
  893. "gerber_editor_circ_dir": 'CW',
  894. "gerber_editor_circ_angle": 0.0,
  895. "gerber_editor_scale_f": 1.0,
  896. "gerber_editor_buff_f": 0.01,
  897. "gerber_editor_ma_low": 0.0,
  898. "gerber_editor_ma_high": 1.0,
  899. # Excellon General
  900. "excellon_plot": True,
  901. "excellon_solid": True,
  902. "excellon_format_upper_in": 2,
  903. "excellon_format_lower_in": 4,
  904. "excellon_format_upper_mm": 3,
  905. "excellon_format_lower_mm": 3,
  906. "excellon_zeros": "L",
  907. "excellon_units": "INCH",
  908. "excellon_update": True,
  909. "excellon_optimization_type": 'B',
  910. "excellon_search_time": 3,
  911. # Excellon Options
  912. "excellon_drillz": -0.0590551,
  913. "excellon_travelz": 0.0787402,
  914. "excellon_endz": 0.5,
  915. "excellon_feedrate": 3.14961,
  916. "excellon_spindlespeed": None,
  917. "excellon_dwell": False,
  918. "excellon_dwelltime": 1,
  919. "excellon_toolchange": False,
  920. "excellon_toolchangez": 0.5,
  921. "excellon_ppname_e": 'default',
  922. "excellon_tooldia": 0.0314961,
  923. "excellon_slot_tooldia": 0.0708661,
  924. "excellon_gcode_type": "drills",
  925. # Excellon Advanced Options
  926. "excellon_offset": 0.0,
  927. "excellon_toolchangexy": "0.0, 0.0",
  928. "excellon_startz": None,
  929. "excellon_feedrate_rapid": 31.4961,
  930. "excellon_z_pdepth": -0.02,
  931. "excellon_feedrate_probe": 3.14961,
  932. "excellon_spindledir": 'CW',
  933. "excellon_f_plunge": False,
  934. "excellon_f_retract": False,
  935. # Excellon Export
  936. "excellon_exp_units": 'INCH',
  937. "excellon_exp_format": 'ndec',
  938. "excellon_exp_integer": 2,
  939. "excellon_exp_decimals": 4,
  940. "excellon_exp_zeros": 'LZ',
  941. "excellon_exp_slot_type": 'routing',
  942. # Excellon Editor
  943. "excellon_editor_sel_limit": 30,
  944. "excellon_editor_newdia": 0.039,
  945. "excellon_editor_array_size": 5,
  946. "excellon_editor_lin_dir": 'X',
  947. "excellon_editor_lin_pitch": 0.1,
  948. "excellon_editor_lin_angle": 0.0,
  949. "excellon_editor_circ_dir": 'CW',
  950. "excellon_editor_circ_angle": 12,
  951. # Excellon Slots
  952. "excellon_editor_slot_direction": 'X',
  953. "excellon_editor_slot_angle": 0.0,
  954. "excellon_editor_slot_length": 5.0,
  955. # Excellon Slot Array
  956. "excellon_editor_slot_array_size": 5,
  957. "excellon_editor_slot_lin_dir": 'X',
  958. "excellon_editor_slot_lin_pitch": 0.1,
  959. "excellon_editor_slot_lin_angle": 0.0,
  960. "excellon_editor_slot_circ_dir": 'CW',
  961. "excellon_editor_slot_circ_angle": 0.0,
  962. # Geometry General
  963. "geometry_plot": True,
  964. "geometry_circle_steps": 128,
  965. "geometry_cnctooldia": "0.0944882",
  966. # Geometry Options
  967. "geometry_cutz": -0.0944882,
  968. "geometry_vtipdia": 0.1,
  969. "geometry_vtipangle": 30,
  970. "geometry_multidepth": False,
  971. "geometry_depthperpass": 0.0314961,
  972. "geometry_travelz": 0.0787402,
  973. "geometry_toolchange": False,
  974. "geometry_toolchangez": 0.5,
  975. "geometry_endz": 0.5,
  976. "geometry_feedrate": 3.14961,
  977. "geometry_feedrate_z": 3.14961,
  978. "geometry_spindlespeed": None,
  979. "geometry_dwell": False,
  980. "geometry_dwelltime": 1,
  981. "geometry_ppname_g": 'default',
  982. # Geometry Advanced Options
  983. "geometry_toolchangexy": "0.0, 0.0",
  984. "geometry_startz": None,
  985. "geometry_feedrate_rapid": 3.14961,
  986. "geometry_extracut": False,
  987. "geometry_z_pdepth": -0.02,
  988. "geometry_f_plunge": False,
  989. "geometry_spindledir": 'CW',
  990. "geometry_feedrate_probe": 3.14961,
  991. "geometry_segx": 0.0,
  992. "geometry_segy": 0.0,
  993. # Geometry Editor
  994. "geometry_editor_sel_limit": 30,
  995. "geometry_editor_milling_type": "cl",
  996. # CNC Job General
  997. "cncjob_plot": True,
  998. "cncjob_plot_kind": 'all',
  999. "cncjob_annotation": True,
  1000. "cncjob_tooldia": 0.0393701,
  1001. "cncjob_coords_type": "G90",
  1002. "cncjob_coords_decimals": 4,
  1003. "cncjob_fr_decimals": 2,
  1004. "cncjob_steps_per_circle": 128,
  1005. # CNC Job Options
  1006. "cncjob_prepend": "",
  1007. "cncjob_append": "",
  1008. # CNC Job Advanced Options
  1009. "cncjob_toolchange_macro": "",
  1010. "cncjob_toolchange_macro_enable": False,
  1011. "cncjob_annotation_fontsize": 9,
  1012. "cncjob_annotation_fontcolor": '#990000',
  1013. # NCC Tool
  1014. "tools_ncctools": "0.0393701, 0.019685",
  1015. "tools_nccorder": 'rev',
  1016. "tools_nccoverlap": 0.015748,
  1017. "tools_nccmargin": 0.0393701,
  1018. "tools_nccmethod": "seed",
  1019. "tools_nccconnect": True,
  1020. "tools_ncccontour": True,
  1021. "tools_nccrest": False,
  1022. "tools_ncc_offset_choice": False,
  1023. "tools_ncc_offset_value": 0.0000,
  1024. "tools_nccref": 'itself',
  1025. "tools_ncc_plotting": 'normal',
  1026. "tools_nccmilling_type": 'cl',
  1027. "tools_ncctool_type": 'V',
  1028. "tools_ncccutz": -0.001968504,
  1029. "tools_ncctipdia": 0.00393701,
  1030. "tools_ncctipangle": 30,
  1031. # Cutout Tool
  1032. "tools_cutouttooldia": 0.0944882,
  1033. "tools_cutoutkind": "single",
  1034. "tools_cutoutmargin": 0.00393701,
  1035. "tools_cutoutgapsize": 0.15748,
  1036. "tools_gaps_ff": "4",
  1037. "tools_cutout_convexshape": False,
  1038. # Paint Tool
  1039. "tools_painttooldia": 0.023622,
  1040. "tools_paintorder": 'rev',
  1041. "tools_paintoverlap": 0.015748,
  1042. "tools_paintmargin": 0.0,
  1043. "tools_paintmethod": "seed",
  1044. "tools_selectmethod": "all",
  1045. "tools_pathconnect": True,
  1046. "tools_paintcontour": True,
  1047. "tools_paint_plotting": 'normal',
  1048. # 2-Sided Tool
  1049. "tools_2sided_mirror_axis": "X",
  1050. "tools_2sided_axis_loc": "point",
  1051. "tools_2sided_drilldia": 0.11811,
  1052. # Film Tool
  1053. "tools_film_type": 'neg',
  1054. "tools_film_boundary": 0.0393701,
  1055. "tools_film_scale_stroke": 0,
  1056. "tools_film_color": '#000000',
  1057. "tools_film_scale_cb": False,
  1058. "tools_film_scale_x_entry": 1.0,
  1059. "tools_film_scale_y_entry": 1.0,
  1060. "tools_film_skew_cb": False,
  1061. "tools_film_skew_x_entry": 0.0,
  1062. "tools_film_skew_y_entry": 0.0,
  1063. "tools_film_skew_ref_radio": 'bottomleft',
  1064. "tools_film_mirror_cb": False,
  1065. "tools_film_mirror_axis_radio": 'none',
  1066. # Panel Tool
  1067. "tools_panelize_spacing_columns": 0,
  1068. "tools_panelize_spacing_rows": 0,
  1069. "tools_panelize_columns": 1,
  1070. "tools_panelize_rows": 1,
  1071. "tools_panelize_constrain": False,
  1072. "tools_panelize_constrainx": 200.0,
  1073. "tools_panelize_constrainy": 290.0,
  1074. "tools_panelize_panel_type": 'gerber',
  1075. # Calculators Tool
  1076. "tools_calc_vshape_tip_dia": 0.007874,
  1077. "tools_calc_vshape_tip_angle": 30,
  1078. "tools_calc_vshape_cut_z": 0.000787,
  1079. "tools_calc_electro_length": 10.0,
  1080. "tools_calc_electro_width": 10.0,
  1081. "tools_calc_electro_cdensity": 13.0,
  1082. "tools_calc_electro_growth": 10.0,
  1083. # Transform Tool
  1084. "tools_transform_rotate": 90,
  1085. "tools_transform_skew_x": 0.0,
  1086. "tools_transform_skew_y": 0.0,
  1087. "tools_transform_scale_x": 1.0,
  1088. "tools_transform_scale_y": 1.0,
  1089. "tools_transform_scale_link": True,
  1090. "tools_transform_scale_reference": True,
  1091. "tools_transform_offset_x": 0.0,
  1092. "tools_transform_offset_y": 0.0,
  1093. "tools_transform_mirror_reference": False,
  1094. "tools_transform_mirror_point": (0, 0),
  1095. # SolderPaste Tool
  1096. "tools_solderpaste_tools": "0.0393701, 0.011811",
  1097. "tools_solderpaste_new": 0.011811,
  1098. "tools_solderpaste_z_start": 0.00019685039,
  1099. "tools_solderpaste_z_dispense": 0.00393701,
  1100. "tools_solderpaste_z_stop": 0.00019685039,
  1101. "tools_solderpaste_z_travel": 0.00393701,
  1102. "tools_solderpaste_z_toolchange": 0.0393701,
  1103. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  1104. "tools_solderpaste_frxy": 3.0,
  1105. "tools_solderpaste_frz": 3.0,
  1106. "tools_solderpaste_frz_dispense": 0.0393701,
  1107. "tools_solderpaste_speedfwd": 20,
  1108. "tools_solderpaste_dwellfwd": 1,
  1109. "tools_solderpaste_speedrev": 10,
  1110. "tools_solderpaste_dwellrev": 1,
  1111. "tools_solderpaste_pp": 'Paste_1',
  1112. # Subtract Tool
  1113. "tools_sub_close_paths": True,
  1114. # ###################################################################################
  1115. # ################################ TOOLS 2 ##########################################
  1116. # ###################################################################################
  1117. # Optimal Tool
  1118. "tools_opt_precision": 4,
  1119. # Check Rules Tool
  1120. "tools_cr_trace_size": True,
  1121. "tools_cr_trace_size_val": 0.01,
  1122. "tools_cr_c2c": True,
  1123. "tools_cr_c2c_val": 0.01,
  1124. "tools_cr_c2o": True,
  1125. "tools_cr_c2o_val": 0.03937,
  1126. "tools_cr_s2s": True,
  1127. "tools_cr_s2s_val": 0.01,
  1128. "tools_cr_s2sm": True,
  1129. "tools_cr_s2sm_val": 0.01,
  1130. "tools_cr_s2o": True,
  1131. "tools_cr_s2o_val": 0.03937,
  1132. "tools_cr_sm2sm": True,
  1133. "tools_cr_sm2sm_val": 0.01,
  1134. "tools_cr_ri": True,
  1135. "tools_cr_ri_val": 0.015,
  1136. "tools_cr_h2h": True,
  1137. "tools_cr_h2h_val": 0.015,
  1138. "tools_cr_dh": True,
  1139. "tools_cr_dh_val": 0.011811,
  1140. # QRCode Tool
  1141. "tools_qrcode_version": 1,
  1142. "tools_qrcode_error": 'L',
  1143. "tools_qrcode_box_size": 3,
  1144. "tools_qrcode_border_size": 4,
  1145. "tools_qrcode_qrdata": '',
  1146. "tools_qrcode_polarity": 'pos',
  1147. "tools_qrcode_rounded": 's',
  1148. "tools_qrcode_fill_color": '#000000',
  1149. "tools_qrcode_back_color": '#FFFFFF',
  1150. "tools_qrcode_sel_limit": 330,
  1151. # Copper Fill Tool
  1152. "tools_copperfill_clearance": 0.01,
  1153. "tools_copperfill_margin": 0.039,
  1154. "tools_copperfill_reference": 'itself',
  1155. "tools_copperfill_box_type": 'rect',
  1156. "tools_copperfill_circle_steps": 128,
  1157. # Utilities
  1158. # file associations
  1159. "fa_excellon": 'drd, drl, exc, ncd, tap, xln',
  1160. "fa_gcode": 'cnc, din, dnc, ecs, eia, fan, fgc, fnc, gc, gcd, gcode, h, hnc, i, min, mpf, mpr, nc, ncc, '
  1161. 'ncg, ncp, out, plt, ply, rol, sbp, tap, xpi',
  1162. "fa_gerber": 'art, bot, bsm, cmp, crc, crs, dim, g4, gb0, gb1, gb2, gb3, gb5, gb6, gb7, gb8, gb9, gbd, '
  1163. 'gbl, gbo, gbp, gbr, gbs, gdo, ger, gko, gm1, gm2, gm3, grb, gtl, gto, gtp, gts, ly15, ly2, '
  1164. 'mil, pho, plc, pls, smb, smt, sol, spb, spt, ssb, sst, stc, sts, top, tsm',
  1165. # Keyword list
  1166. "util_autocomplete_keywords": 'Desktop, Documents, FlatConfig, FlatPrj, Marius, My Documents, Paste_1, '
  1167. 'Repetier, Roland_MDX_20, Users, Toolchange_Custom, Toolchange_Probe_MACH3, '
  1168. 'Toolchange_manual, Users, all, angle_x, angle_y, axis, auto, axisoffset, '
  1169. 'box, center_x, center_y, columns, combine, connect, contour, default, '
  1170. 'depthperpass, dia, diatol, dist, drilled_dias, drillz, dwell, dwelltime, '
  1171. 'feedrate_z, grbl_11, grbl_laser, gridoffsety, gridx, gridy, has_offset, '
  1172. 'holes, hpgl, iso_type, line_xyz, margin, marlin, method, milled_dias, '
  1173. 'minoffset, multidepth, name, offset, opt_type, order, outname, overlap, '
  1174. 'passes, postamble, pp, ppname_e, ppname_g, preamble, radius, ref, rest, '
  1175. 'rows, shellvar_, scale_factor, spacing_columns, spacing_rows, spindlespeed, '
  1176. 'toolchange_xy, tooldia, use_threads, value, x, x0, x1, y, y0, y1, z_cut, '
  1177. 'z_move',
  1178. "script_autocompleter": True,
  1179. "script_text": "",
  1180. "script_plot": True,
  1181. "script_source_file": "",
  1182. "document_autocompleter": False,
  1183. "document_text": "",
  1184. "document_plot": True,
  1185. "document_source_file": "",
  1186. "document_font_color": '#000000',
  1187. "document_sel_color": '#0055ff',
  1188. "document_font_size": 6,
  1189. "document_tab_size": 80,
  1190. })
  1191. # ############################################################
  1192. # ############### Load defaults from file ####################
  1193. # ############################################################
  1194. if user_defaults:
  1195. self.load_defaults(filename='current_defaults')
  1196. # #############################################################
  1197. # ############## APPLY APP LANGUAGE ###########################
  1198. # #############################################################
  1199. ret_val = fcTranslate.apply_language('strings')
  1200. if ret_val == "no language":
  1201. self.inform.emit('[ERROR] %s' %
  1202. _("Could not find the Language files. The App strings are missing."))
  1203. log.debug("Could not find the Language files. The App strings are missing.")
  1204. else:
  1205. # make the current language the current selection on the language combobox
  1206. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1207. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1208. # ##############################################################
  1209. # ################# CREATE UNIQUE SERIAL NUMBER ################
  1210. # ##############################################################
  1211. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1212. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1213. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  1214. self.save_defaults(silent=True, first_time=True)
  1215. self.propagate_defaults(silent=True)
  1216. self.restore_main_win_geom()
  1217. # def auto_save_defaults():
  1218. # try:
  1219. # self.save_defaults(silent=True)
  1220. # self.propagate_defaults(silent=True)
  1221. # finally:
  1222. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1223. # the following lines activates automatic defaults save
  1224. # if user_defaults:
  1225. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1226. # self.options_form = PreferencesUI()
  1227. self.options_form_fields = {
  1228. "units": self.ui.general_options_form.general_app_group.units_radio,
  1229. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  1230. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  1231. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  1232. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  1233. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  1234. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  1235. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  1236. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  1237. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  1238. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  1239. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  1240. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  1241. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  1242. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  1243. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  1244. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  1245. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  1246. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  1247. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  1248. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  1249. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  1250. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  1251. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  1252. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  1253. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  1254. "excellon_endz": self.ui.excellon_options_form.excellon_opt_group.eendz_entry,
  1255. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  1256. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  1257. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  1258. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  1259. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  1260. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  1261. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  1262. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  1263. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1264. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  1265. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  1266. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  1267. "excellon_spindledir": self.ui.excellon_options_form.excellon_adv_opt_group.spindledir_radio,
  1268. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  1269. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  1270. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  1271. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  1272. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  1273. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  1274. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  1275. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  1276. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  1277. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  1278. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  1279. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  1280. "geometry_endz": self.ui.geometry_options_form.geometry_opt_group.gendz_entry,
  1281. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  1282. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  1283. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  1284. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  1285. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1286. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  1287. "geometry_spindledir": self.ui.geometry_options_form.geometry_adv_opt_group.spindledir_radio,
  1288. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  1289. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  1290. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  1291. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  1292. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  1293. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  1294. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  1295. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  1296. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  1297. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  1298. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  1299. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  1300. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  1301. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  1302. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  1303. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  1304. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  1305. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  1306. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  1307. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  1308. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  1309. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  1310. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  1311. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  1312. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  1313. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  1314. "tools_film_scale_stroke": self.ui.tools_options_form.tools_film_group.film_scale_stroke_entry,
  1315. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  1316. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  1317. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  1318. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  1319. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  1320. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  1321. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  1322. }
  1323. for name in list(self.postprocessors.keys()):
  1324. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1325. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1326. self.options = LoudDict()
  1327. self.options.set_change_callback(self.on_options_dict_change)
  1328. self.options.update({
  1329. "units": "IN",
  1330. "global_gridx": 1.0,
  1331. "global_gridy": 1.0,
  1332. "global_snap_max": 0.05,
  1333. "global_background_timeout": 300000, # Default value is 5 minutes
  1334. "global_verbose_error_level": 0, # Shell verbosity:
  1335. # 0 = default(python trace only for unknown errors),
  1336. # 1 = show trace(show trace allways), 2 = (For the future).
  1337. "gerber_plot": True,
  1338. "gerber_solid": True,
  1339. "gerber_multicolored": False,
  1340. "gerber_isotooldia": 0.016,
  1341. "gerber_isopasses": 1,
  1342. "gerber_isooverlap": 0.15,
  1343. "gerber_combine_passes": True,
  1344. "gerber_noncoppermargin": 0.0,
  1345. "gerber_noncopperrounded": False,
  1346. "gerber_bboxmargin": 0.0,
  1347. "gerber_bboxrounded": False,
  1348. "excellon_plot": True,
  1349. "excellon_solid": False,
  1350. "excellon_format_upper_in": 2,
  1351. "excellon_format_lower_in": 4,
  1352. "excellon_format_upper_mm": 3,
  1353. "excellon_format_lower_mm": 3,
  1354. "excellon_units": 'INCH',
  1355. "excellon_optimization_type": 'B',
  1356. "excellon_search_time": 3,
  1357. "excellon_zeros": "L",
  1358. "excellon_drillz": -0.1,
  1359. "excellon_travelz": 0.1,
  1360. "excellon_feedrate": 3.0,
  1361. "excellon_feedrate_rapid": 3.0,
  1362. "excellon_spindlespeed": None,
  1363. "excellon_spindledir": 'CW',
  1364. "excellon_dwell": True,
  1365. "excellon_dwelltime": 1000,
  1366. "excellon_toolchange": False,
  1367. "excellon_toolchangez": 1.0,
  1368. "excellon_toolchangexy": "0.0, 0.0",
  1369. "excellon_tooldia": 0.016,
  1370. "excellon_ppname_e": 'default',
  1371. "excellon_f_plunge": False,
  1372. "excellon_startz": None,
  1373. "excellon_endz": 2.0,
  1374. "geometry_plot": True,
  1375. "geometry_segx": 0.0,
  1376. "geometry_segy": 0.0,
  1377. "geometry_cutz": -0.002,
  1378. "geometry_vtipdia": 0.1,
  1379. "geometry_vtipangle": 30,
  1380. "geometry_travelz": 0.1,
  1381. "geometry_feedrate": 3.0,
  1382. "geometry_feedrate_z": 3.0,
  1383. "geometry_feedrate_rapid": 3.0,
  1384. "geometry_spindlespeed": None,
  1385. "geometry_spindledir": 'CW',
  1386. "geometry_dwell": True,
  1387. "geometry_dwelltime": 1000,
  1388. "geometry_cnctooldia": 0.016,
  1389. "geometry_toolchange": False,
  1390. "geometry_toolchangez": 2.0,
  1391. "geometry_toolchangexy": "0.0, 0.0",
  1392. "geometry_startz": None,
  1393. "geometry_endz": 2.0,
  1394. "geometry_ppname_g": "default",
  1395. "geometry_f_plunge": False,
  1396. "geometry_depthperpass": 0.002,
  1397. "geometry_multidepth": False,
  1398. "geometry_extracut": False,
  1399. "cncjob_plot": True,
  1400. "cncjob_tooldia": 0.016,
  1401. "cncjob_prepend": "",
  1402. "cncjob_append": "",
  1403. "tools_ncctools": "1.0, 0.5",
  1404. "tools_nccoverlap": 0.4,
  1405. "tools_nccmargin": 1,
  1406. "tools_cutouttooldia": 0.07,
  1407. "tools_cutoutmargin": 0.1,
  1408. "tools_cutoutgapsize": 0.15,
  1409. "tools_gaps_ff": "8",
  1410. "tools_painttooldia": 0.07,
  1411. "tools_paintoverlap": 0.15,
  1412. "tools_paintmargin": 0.0,
  1413. "tools_paintmethod": "seed",
  1414. "tools_selectmethod": "single",
  1415. "tools_pathconnect": True,
  1416. "tools_paintcontour": True,
  1417. "tools_2sided_mirror_axis": "X",
  1418. "tools_2sided_axis_loc": 'point',
  1419. "tools_2sided_drilldia": 1,
  1420. "tools_film_type": 'neg',
  1421. "tools_film_boundary": 1,
  1422. "tools_film_scale_stroke": 0,
  1423. "tools_panelize_spacing_columns": 0,
  1424. "tools_panelize_spacing_rows": 0,
  1425. "tools_panelize_columns": 1,
  1426. "tools_panelize_rows": 1,
  1427. "tools_panelize_constrain": False,
  1428. "tools_panelize_constrainx": 0.0,
  1429. "tools_panelize_constrainy": 0.0,
  1430. "script_text": "",
  1431. "script_plot": False,
  1432. "script_source_file": "",
  1433. "document_text": "",
  1434. "document_plot": False,
  1435. "document_source_file": "",
  1436. })
  1437. # ----------------------------------------------------------------------------------------------------
  1438. # Update the self.options from the self.defaults
  1439. # The self.defaults holds the application defaults while the self.options holds the object defaults
  1440. # -----------------------------------------------------------------------------------------------------
  1441. self.options.update(self.defaults) # Copy app defaults to project options
  1442. self.gen_form = None
  1443. self.ger_form = None
  1444. self.exc_form = None
  1445. self.geo_form = None
  1446. self.cnc_form = None
  1447. self.tools_form = None
  1448. self.tools2_form = None
  1449. self.fa_form = None
  1450. self.on_options_combo_change(0) # Will show the initial form
  1451. # ################################
  1452. # -----------------------------------------------------------------------------------------------------
  1453. # Initialize the color box's color in Preferences -> Global -> Color
  1454. # -----------------------------------------------------------------------------------------------------
  1455. # Init Plot Colors
  1456. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  1457. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  1458. "background-color:%s;"
  1459. "border-color: dimgray" % str(self.defaults['global_plot_fill'])[:7])
  1460. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  1461. int(self.defaults['global_plot_fill'][7:9], 16))
  1462. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  1463. int(self.defaults['global_plot_fill'][7:9], 16))
  1464. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  1465. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  1466. "background-color:%s;"
  1467. "border-color: dimgray" % str(self.defaults['global_plot_line'])[:7])
  1468. # Init Left-Right Selection colors
  1469. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  1470. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  1471. "background-color:%s;"
  1472. "border-color: dimgray" % str(self.defaults['global_sel_fill'])[:7])
  1473. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1474. int(self.defaults['global_sel_fill'][7:9], 16))
  1475. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1476. int(self.defaults['global_sel_fill'][7:9], 16))
  1477. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1478. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1479. "background-color:%s;"
  1480. "border-color: dimgray" % str(self.defaults['global_sel_line'])[:7])
  1481. # Init Right-Left Selection colors
  1482. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1483. self.defaults['global_alt_sel_fill'])
  1484. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1485. "background-color:%s;"
  1486. "border-color: dimgray" % str(self.defaults['global_alt_sel_fill'])[:7])
  1487. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1488. int(self.defaults['global_sel_fill'][7:9], 16))
  1489. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1490. int(self.defaults['global_sel_fill'][7:9], 16))
  1491. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1492. self.defaults['global_alt_sel_line'])
  1493. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1494. "background-color:%s;"
  1495. "border-color: dimgray" % str(self.defaults['global_alt_sel_line'])[:7])
  1496. # Init Draw color and Selection Draw Color
  1497. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1498. self.defaults['global_draw_color'])
  1499. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1500. "background-color:%s;"
  1501. "border-color: dimgray" % str(self.defaults['global_draw_color'])[:7])
  1502. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1503. self.defaults['global_sel_draw_color'])
  1504. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1505. "background-color:%s;"
  1506. "border-color: dimgray" % str(self.defaults['global_sel_draw_color'])[:7])
  1507. # Init Project Items color
  1508. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1509. self.defaults['global_proj_item_color'])
  1510. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1511. "background-color:%s;"
  1512. "border-color: dimgray" % str(self.defaults['global_proj_item_color'])[:7])
  1513. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1514. self.defaults['global_proj_item_dis_color'])
  1515. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1516. "background-color:%s;"
  1517. "border-color: dimgray" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1518. # Init the Annotation CNC Job color
  1519. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  1520. self.defaults['cncjob_annotation_fontcolor'])
  1521. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  1522. "background-color:%s;"
  1523. "border-color: dimgray" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  1524. # Init the Tool Film color
  1525. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  1526. self.defaults['tools_film_color'])
  1527. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  1528. "background-color:%s;"
  1529. "border-color: dimgray" % str(self.defaults['tools_film_color'])[:7]
  1530. )
  1531. # Init the Tool QRCode colors
  1532. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(
  1533. self.defaults['tools_qrcode_fill_color'])
  1534. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  1535. "background-color:%s;"
  1536. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])[:7])
  1537. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(
  1538. self.defaults['tools_qrcode_back_color'])
  1539. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  1540. "background-color:%s;"
  1541. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])[:7])
  1542. # ### End of Data ####
  1543. # ##############################################
  1544. # ######### SETUP OBJECT COLLECTION ############
  1545. # ##############################################
  1546. self.collection = ObjectCollection(self)
  1547. self.ui.project_tab_layout.addWidget(self.collection.view)
  1548. # ### Adjust tabs width ## ##
  1549. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1550. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1551. self.collection.view.setMinimumWidth(290)
  1552. self.log.debug("Finished creating Object Collection.")
  1553. # ###############################################
  1554. # ############# SETUP Plot Area #################
  1555. # ###############################################
  1556. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  1557. if self.defaults["global_graphic_engine"] == '3D':
  1558. self.is_legacy = False
  1559. else:
  1560. self.is_legacy = True
  1561. # Matplotlib axis
  1562. self.axes = None
  1563. if show_splash:
  1564. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1565. "Canvas initialization started."),
  1566. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1567. color=QtGui.QColor("gray"))
  1568. start_plot_time = time.time() # debug
  1569. self.plotcanvas = None
  1570. self.app_cursor = None
  1571. self.hover_shapes = None
  1572. self.on_plotcanvas_setup()
  1573. end_plot_time = time.time()
  1574. self.used_time = end_plot_time - start_plot_time
  1575. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1576. if show_splash:
  1577. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1578. "Canvas initialization started.\n"
  1579. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1580. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1581. color=QtGui.QColor("gray"))
  1582. self.ui.splitter.setStretchFactor(1, 2)
  1583. # #################################################################
  1584. # ####################### SYS TRAY ################################
  1585. # #################################################################
  1586. if self.defaults["global_systray_icon"]:
  1587. self.parent_w = QtWidgets.QWidget()
  1588. if self.cmd_line_headless == 1:
  1589. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1590. headless=True,
  1591. parent=self.parent_w)
  1592. else:
  1593. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1594. parent=self.parent_w)
  1595. # #################################################################
  1596. # ####################### Worker SETUP ############################
  1597. # #################################################################
  1598. if self.defaults["global_worker_number"]:
  1599. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1600. else:
  1601. self.workers = WorkerStack(workers_number=2)
  1602. self.worker_task.connect(self.workers.add_task)
  1603. self.log.debug("Finished creating Workers crew.")
  1604. # #################################################################
  1605. # ######################## Activity Monitor #######################
  1606. # #################################################################
  1607. if self.defaults["global_activity_icon"] == "Ball green":
  1608. icon = 'share/active_2_static.png'
  1609. movie = "share/active_2.gif"
  1610. elif self.defaults["global_activity_icon"] == "Ball black":
  1611. icon = 'share/active_static.png'
  1612. movie = "share/active.gif"
  1613. elif self.defaults["global_activity_icon"] == "Arrow green":
  1614. icon = 'share/active_3_static.png'
  1615. movie = "share/active_3.gif"
  1616. elif self.defaults["global_activity_icon"] == "Eclipse green":
  1617. icon = 'share/active_4_static.png'
  1618. movie = "share/active_4.gif"
  1619. else:
  1620. icon = 'share/active_static.png'
  1621. movie = "share/active.gif"
  1622. self.activity_view = FlatCAMActivityView(icon=icon, movie=movie)
  1623. self.ui.infobar.addWidget(self.activity_view)
  1624. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  1625. # #################################################################
  1626. # ######################### Signal handling #######################
  1627. # #################################################################
  1628. # ########################### Custom signals #####################
  1629. # signal for displaying messages in status bar
  1630. self.inform.connect(self.info)
  1631. # signal to be called when the app is quiting
  1632. self.app_quit.connect(self.quit_application)
  1633. self.message.connect(self.message_dialog)
  1634. self.progress.connect(self.set_progress_bar)
  1635. # signals that are emitted when object state changes
  1636. self.object_created.connect(self.on_object_created)
  1637. self.object_changed.connect(self.on_object_changed)
  1638. self.object_plotted.connect(self.on_object_plotted)
  1639. self.plots_updated.connect(self.on_plots_updated)
  1640. # signals emitted when file state change
  1641. self.file_opened.connect(self.register_recent)
  1642. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1643. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1644. # ############# Standard signals ###################
  1645. # ### Menu
  1646. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1647. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1648. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1649. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1650. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  1651. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1652. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1653. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1654. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1655. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1656. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1657. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1658. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1659. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1660. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1661. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1662. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1663. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1664. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1665. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1666. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1667. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1668. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1669. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1670. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1671. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1672. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1673. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1674. self.ui.menufile_exit.triggered.connect(self.final_save)
  1675. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1676. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1677. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1678. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1679. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1680. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1681. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1682. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1683. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1684. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1685. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1686. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1687. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1688. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1689. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1690. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1691. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1692. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1693. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1694. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1695. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1696. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1697. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1698. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1699. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1700. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1701. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1702. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1703. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1704. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1705. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1706. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1707. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1708. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1709. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1710. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1711. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1712. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1713. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1714. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  1715. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1716. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  1717. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1718. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1719. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1720. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1721. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1722. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1723. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1724. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1725. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1726. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1727. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1728. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1729. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1730. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1731. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1732. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1733. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1734. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1735. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1736. # ToolBar signals
  1737. self.connect_toolbar_signals()
  1738. # Notebook and Plot Tab Area signals
  1739. # make the right click on the notebook tab and plot tab area tab raise a menu
  1740. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1741. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1742. self.on_tab_setup_context_menu()
  1743. # activate initial state
  1744. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1745. # Context Menu
  1746. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1747. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1748. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1749. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1750. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1751. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1752. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1753. self.ui.clearplot.triggered.connect(self.clear_plots)
  1754. self.ui.replot.triggered.connect(self.plot_all)
  1755. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1756. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1757. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1758. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1759. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1760. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1761. # Preferences Plot Area TAB
  1762. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1763. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1764. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1765. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1766. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1767. # ##############################
  1768. # ### GUI PREFERENCES SIGNALS ##
  1769. # ##############################
  1770. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  1771. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1772. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1773. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1774. )
  1775. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1776. lambda: self.on_toggle_units(no_pref=False))
  1777. # ###############################################################
  1778. # ################### GUI COLORS SIGNALS ########################
  1779. # ###############################################################
  1780. # Setting plot colors signals
  1781. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1782. self.on_pf_color_entry)
  1783. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1784. self.on_pf_color_button)
  1785. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1786. self.on_pf_color_spinner)
  1787. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1788. self.on_pf_color_slider)
  1789. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1790. self.on_pl_color_entry)
  1791. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1792. self.on_pl_color_button)
  1793. # Setting selection (left - right) colors signals
  1794. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1795. self.on_sf_color_entry)
  1796. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1797. self.on_sf_color_button)
  1798. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1799. self.on_sf_color_spinner)
  1800. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1801. self.on_sf_color_slider)
  1802. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1803. self.on_sl_color_entry)
  1804. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1805. self.on_sl_color_button)
  1806. # Setting selection (right - left) colors signals
  1807. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1808. self.on_alt_sf_color_entry)
  1809. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1810. self.on_alt_sf_color_button)
  1811. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1812. self.on_alt_sf_color_spinner)
  1813. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1814. self.on_alt_sf_color_slider)
  1815. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1816. self.on_alt_sl_color_entry)
  1817. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1818. self.on_alt_sl_color_button)
  1819. # Setting Editor Draw colors signals
  1820. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1821. self.on_draw_color_entry)
  1822. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1823. self.on_draw_color_button)
  1824. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1825. self.on_sel_draw_color_entry)
  1826. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1827. self.on_sel_draw_color_button)
  1828. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1829. self.on_proj_color_entry)
  1830. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1831. self.on_proj_color_button)
  1832. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1833. self.on_proj_color_dis_entry)
  1834. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1835. self.on_proj_color_dis_button)
  1836. # ########## workspace setting signals ###########
  1837. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1838. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1839. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1840. # #################################################
  1841. # ############ GUI SETTINGS SIGNALS ###############
  1842. # #################################################
  1843. self.ui.general_defaults_form.general_gui_set_group.theme_radio.activated_custom.connect(self.on_theme_change)
  1844. self.ui.general_defaults_form.general_gui_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  1845. # ########## CNC Job related signals #############
  1846. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1847. self.on_cnc_custom_parameters)
  1848. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.editingFinished.connect(
  1849. self.on_annotation_fontcolor_entry)
  1850. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.clicked.connect(
  1851. self.on_annotation_fontcolor_button)
  1852. # ########## Tools related signals #############
  1853. # Film Tool
  1854. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1855. self.on_film_color_entry)
  1856. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1857. self.on_film_color_button)
  1858. # QRCode Tool
  1859. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  1860. self.on_qrcode_fill_color_entry)
  1861. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  1862. self.on_qrcode_fill_color_button)
  1863. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  1864. self.on_qrcode_back_color_entry)
  1865. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  1866. self.on_qrcode_back_color_button)
  1867. # portability changed signal
  1868. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1869. # Object list
  1870. self.collection.view.activated.connect(self.on_row_activated)
  1871. self.collection.item_selected.connect(self.on_row_selected)
  1872. self.object_status_changed.connect(self.on_collection_updated)
  1873. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1874. self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1875. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1876. # Export Excellon parameters.
  1877. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1878. self.on_update_exc_export
  1879. )
  1880. # call it once to make sure it is updated at startup
  1881. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1882. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1883. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1884. self.on_excellon_defaults_button)
  1885. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1886. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1887. self.on_excellon_options_button)
  1888. # when there are arguments at application startup this get launched
  1889. self.args_at_startup[list].connect(self.on_startup_args)
  1890. # ##############################################################
  1891. # ############### FILE ASSOCIATIONS SIGNALS ####################
  1892. # ##############################################################
  1893. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1894. lambda: self.restore_extensions(ext_type='excellon'))
  1895. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1896. lambda: self.restore_extensions(ext_type='gcode'))
  1897. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1898. lambda: self.restore_extensions(ext_type='gerber'))
  1899. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1900. lambda: self.delete_all_extensions(ext_type='excellon'))
  1901. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1902. lambda: self.delete_all_extensions(ext_type='gcode'))
  1903. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1904. lambda: self.delete_all_extensions(ext_type='gerber'))
  1905. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1906. lambda: self.add_extension(ext_type='excellon'))
  1907. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1908. lambda: self.add_extension(ext_type='gcode'))
  1909. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1910. lambda: self.add_extension(ext_type='gerber'))
  1911. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1912. lambda: self.del_extension(ext_type='excellon'))
  1913. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1914. lambda: self.del_extension(ext_type='gcode'))
  1915. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1916. lambda: self.del_extension(ext_type='gerber'))
  1917. # connect the 'Apply' buttons from the Preferences/File Associations
  1918. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1919. lambda: self.on_register_files(obj_type='excellon'))
  1920. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1921. lambda: self.on_register_files(obj_type='gcode'))
  1922. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1923. lambda: self.on_register_files(obj_type='gerber'))
  1924. # ##############################################################
  1925. # ###################### KEYWORDS SIGNALS ######################
  1926. # ##############################################################
  1927. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1928. lambda: self.restore_extensions(ext_type='keyword'))
  1929. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1930. lambda: self.delete_all_extensions(ext_type='keyword'))
  1931. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1932. lambda: self.add_extension(ext_type='keyword'))
  1933. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1934. lambda: self.del_extension(ext_type='keyword'))
  1935. # splash screen button signal
  1936. self.ui.general_defaults_form.general_gui_set_group.splash_cb.stateChanged.connect(self.on_splash_changed)
  1937. # connect the abort_all_tasks related slots to the related signals
  1938. self.proc_container.idle_flag.connect(self.app_is_idle)
  1939. # signal emitted when a tab is closed in the Plot Area
  1940. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  1941. # #####################################################################################
  1942. # ########### FINISHED CONNECTING SIGNALS #############################################
  1943. # #####################################################################################
  1944. self.log.debug("Finished connecting Signals.")
  1945. # #####################################################################################
  1946. # ########################## Other setups #############################################
  1947. # #####################################################################################
  1948. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  1949. # depending on from where those tools are called different actions can be done
  1950. self.call_source = 'app'
  1951. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1952. self.tool_tab_locked = False
  1953. # decide if to show or hide the Notebook side of the screen at startup
  1954. if self.defaults["global_project_at_startup"] is True:
  1955. self.ui.splitter.setSizes([1, 1])
  1956. else:
  1957. self.ui.splitter.setSizes([0, 1])
  1958. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1959. self.setup_obj_classes()
  1960. self.setup_recent_items()
  1961. self.setup_component_editor()
  1962. # this does not work in Legacy Mode
  1963. if self.is_legacy is True:
  1964. self.ui.general_defaults_form.general_gui_group.workspace_cb.setDisabled(True)
  1965. self.ui.general_defaults_form.general_gui_group.workspace_type_lbl.setDisabled(True)
  1966. self.ui.general_defaults_form.general_gui_group.wk_cb.setDisabled(True)
  1967. # #####################################################################################
  1968. # ######################### Auto-complete KEYWORDS ####################################
  1969. # #####################################################################################
  1970. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1971. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1972. 'delete', 'drillcncjob', 'export_gcode', 'export_svg', 'ext', 'exteriors', 'follow',
  1973. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1974. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1975. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1976. 'mirror', 'ncc',
  1977. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1978. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'origin',
  1979. 'paint', 'pan', 'panel', 'panelize', 'plot_all', 'plot_objects', 'quit_flatcam',
  1980. 'save', 'save_project',
  1981. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_sys',
  1982. 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1983. 'version', 'write_gcode'
  1984. ]
  1985. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'Marius', 'My Documents', 'Paste_1',
  1986. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  1987. 'Toolchange_manual', 'Users', 'all', 'angle_x', 'angle_y', 'auto', 'axis',
  1988. 'axisoffset',
  1989. 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect', 'contour', 'default',
  1990. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dwell',
  1991. 'dwelltime', 'feedrate_z', 'grbl_11', 'grbl_laser', 'gridoffsety', 'gridx', 'gridy',
  1992. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  1993. 'milled_dias', 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order',
  1994. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  1995. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  1996. 'spacing_columns',
  1997. 'spacing_rows', 'spindlespeed', 'toolchange_xy', 'tooldia', 'use_threads', 'value',
  1998. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1999. ]
  2000. self.tcl_keywords = [
  2001. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  2002. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  2003. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  2004. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  2005. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  2006. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  2007. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  2008. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  2009. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  2010. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  2011. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  2012. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  2013. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  2014. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  2015. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  2016. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  2017. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  2018. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  2019. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  2020. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  2021. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  2022. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  2023. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  2024. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  2025. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  2026. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  2027. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  2028. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  2029. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  2030. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  2031. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  2032. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  2033. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  2034. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  2035. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  2036. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  2037. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  2038. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  2039. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  2040. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  2041. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  2042. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  2043. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  2044. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  2045. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  2046. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  2047. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  2048. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  2049. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  2050. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  2051. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  2052. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  2053. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  2054. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  2055. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  2056. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  2057. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  2058. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  2059. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  2060. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  2061. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  2062. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  2063. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  2064. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  2065. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  2066. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  2067. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  2068. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  2069. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  2070. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  2071. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  2072. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  2073. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  2074. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  2075. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  2076. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  2077. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  2078. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  2079. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  2080. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  2081. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  2082. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  2083. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  2084. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  2085. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  2086. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  2087. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  2088. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  2089. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  2090. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  2091. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  2092. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  2093. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  2094. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  2095. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  2096. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  2097. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  2098. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  2099. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  2100. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  2101. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  2102. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  2103. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  2104. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  2105. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  2106. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  2107. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  2108. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  2109. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  2110. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  2111. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  2112. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  2113. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  2114. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  2115. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  2116. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  2117. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  2118. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  2119. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  2120. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  2121. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  2122. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  2123. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  2124. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  2125. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  2126. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  2127. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  2128. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  2129. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  2130. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  2131. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  2132. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  2133. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  2134. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  2135. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  2136. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  2137. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  2138. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  2139. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  2140. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  2141. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  2142. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  2143. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  2144. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  2145. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  2146. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  2147. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  2148. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  2149. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  2150. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  2151. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  2152. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  2153. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  2154. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  2155. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  2156. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  2157. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  2158. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  2159. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  2160. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  2161. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  2162. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  2163. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  2164. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  2165. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  2166. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  2167. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  2168. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  2169. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  2170. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  2171. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  2172. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  2173. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  2174. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  2175. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  2176. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  2177. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  2178. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  2179. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  2180. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  2181. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  2182. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  2183. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  2184. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  2185. ]
  2186. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  2187. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2188. # ####################################################################################
  2189. # ####################### Shell SETUP ################################################
  2190. # ####################################################################################
  2191. # this will hold the TCL instance
  2192. self.tcl = None
  2193. self.init_tcl()
  2194. self.shell = FCShell(self, version=self.version)
  2195. self.shell._edit.set_model_data(self.myKeywords)
  2196. self.shell.setWindowIcon(self.ui.app_icon)
  2197. self.shell.setWindowTitle("FlatCAM Shell")
  2198. self.shell.resize(*self.defaults["global_shell_shape"])
  2199. self.shell.append_output("FlatCAM %s - " % self.version)
  2200. self.shell.append_output(_("Type >help< to get started\n\n"))
  2201. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  2202. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  2203. self.ui.shell_dock.setWidget(self.shell)
  2204. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  2205. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  2206. QtWidgets.QDockWidget.DockWidgetFloatable |
  2207. QtWidgets.QDockWidget.DockWidgetClosable)
  2208. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  2209. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  2210. if self.defaults["global_shell_at_startup"]:
  2211. self.ui.shell_dock.show()
  2212. else:
  2213. self.ui.shell_dock.hide()
  2214. # ##################################################################################
  2215. # ###################### Tools and Plugins #########################################
  2216. # ##################################################################################
  2217. self.dblsidedtool = None
  2218. self.distance_tool = None
  2219. self.distance_min_tool = None
  2220. self.panelize_tool = None
  2221. self.film_tool = None
  2222. self.paste_tool = None
  2223. self.calculator_tool = None
  2224. self.rules_tool = None
  2225. self.sub_tool = None
  2226. self.move_tool = None
  2227. self.cutout_tool = None
  2228. self.ncclear_tool = None
  2229. self.optimal_tool = None
  2230. self.paint_tool = None
  2231. self.transform_tool = None
  2232. self.properties_tool = None
  2233. self.pdf_tool = None
  2234. self.image_tool = None
  2235. self.pcb_wizard_tool = None
  2236. self.cal_exc_tool = None
  2237. self.qrcode_tool = None
  2238. self.copperfill_tool = None
  2239. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  2240. self.install_tools()
  2241. # ##################################################################################
  2242. # ########################### BookMarks Manager ####################################
  2243. # ##################################################################################
  2244. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  2245. self.install_bookmarks()
  2246. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  2247. # ### System Font Parsing ###
  2248. # self.f_parse = ParseFont(self)
  2249. # self.parse_system_fonts()
  2250. # #####################################################################################
  2251. # ######################## Check for updates ##########################################
  2252. # #####################################################################################
  2253. # Separate thread (Not worker)
  2254. # Check for updates on startup but only if the user consent and the app is not in Beta version
  2255. if (self.beta is False or self.beta is None) and \
  2256. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  2257. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  2258. self.thr2 = QtCore.QThread()
  2259. self.worker_task.emit({'fcn': self.version_check,
  2260. 'params': []})
  2261. self.thr2.start(QtCore.QThread.LowPriority)
  2262. # #####################################################################################
  2263. # ######################### Register files with FlatCAM; #############################
  2264. # ######################### It works only for Windows for now ########################
  2265. # #####################################################################################
  2266. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  2267. self.on_register_files()
  2268. # #####################################################################################
  2269. # ###################### Variables for global usage ###################################
  2270. # #####################################################################################
  2271. # coordinates for relative position display
  2272. self.rel_point1 = (0, 0)
  2273. self.rel_point2 = (0, 0)
  2274. # variable to store coordinates
  2275. self.pos = (0, 0)
  2276. self.pos_jump = (0, 0)
  2277. # variable to store mouse coordinates
  2278. self.mouse = [0, 0]
  2279. # decide if we have a double click or single click
  2280. self.doubleclick = False
  2281. # variable to store if a command is active (then the var is not None) and which one it is
  2282. self.command_active = None
  2283. # variable to store the status of moving selection action
  2284. # None value means that it's not an selection action
  2285. # True value = a selection from left to right
  2286. # False value = a selection from right to left
  2287. self.selection_type = None
  2288. # List to store the objects that are currently loaded in FlatCAM
  2289. # This list is updated on each object creation or object delete
  2290. self.all_objects_list = list()
  2291. # List to store the objects that are selected
  2292. self.sel_objects_list = list()
  2293. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  2294. self.key_modifiers = None
  2295. # Variable to hold the status of the axis
  2296. self.toggle_axis = True
  2297. # Variable to hold the status of the grid lines
  2298. self.toggle_grid_lines = True
  2299. # Variable to store the status of the fullscreen event
  2300. self.toggle_fscreen = False
  2301. # Variable to store the status of the code editor
  2302. self.toggle_codeeditor = False
  2303. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  2304. self.click_noproject = False
  2305. self.cursor = None
  2306. # Variable to store the GCODE that was edited
  2307. self.gcode_edited = ""
  2308. self.text_editor_tab = None
  2309. # reference for the self.ui.code_editor
  2310. self.reference_code_editor = None
  2311. self.script_code = ''
  2312. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  2313. self.preferences_changed_flag = False
  2314. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  2315. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  2316. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'pho',
  2317. 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top', 'tsm']
  2318. self.exc_list = ['drd', 'drl', 'exc', 'ncd', 'tap', 'txt', 'xln']
  2319. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  2320. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ncp', 'out', 'plt', 'ply', 'rol', 'sbp',
  2321. 'tap', 'xpi']
  2322. self.svg_list = ['svg']
  2323. self.dxf_list = ['dxf']
  2324. self.pdf_list = ['pdf']
  2325. self.prj_list = ['flatprj']
  2326. self.conf_list = ['flatconfig']
  2327. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  2328. # flag for polygons not cleared
  2329. self.poly_not_cleared = False
  2330. # VisPy visuals
  2331. self.isHovering = False
  2332. self.notHovering = True
  2333. # Window geometry
  2334. self.x_pos = None
  2335. self.y_pos = None
  2336. self.width = None
  2337. self.height = None
  2338. # Event signals disconnect id holders
  2339. self.mp = None
  2340. self.mm = None
  2341. self.mr = None
  2342. self.mp_zc = None
  2343. # when True, the app has to return from any thread
  2344. self.abort_flag = False
  2345. # set the value used in the Windows Title
  2346. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  2347. # this holds a widget that is installed in the Plot Area when View Source option is used
  2348. self.source_editor_tab = None
  2349. # ###############################################################################
  2350. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  2351. # ############# It's done only once after install ###############
  2352. # ###############################################################################
  2353. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  2354. fac_def_from_file = factory_file.read()
  2355. factory_defaults = json.loads(fac_def_from_file)
  2356. # if the file contain an empty dictionary then save the factory defaults into the file
  2357. if not factory_defaults:
  2358. self.save_factory_defaults(silent_message=False)
  2359. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  2360. initial_lay = 'compact'
  2361. self.on_layout(lay=initial_lay)
  2362. # Set the combobox in Preferences to the current layout
  2363. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  2364. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  2365. factory_file.close()
  2366. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  2367. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  2368. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  2369. # after the first run, this object should be False
  2370. self.defaults["first_run"] = False
  2371. # ###############################################################################
  2372. # ################# ADDING FlatCAM EDITORS section ##############################
  2373. # ###############################################################################
  2374. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2375. # at the first launch of the App , the editors will not be functional.
  2376. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  2377. self.exc_editor = FlatCAMExcEditor(self)
  2378. self.grb_editor = FlatCAMGrbEditor(self)
  2379. self.log.debug("Finished adding FlatCAM Editor's.")
  2380. self.set_ui_title(name=_("New Project - Not saved"))
  2381. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2382. current_platform = platform.architecture()[0]
  2383. if current_platform != '64bit':
  2384. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2385. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2386. # ###############################################################################
  2387. # ####################### Finished the CONSTRUCTOR ##############################
  2388. # ###############################################################################
  2389. App.log.debug("END of constructor. Releasing control.")
  2390. # #####################################################################################
  2391. # ########################## SHOW GUI #################################################
  2392. # #####################################################################################
  2393. # if the app is not started as headless, show it
  2394. if self.cmd_line_headless != 1:
  2395. if show_splash:
  2396. # finish the splash
  2397. self.splash.finish(self.ui)
  2398. settings = QSettings("Open Source", "FlatCAM")
  2399. if settings.contains("maximized_gui"):
  2400. maximized_ui = settings.value('maximized_gui', type=bool)
  2401. if maximized_ui is True:
  2402. self.ui.showMaximized()
  2403. else:
  2404. self.ui.show()
  2405. else:
  2406. self.ui.show()
  2407. if self.defaults["global_systray_icon"]:
  2408. self.trayIcon.show()
  2409. else:
  2410. log.warning("******************* RUNNING HEADLESS *******************")
  2411. # #####################################################################################
  2412. # ########################## START-UP ARGUMENTS #######################################
  2413. # #####################################################################################
  2414. # test if the program was started with a script as parameter
  2415. if self.cmd_line_shellvar:
  2416. try:
  2417. cnt = 0
  2418. command_tcl = 0
  2419. for i in self.cmd_line_shellvar.split(','):
  2420. if i is not None:
  2421. try:
  2422. command_tcl = eval(i)
  2423. except:
  2424. command_tcl = i
  2425. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  2426. cnt += 1
  2427. # if there are Windows paths then replace the path separator with a Unix like one
  2428. if sys.platform == 'win32':
  2429. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  2430. self.shell._sysShell.exec_command(command_tcl_formatted, no_echo=True)
  2431. except Exception as ext:
  2432. print("ERROR: ", ext)
  2433. sys.exit(2)
  2434. if self.cmd_line_shellfile:
  2435. try:
  2436. if self.ui.shell_dock.isHidden():
  2437. self.ui.shell_dock.show()
  2438. with open(self.cmd_line_shellfile, "r") as myfile:
  2439. if show_splash:
  2440. self.splash.showMessage('%s: %ssec\n%s' % (
  2441. _("Canvas initialization started.\n"
  2442. "Canvas initialization finished in"), '%.2f' % self.used_time,
  2443. _("Executing Tcl Script ...")),
  2444. alignment=Qt.AlignBottom | Qt.AlignLeft,
  2445. color=QtGui.QColor("gray"))
  2446. cmd_line_shellfile_text = myfile.read()
  2447. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  2448. except Exception as ext:
  2449. print("ERROR: ", ext)
  2450. sys.exit(2)
  2451. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2452. # the path/file_name must be enclosed in quotes if it contain spaces
  2453. if App.args:
  2454. self.args_at_startup.emit(App.args)
  2455. @staticmethod
  2456. def copy_and_overwrite(from_path, to_path):
  2457. """
  2458. From here:
  2459. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2460. :param from_path: source path
  2461. :param to_path: destination path
  2462. :return: None
  2463. """
  2464. if os.path.exists(to_path):
  2465. shutil.rmtree(to_path)
  2466. try:
  2467. shutil.copytree(from_path, to_path)
  2468. except FileNotFoundError:
  2469. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2470. shutil.copytree(from_new_path, to_path)
  2471. def on_startup_args(self, args, silent=False):
  2472. """
  2473. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2474. :param args: a list containing the application args at startup
  2475. :return: None
  2476. """
  2477. if args is not None:
  2478. args_to_process = args
  2479. else:
  2480. args_to_process = App.args
  2481. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2482. for argument in args_to_process:
  2483. if '.FlatPrj'.lower() in argument.lower():
  2484. try:
  2485. project_name = str(argument)
  2486. if project_name == "":
  2487. if silent is False:
  2488. self.inform.emit(_("Open cancelled."))
  2489. else:
  2490. # self.open_project(project_name)
  2491. run_from_arg = True
  2492. # self.worker_task.emit({'fcn': self.open_project,
  2493. # 'params': [project_name, run_from_arg]})
  2494. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2495. except Exception as e:
  2496. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2497. elif '.FlatConfig'.lower() in argument.lower():
  2498. try:
  2499. file_name = str(argument)
  2500. if file_name == "":
  2501. if silent is False:
  2502. self.inform.emit(_("Open Config file failed."))
  2503. else:
  2504. run_from_arg = True
  2505. # self.worker_task.emit({'fcn': self.open_config_file,
  2506. # 'params': [file_name, run_from_arg]})
  2507. self.open_config_file(file_name, run_from_arg=run_from_arg)
  2508. except Exception as e:
  2509. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2510. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  2511. try:
  2512. file_name = str(argument)
  2513. if file_name == "":
  2514. if silent is False:
  2515. self.inform.emit(_("Open Script file failed."))
  2516. else:
  2517. if silent is False:
  2518. self.on_fileopenscript(name=file_name)
  2519. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  2520. self.on_filerunscript(name=file_name)
  2521. except Exception as e:
  2522. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2523. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  2524. log.debug("App.on_startup_args() --> Quit event.")
  2525. sys.exit()
  2526. elif 'save'.lower() in argument.lower():
  2527. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  2528. self.save_defaults()
  2529. else:
  2530. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2531. proc_arg = argument.lower()
  2532. for ext in exc_list:
  2533. proc_ext = ext.replace(' ', '')
  2534. proc_ext = '.%s' % proc_ext
  2535. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2536. file_name = str(argument)
  2537. if file_name == "":
  2538. if silent is False:
  2539. self.inform.emit(_("Open Excellon file failed."))
  2540. else:
  2541. self.on_fileopenexcellon(name=file_name)
  2542. return
  2543. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2544. for ext in gco_list:
  2545. proc_ext = ext.replace(' ', '')
  2546. proc_ext = '.%s' % proc_ext
  2547. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2548. file_name = str(argument)
  2549. if file_name == "":
  2550. if silent is False:
  2551. self.inform.emit(_("Open GCode file failed."))
  2552. else:
  2553. self.on_fileopengcode(name=file_name)
  2554. return
  2555. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2556. for ext in grb_list:
  2557. proc_ext = ext.replace(' ', '')
  2558. proc_ext = '.%s' % proc_ext
  2559. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2560. file_name = str(argument)
  2561. if file_name == "":
  2562. if silent is False:
  2563. self.inform.emit(_("Open Gerber file failed."))
  2564. else:
  2565. self.on_fileopengerber(name=file_name)
  2566. return
  2567. # if it reached here without already returning then the app was registered with a file that it does not
  2568. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  2569. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  2570. # for arg in args_to_process:
  2571. # if 'FlatCAM.exe' in arg:
  2572. # continue
  2573. # else:
  2574. # sys.exit(2)
  2575. def set_ui_title(self, name):
  2576. """
  2577. Sets the title of the main window.
  2578. :param name: String that store the project path and project name
  2579. :return: None
  2580. """
  2581. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  2582. (self.version,
  2583. ('BETA' if self.beta else ''),
  2584. platform.architecture()[0],
  2585. self.engine,
  2586. name)
  2587. )
  2588. def on_theme_change(self, val):
  2589. settings = QSettings("Open Source", "FlatCAM")
  2590. settings.setValue('theme', val)
  2591. # This will write the setting to the platform specific storage.
  2592. del settings
  2593. self.on_app_restart()
  2594. def on_app_restart(self):
  2595. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  2596. # be left in the SySTray
  2597. try:
  2598. self.trayIcon.hide()
  2599. except Exception as e:
  2600. pass
  2601. fcTranslate.restart_program(app=self)
  2602. def defaults_read_form(self):
  2603. """
  2604. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2605. :return: None
  2606. """
  2607. for option in self.defaults_form_fields:
  2608. try:
  2609. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2610. except Exception as e:
  2611. log.debug("App.defaults_read_form() --> %s" % str(e))
  2612. def defaults_write_form(self, factor=None, fl_units=None):
  2613. """
  2614. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2615. self.defaults dictionary.
  2616. :param factor: will apply a factor to the values that written in the GUI elements
  2617. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2618. :return: None
  2619. """
  2620. for option in self.defaults:
  2621. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2622. # try:
  2623. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2624. # except KeyError:
  2625. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2626. # # TODO: Rethink this?
  2627. # pass
  2628. def defaults_write_form_field(self, field, factor=None, units=None):
  2629. """
  2630. Basically it is the worker in the self.defaults_write_form()
  2631. :param field: the GUI element in Preferences GUI to be updated
  2632. :param factor: factor to be applied to the field parameter
  2633. :param units: current FLatCAM measuring units
  2634. :return: None, it updates GUI elements
  2635. """
  2636. try:
  2637. if factor is None:
  2638. if units is None:
  2639. self.defaults_form_fields[field].set_value(self.defaults[field])
  2640. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2641. self.defaults_form_fields[field].set_value(self.defaults[field])
  2642. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2643. self.defaults_form_fields[field].set_value(self.defaults[field])
  2644. else:
  2645. if units is None:
  2646. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2647. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2648. self.defaults_form_fields[field].set_value((self.defaults[field] * factor))
  2649. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2650. self.defaults_form_fields[field].set_value((self.defaults[field] * factor))
  2651. except KeyError:
  2652. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2653. # TODO: Rethink this?
  2654. pass
  2655. except AttributeError:
  2656. log.debug(field)
  2657. def clear_pool(self):
  2658. """
  2659. Clear the multiprocessing pool and calls garbage collector.
  2660. :return: None
  2661. """
  2662. self.pool.close()
  2663. self.pool = Pool()
  2664. self.pool_recreated.emit(self.pool)
  2665. gc.collect()
  2666. def install_tools(self):
  2667. """
  2668. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2669. Instantiation of the Tools classes.
  2670. The order that the tools are installed is important as they can depend on each other install position.
  2671. :return: None
  2672. """
  2673. self.dblsidedtool = DblSidedTool(self)
  2674. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2675. self.cal_exc_tool = ToolCalibrateExcellon(self)
  2676. self.cal_exc_tool.install(icon=QtGui.QIcon('share/drill16.png'), pos=self.ui.menutool,
  2677. before=self.dblsidedtool.menuAction,
  2678. separator=False)
  2679. self.distance_tool = Distance(self)
  2680. self.distance_tool.install(icon=QtGui.QIcon('share/distance16.png'), pos=self.ui.menuedit,
  2681. before=self.ui.menueditorigin,
  2682. separator=False)
  2683. self.distance_min_tool = DistanceMin(self)
  2684. self.distance_min_tool.install(icon=QtGui.QIcon('share/distance_min16.png'), pos=self.ui.menuedit,
  2685. before=self.ui.menueditorigin,
  2686. separator=True)
  2687. self.panelize_tool = Panelize(self)
  2688. self.panelize_tool.install(icon=QtGui.QIcon('share/panelize16.png'))
  2689. self.film_tool = Film(self)
  2690. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2691. self.paste_tool = SolderPaste(self)
  2692. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2693. self.calculator_tool = ToolCalculator(self)
  2694. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator16.png'), separator=True)
  2695. self.sub_tool = ToolSub(self)
  2696. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2697. self.rules_tool = RulesCheck(self)
  2698. self.rules_tool.install(icon=QtGui.QIcon('share/rules32.png'), pos=self.ui.menutool, separator=False)
  2699. self.optimal_tool = ToolOptimal(self)
  2700. self.optimal_tool.install(icon=QtGui.QIcon('share/open_excellon32.png'), pos=self.ui.menutool, separator=True)
  2701. self.move_tool = ToolMove(self)
  2702. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2703. before=self.ui.menueditorigin, separator=True)
  2704. self.cutout_tool = CutOut(self)
  2705. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2706. before=self.sub_tool.menuAction)
  2707. self.ncclear_tool = NonCopperClear(self)
  2708. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2709. before=self.sub_tool.menuAction, separator=True)
  2710. self.paint_tool = ToolPaint(self)
  2711. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2712. before=self.sub_tool.menuAction, separator=True)
  2713. self.copperfill_tool = ToolCopperFill(self)
  2714. self.copperfill_tool.install(icon=QtGui.QIcon('share/copperfill32.png'), pos=self.ui.menutool)
  2715. self.qrcode_tool = QRCode(self)
  2716. self.qrcode_tool.install(icon=QtGui.QIcon('share/qrcode32.png'), pos=self.ui.menutool)
  2717. self.transform_tool = ToolTransform(self)
  2718. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2719. self.properties_tool = Properties(self)
  2720. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2721. self.pdf_tool = ToolPDF(self)
  2722. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2723. separator=True)
  2724. self.image_tool = ToolImage(self)
  2725. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2726. separator=True)
  2727. self.pcb_wizard_tool = PcbWizard(self)
  2728. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2729. self.log.debug("Tools are installed.")
  2730. def remove_tools(self):
  2731. """
  2732. Will remove all the actions in the Tool menu.
  2733. :return: None
  2734. """
  2735. for act in self.ui.menutool.actions():
  2736. self.ui.menutool.removeAction(act)
  2737. def init_tools(self):
  2738. """
  2739. Initialize the Tool tab in the notebook side of the central widget.
  2740. Remove the actions in the Tools menu.
  2741. Instantiate again the FlatCAM tools (plugins).
  2742. All this is required when changing the layout: standard, compact etc.
  2743. :return: None
  2744. """
  2745. log.debug("init_tools()")
  2746. # delete the data currently in the Tools Tab and the Tab itself
  2747. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2748. if widget is not None:
  2749. widget.deleteLater()
  2750. self.ui.notebook.removeTab(2)
  2751. # rebuild the Tools Tab
  2752. self.ui.tool_tab = QtWidgets.QWidget()
  2753. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2754. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2755. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2756. self.ui.tool_scroll_area = VerticalScrollArea()
  2757. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2758. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2759. # first remove all of them
  2760. self.remove_tools()
  2761. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2762. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2763. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2764. # third install all of them
  2765. self.install_tools()
  2766. self.log.debug("Tools are initialized.")
  2767. # def parse_system_fonts(self):
  2768. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2769. # 'params': []})
  2770. def connect_toolbar_signals(self):
  2771. """
  2772. Reconnect the signals to the actions in the toolbar.
  2773. This has to be done each time after the FlatCAM tools are removed/installed.
  2774. :return: None
  2775. """
  2776. # Toolbar
  2777. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2778. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2779. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2780. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2781. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2782. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2783. self.ui.replot_btn.triggered.connect(self.plot_all)
  2784. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2785. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2786. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2787. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2788. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2789. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2790. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2791. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2792. self.ui.copy_btn.triggered.connect(self.on_copy_object)
  2793. self.ui.delete_btn.triggered.connect(self.on_delete)
  2794. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  2795. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  2796. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  2797. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  2798. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2799. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2800. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2801. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2802. # Tools Toolbar Signals
  2803. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2804. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2805. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2806. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2807. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2808. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2809. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2810. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2811. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  2812. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  2813. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2814. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2815. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  2816. self.ui.copperfill_btn.triggered.connect(lambda: self.copperfill_tool.run(toggle=True))
  2817. def object2editor(self):
  2818. """
  2819. Send the current Geometry or Excellon object (if any) into the it's editor.
  2820. :return: None
  2821. """
  2822. self.report_usage("object2editor()")
  2823. # disable the objects menu as it may interfere with the Editors
  2824. self.ui.menuobjects.setDisabled(True)
  2825. edited_object = self.collection.get_active()
  2826. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2827. isinstance(edited_object, FlatCAMExcellon):
  2828. pass
  2829. else:
  2830. self.inform.emit('[WARNING_NOTCL] %s' %
  2831. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2832. return
  2833. if isinstance(edited_object, FlatCAMGeometry):
  2834. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2835. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2836. # we set the notebook to hidden
  2837. self.ui.splitter.setSizes([0, 1])
  2838. if edited_object.multigeo is True:
  2839. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  2840. if len(edited_tools) > 1:
  2841. self.inform.emit('[WARNING_NOTCL] %s' %
  2842. _("Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  2843. "is not possible.\n"
  2844. "Edit only one geometry at a time."))
  2845. # determine the tool dia of the selected tool
  2846. selected_tooldia = float(edited_object.ui.geo_tools_table.item((edited_tools[0] - 1), 1).text())
  2847. # now find the key in the edited_object.tools that has this tooldia
  2848. multi_tool = 1
  2849. for tool in edited_object.tools:
  2850. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2851. multi_tool = tool
  2852. break
  2853. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2854. else:
  2855. self.geo_editor.edit_fcgeometry(edited_object)
  2856. # set call source to the Editor we go into
  2857. self.call_source = 'geo_editor'
  2858. elif isinstance(edited_object, FlatCAMExcellon):
  2859. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2860. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2861. if self.ui.splitter.sizes()[0] == 0:
  2862. self.ui.splitter.setSizes([1, 1])
  2863. self.exc_editor.edit_fcexcellon(edited_object)
  2864. # set call source to the Editor we go into
  2865. self.call_source = 'exc_editor'
  2866. elif isinstance(edited_object, FlatCAMGerber):
  2867. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2868. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2869. if self.ui.splitter.sizes()[0] == 0:
  2870. self.ui.splitter.setSizes([1, 1])
  2871. self.grb_editor.edit_fcgerber(edited_object)
  2872. # set call source to the Editor we go into
  2873. self.call_source = 'grb_editor'
  2874. # make sure that we can't select another object while in Editor Mode:
  2875. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2876. self.ui.project_frame.setDisabled(True)
  2877. # delete any selection shape that might be active as they are not relevant in Editor
  2878. self.delete_selection_shape()
  2879. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2880. self.ui.plot_tab_area.protectTab(0)
  2881. self.inform.emit('[WARNING_NOTCL] %s' %
  2882. _("Editor is activated ..."))
  2883. self.should_we_save = True
  2884. def editor2object(self, cleanup=None):
  2885. """
  2886. Transfers the Geometry or Excellon from it's editor to the current object.
  2887. :return: None
  2888. """
  2889. self.report_usage("editor2object()")
  2890. # re-enable the objects menu that was disabled on entry in Editor mode
  2891. self.ui.menuobjects.setDisabled(False)
  2892. # do not update a geometry or excellon object unless it comes out of an editor
  2893. if self.call_source != 'app':
  2894. edited_obj = self.collection.get_active()
  2895. if cleanup is None:
  2896. msgbox = QtWidgets.QMessageBox()
  2897. msgbox.setText(_("Do you want to save the edited object?"))
  2898. msgbox.setWindowTitle(_("Close Editor"))
  2899. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2900. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2901. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2902. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2903. msgbox.setDefaultButton(bt_yes)
  2904. msgbox.exec_()
  2905. response = msgbox.clickedButton()
  2906. if response == bt_yes:
  2907. # clean the Tools Tab
  2908. self.ui.tool_scroll_area.takeWidget()
  2909. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2910. self.ui.notebook.setTabText(2, "Tool")
  2911. if isinstance(edited_obj, FlatCAMGeometry):
  2912. obj_type = "Geometry"
  2913. if cleanup is None:
  2914. self.geo_editor.update_fcgeometry(edited_obj)
  2915. self.geo_editor.update_options(edited_obj)
  2916. self.geo_editor.deactivate()
  2917. # update the geo object options so it is including the bounding box values
  2918. try:
  2919. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2920. edited_obj.options['xmin'] = xmin
  2921. edited_obj.options['ymin'] = ymin
  2922. edited_obj.options['xmax'] = xmax
  2923. edited_obj.options['ymax'] = ymax
  2924. except AttributeError as e:
  2925. self.inform.emit('[WARNING] %s' %
  2926. _("Object empty after edit."))
  2927. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2928. elif isinstance(edited_obj, FlatCAMGerber):
  2929. obj_type = "Gerber"
  2930. if cleanup is None:
  2931. self.grb_editor.update_fcgerber()
  2932. self.grb_editor.update_options(edited_obj)
  2933. self.grb_editor.deactivate_grb_editor()
  2934. # delete the old object (the source object) if it was an empty one
  2935. try:
  2936. if len(edited_obj.solid_geometry) == 0:
  2937. old_name = edited_obj.options['name']
  2938. self.collection.set_active(old_name)
  2939. self.collection.delete_active()
  2940. except TypeError:
  2941. # if the solid_geometry is a single Polygon the len() will not work
  2942. # in any case, falling here means that we have something in the solid_geometry, even if only
  2943. # a single Polygon, therefore we pass this
  2944. pass
  2945. # restore GUI to the Selected TAB
  2946. # Remove anything else in the GUI
  2947. self.ui.selected_scroll_area.takeWidget()
  2948. # Switch notebook to Selected page
  2949. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2950. elif isinstance(edited_obj, FlatCAMExcellon):
  2951. obj_type = "Excellon"
  2952. if cleanup is None:
  2953. self.exc_editor.update_fcexcellon(edited_obj)
  2954. self.exc_editor.update_options(edited_obj)
  2955. self.exc_editor.deactivate()
  2956. # delete the old object (the source object) if it was an empty one
  2957. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  2958. old_name = edited_obj.options['name']
  2959. self.collection.set_active(old_name)
  2960. self.collection.delete_active()
  2961. # restore GUI to the Selected TAB
  2962. # Remove anything else in the GUI
  2963. self.ui.tool_scroll_area.takeWidget()
  2964. # Switch notebook to Selected page
  2965. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2966. else:
  2967. self.inform.emit('[WARNING_NOTCL] %s' %
  2968. _("Select a Gerber, Geometry or Excellon Object to update."))
  2969. return
  2970. self.inform.emit('[selected] %s %s' %
  2971. (obj_type, _("is updated, returning to App...")))
  2972. elif response == bt_no:
  2973. # clean the Tools Tab
  2974. self.ui.tool_scroll_area.takeWidget()
  2975. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2976. self.ui.notebook.setTabText(2, "Tool")
  2977. if isinstance(edited_obj, FlatCAMGeometry):
  2978. self.geo_editor.deactivate()
  2979. elif isinstance(edited_obj, FlatCAMGerber):
  2980. self.grb_editor.deactivate_grb_editor()
  2981. elif isinstance(edited_obj, FlatCAMExcellon):
  2982. self.exc_editor.deactivate()
  2983. # set focus on the project tab
  2984. else:
  2985. self.inform.emit('[WARNING_NOTCL] %s' %
  2986. _("Select a Gerber, Geometry or Excellon Object to update."))
  2987. return
  2988. edited_obj.set_ui(edited_obj.ui_type())
  2989. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2990. elif response == bt_cancel:
  2991. return
  2992. else:
  2993. if isinstance(edited_obj, FlatCAMGeometry):
  2994. self.geo_editor.deactivate()
  2995. elif isinstance(edited_obj, FlatCAMGerber):
  2996. self.grb_editor.deactivate_grb_editor()
  2997. elif isinstance(edited_obj, FlatCAMExcellon):
  2998. self.exc_editor.deactivate()
  2999. else:
  3000. self.inform.emit('[WARNING_NOTCL] %s' %
  3001. _("Select a Gerber, Geometry or Excellon Object to update."))
  3002. return
  3003. # if notebook is hidden we show it
  3004. if self.ui.splitter.sizes()[0] == 0:
  3005. self.ui.splitter.setSizes([1, 1])
  3006. # restore the call_source to app
  3007. self.call_source = 'app'
  3008. edited_obj.plot()
  3009. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  3010. self.ui.plot_tab_area.protectTab(0)
  3011. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  3012. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  3013. self.ui.project_frame.setDisabled(False)
  3014. def get_last_folder(self):
  3015. """
  3016. Get the folder path from where the last file was opened.
  3017. :return: String, last opened folder path
  3018. """
  3019. return self.defaults["global_last_folder"]
  3020. def get_last_save_folder(self):
  3021. """
  3022. Get the folder path from where the last file was saved.
  3023. :return: String, last saved folder path
  3024. """
  3025. loc = self.defaults["global_last_save_folder"]
  3026. if loc is None:
  3027. loc = self.defaults["global_last_folder"]
  3028. if loc is None:
  3029. loc = os.path.dirname(__file__)
  3030. return loc
  3031. def report_usage(self, resource):
  3032. """
  3033. Increments usage counter for the given resource
  3034. in self.defaults['global_stats'].
  3035. :param resource: Name of the resource.
  3036. :return: None
  3037. """
  3038. if resource in self.defaults['global_stats']:
  3039. self.defaults['global_stats'][resource] += 1
  3040. else:
  3041. self.defaults['global_stats'][resource] = 1
  3042. def init_tcl(self):
  3043. """
  3044. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  3045. :return: None
  3046. """
  3047. if hasattr(self, 'tcl') and self.tcl is not None:
  3048. # self.tcl = None
  3049. # TODO we need to clean non default variables and procedures here
  3050. # new object cannot be used here as it will not remember values created for next passes,
  3051. # because tcl was execudted in old instance of TCL
  3052. pass
  3053. else:
  3054. self.tcl = tk.Tcl()
  3055. self.setup_shell()
  3056. self.log.debug("TCL Shell has been initialized.")
  3057. # TODO: This shouldn't be here.
  3058. class TclErrorException(Exception):
  3059. """
  3060. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  3061. """
  3062. pass
  3063. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  3064. """
  3065. Shows a message on the FlatCAM Shell
  3066. :param msg: Message to display.
  3067. :param show: Opens the shell.
  3068. :param error: Shows the message as an error.
  3069. :param warning: Shows the message as an warning.
  3070. :param success: Shows the message as an success.
  3071. :param selected: Indicate that something was selected on canvas
  3072. :return: None
  3073. """
  3074. if show:
  3075. self.ui.shell_dock.show()
  3076. try:
  3077. if error:
  3078. self.shell.append_error(msg + "\n")
  3079. elif warning:
  3080. self.shell.append_warning(msg + "\n")
  3081. elif success:
  3082. self.shell.append_success(msg + "\n")
  3083. elif selected:
  3084. self.shell.append_selected(msg + "\n")
  3085. else:
  3086. self.shell.append_output(msg + "\n")
  3087. except AttributeError:
  3088. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  3089. def raise_tcl_unknown_error(self, unknownException):
  3090. """
  3091. Raise exception if is different type than TclErrorException
  3092. this is here mainly to show unknown errors inside TCL shell console.
  3093. :param unknownException:
  3094. :return:
  3095. """
  3096. if not isinstance(unknownException, self.TclErrorException):
  3097. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  3098. else:
  3099. raise unknownException
  3100. def display_tcl_error(self, error, error_info=None):
  3101. """
  3102. Escape bracket [ with '\' otherwise there is error
  3103. "ERROR: missing close-bracket" instead of real error
  3104. :param error: it may be text or exception
  3105. :param error_info: Some informations about the error
  3106. :return: None
  3107. """
  3108. if isinstance(error, Exception):
  3109. exc_type, exc_value, exc_traceback = error_info
  3110. if not isinstance(error, self.TclErrorException):
  3111. show_trace = 1
  3112. else:
  3113. show_trace = int(self.defaults['global_verbose_error_level'])
  3114. if show_trace > 0:
  3115. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  3116. trc_formated = []
  3117. for a in reversed(trc):
  3118. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  3119. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  3120. else:
  3121. text = "%s" % error
  3122. else:
  3123. text = error
  3124. text = text.replace('[', '\\[').replace('"', '\\"')
  3125. self.tcl.eval('return -code error "%s"' % text)
  3126. def raise_tcl_error(self, text):
  3127. """
  3128. This method pass exception from python into TCL as error, so we get stacktrace and reason
  3129. :param text: text of error
  3130. :return: raise exception
  3131. """
  3132. self.display_tcl_error(text)
  3133. raise self.TclErrorException(text)
  3134. def exec_command(self, text, no_echo=False):
  3135. """
  3136. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  3137. Also handles execution in separated threads
  3138. :param text: FlatCAM TclCommand with parameters
  3139. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  3140. will create crashes of the _Expandable_Edit widget
  3141. :return: output if there was any
  3142. """
  3143. self.report_usage('exec_command')
  3144. result = self.exec_command_test(text, False, no_echo=no_echo)
  3145. # MS: added this method call so the geometry is updated once the TCL command is executed
  3146. # if no_plot is None:
  3147. # self.plot_all()
  3148. return result
  3149. def exec_command_test(self, text, reraise=True, no_echo=False):
  3150. """
  3151. Same as exec_command(...) with additional control over exceptions.
  3152. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  3153. :param text: Input command
  3154. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  3155. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  3156. will create crashes of the _Expandable_Edit widget
  3157. :return: Output from the command
  3158. """
  3159. tcl_command_string = str(text)
  3160. try:
  3161. if no_echo is False:
  3162. self.shell.open_proccessing() # Disables input box.
  3163. result = self.tcl.eval(str(tcl_command_string))
  3164. if result != 'None' and no_echo is False:
  3165. self.shell.append_output(result + '\n')
  3166. except tk.TclError as e:
  3167. # This will display more precise answer if something in TCL shell fails
  3168. result = self.tcl.eval("set errorInfo")
  3169. self.log.error("Exec command Exception: %s" % (result + '\n'))
  3170. if no_echo is False:
  3171. self.shell.append_error('ERROR: ' + result + '\n')
  3172. # Show error in console and just return or in test raise exception
  3173. if reraise:
  3174. raise e
  3175. finally:
  3176. if no_echo is False:
  3177. self.shell.close_proccessing()
  3178. pass
  3179. return result
  3180. # """
  3181. # Code below is unsused. Saved for later.
  3182. # """
  3183. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  3184. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  3185. # self.log.debug(parts)
  3186. # try:
  3187. # if parts[0] not in commands:
  3188. # self.shell.append_error("Unknown command\n")
  3189. # return
  3190. #
  3191. # #import inspect
  3192. # #inspect.getargspec(someMethod)
  3193. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  3194. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  3195. # self.shell.append_error(
  3196. # "Command %s takes %d arguments. %d given.\n" %
  3197. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  3198. # )
  3199. # return
  3200. #
  3201. # cmdfcn = commands[parts[0]]["fcn"]
  3202. # cmdconv = commands[parts[0]]["converters"]
  3203. # if len(parts) - 1 > 0:
  3204. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  3205. # else:
  3206. # retval = cmdfcn()
  3207. # retfcn = commands[parts[0]]["retfcn"]
  3208. # if retval and retfcn(retval):
  3209. # self.shell.append_output(retfcn(retval) + "\n")
  3210. #
  3211. # except Exception as e:
  3212. # #self.shell.append_error(''.join(traceback.format_exc()))
  3213. # #self.shell.append_error("?\n")
  3214. # self.shell.append_error(str(e) + "\n")
  3215. def info(self, msg):
  3216. """
  3217. Informs the user. Normally on the status bar, optionally
  3218. also on the shell.
  3219. :param msg: Text to write.
  3220. :return: None
  3221. """
  3222. # Type of message in brackets at the beginning of the message.
  3223. match = re.search("\[([^\]]+)\](.*)", msg)
  3224. if match:
  3225. level = match.group(1)
  3226. msg_ = match.group(2)
  3227. self.ui.fcinfo.set_status(str(msg_), level=level)
  3228. if level.lower() == "error":
  3229. self.shell_message(msg, error=True, show=True)
  3230. elif level.lower() == "warning":
  3231. self.shell_message(msg, warning=True, show=True)
  3232. elif level.lower() == "error_notcl":
  3233. self.shell_message(msg, error=True, show=False)
  3234. elif level.lower() == "warning_notcl":
  3235. self.shell_message(msg, warning=True, show=False)
  3236. elif level.lower() == "success":
  3237. self.shell_message(msg, success=True, show=False)
  3238. elif level.lower() == "selected":
  3239. self.shell_message(msg, selected=True, show=False)
  3240. else:
  3241. self.shell_message(msg, show=False)
  3242. else:
  3243. self.ui.fcinfo.set_status(str(msg), level="info")
  3244. # make sure that if the message is to clear the infobar with a space
  3245. # is not printed over and over on the shell
  3246. if msg != '':
  3247. self.shell_message(msg)
  3248. def restore_toolbar_view(self):
  3249. """
  3250. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  3251. was saved in the defaults dictionary.
  3252. :return: None
  3253. """
  3254. tb = self.defaults["global_toolbar_view"]
  3255. if tb & 1:
  3256. self.ui.toolbarfile.setVisible(True)
  3257. else:
  3258. self.ui.toolbarfile.setVisible(False)
  3259. if tb & 2:
  3260. self.ui.toolbargeo.setVisible(True)
  3261. else:
  3262. self.ui.toolbargeo.setVisible(False)
  3263. if tb & 4:
  3264. self.ui.toolbarview.setVisible(True)
  3265. else:
  3266. self.ui.toolbarview.setVisible(False)
  3267. if tb & 8:
  3268. self.ui.toolbartools.setVisible(True)
  3269. else:
  3270. self.ui.toolbartools.setVisible(False)
  3271. if tb & 16:
  3272. self.ui.exc_edit_toolbar.setVisible(True)
  3273. else:
  3274. self.ui.exc_edit_toolbar.setVisible(False)
  3275. if tb & 32:
  3276. self.ui.geo_edit_toolbar.setVisible(True)
  3277. else:
  3278. self.ui.geo_edit_toolbar.setVisible(False)
  3279. if tb & 64:
  3280. self.ui.grb_edit_toolbar.setVisible(True)
  3281. else:
  3282. self.ui.grb_edit_toolbar.setVisible(False)
  3283. if tb & 128:
  3284. self.ui.snap_toolbar.setVisible(True)
  3285. else:
  3286. self.ui.snap_toolbar.setVisible(False)
  3287. if tb & 256:
  3288. self.ui.toolbarshell.setVisible(True)
  3289. else:
  3290. self.ui.toolbarshell.setVisible(False)
  3291. def load_defaults(self, filename):
  3292. """
  3293. Loads the aplication's default settings from current_defaults.FlatConfig into
  3294. ``self.defaults``.
  3295. :return: None
  3296. """
  3297. try:
  3298. f = open(self.data_path + "/" + filename + ".FlatConfig")
  3299. options = f.read()
  3300. f.close()
  3301. except IOError:
  3302. self.log.error("Could not load defaults file.")
  3303. self.inform.emit('[ERROR] %s' %
  3304. _("Could not load defaults file."))
  3305. # in case the defaults file can't be loaded, show all toolbars
  3306. self.defaults["global_toolbar_view"] = 511
  3307. return
  3308. try:
  3309. defaults = json.loads(options)
  3310. except:
  3311. # in case the defaults file can't be loaded, show all toolbars
  3312. self.defaults["global_toolbar_view"] = 511
  3313. e = sys.exc_info()[0]
  3314. App.log.error(str(e))
  3315. self.inform.emit('[ERROR] %s' %
  3316. _("Failed to parse defaults file."))
  3317. return
  3318. self.defaults.update(defaults)
  3319. log.debug("FlatCAM defaults loaded from: %s" % filename)
  3320. # restore the toolbar view
  3321. self.restore_toolbar_view()
  3322. def on_import_preferences(self):
  3323. """
  3324. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  3325. ``self.defaults``.
  3326. :return: None
  3327. """
  3328. self.report_usage("on_import_preferences")
  3329. App.log.debug("on_import_preferences()")
  3330. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  3331. try:
  3332. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3333. directory=self.data_path,
  3334. filter=filter_)
  3335. except TypeError:
  3336. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3337. filter=filter_)
  3338. filename = str(filename)
  3339. if filename == "":
  3340. self.inform.emit('[WARNING_NOTCL] %s' %
  3341. _("FlatCAM preferences import cancelled."))
  3342. else:
  3343. try:
  3344. f = open(filename)
  3345. options = f.read()
  3346. f.close()
  3347. except IOError:
  3348. self.log.error("Could not load defaults file.")
  3349. self.inform.emit('[ERROR_NOTCL] %s' %
  3350. _("Could not load defaults file."))
  3351. return
  3352. try:
  3353. defaults_from_file = json.loads(options)
  3354. except Exception as e:
  3355. e = sys.exc_info()[0]
  3356. App.log.error(str(e))
  3357. self.inform.emit('[ERROR_NOTCL] %s' %
  3358. _("Failed to parse defaults file."))
  3359. return
  3360. self.defaults.update(defaults_from_file)
  3361. self.on_preferences_edited()
  3362. self.inform.emit('[success] %s: %s' %
  3363. (_("Imported Defaults from"), filename))
  3364. def on_export_preferences(self):
  3365. """
  3366. Save the defaults dictionary to a file.
  3367. :return: None
  3368. """
  3369. self.report_usage("on_export_preferences")
  3370. App.log.debug("on_export_preferences()")
  3371. defaults_file_content = None
  3372. self.date = str(datetime.today()).rpartition('.')[0]
  3373. self.date = ''.join(c for c in self.date if c not in ':-')
  3374. self.date = self.date.replace(' ', '_')
  3375. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  3376. try:
  3377. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  3378. caption=_("Export FlatCAM Preferences"),
  3379. directory=self.data_path + '/preferences_' + self.date,
  3380. filter=filter__
  3381. )
  3382. except TypeError:
  3383. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  3384. filter=filter__)
  3385. filename = str(filename)
  3386. defaults_from_file = {}
  3387. if filename == "":
  3388. self.inform.emit('[WARNING_NOTCL] %s' %
  3389. _("FlatCAM preferences export cancelled."))
  3390. return
  3391. else:
  3392. try:
  3393. f = open(filename, 'w')
  3394. defaults_file_content = f.read()
  3395. f.close()
  3396. except PermissionError:
  3397. self.inform.emit('[WARNING] %s' %
  3398. _("Permission denied, saving not possible.\n"
  3399. "Most likely another app is holding the file open and not accessible."))
  3400. return
  3401. except IOError:
  3402. App.log.debug('Creating a new preferences file ...')
  3403. f = open(filename, 'w')
  3404. json.dump({}, f)
  3405. f.close()
  3406. except:
  3407. e = sys.exc_info()[0]
  3408. App.log.error("Could not load defaults file.")
  3409. App.log.error(str(e))
  3410. self.inform.emit('[ERROR_NOTCL] %s' %
  3411. _("Could not load preferences file."))
  3412. return
  3413. try:
  3414. defaults_from_file = json.loads(defaults_file_content)
  3415. except:
  3416. App.log.warning("Trying to read an empty Preferences file. Continue.")
  3417. # Update options
  3418. self.defaults_read_form()
  3419. defaults_from_file.update(self.defaults)
  3420. self.propagate_defaults(silent=True)
  3421. # Save update options
  3422. try:
  3423. f = open(filename, "w")
  3424. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  3425. f.close()
  3426. except:
  3427. self.inform.emit('[ERROR_NOTCL] %s' %
  3428. _("Failed to write defaults to file."))
  3429. return
  3430. if self.defaults["global_open_style"] is False:
  3431. self.file_opened.emit("preferences", filename)
  3432. self.file_saved.emit("preferences", filename)
  3433. self.inform.emit('[success] %s: %s' %
  3434. (_("Exported preferences to"), filename))
  3435. def on_preferences_open_folder(self):
  3436. """
  3437. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  3438. :return: None
  3439. """
  3440. self.report_usage("on_preferences_open_folder()")
  3441. if sys.platform == 'win32':
  3442. subprocess.Popen('explorer %s' % self.data_path)
  3443. elif sys.platform == 'darwin':
  3444. os.system('open "%s"' % self.data_path)
  3445. else:
  3446. subprocess.Popen(['xdg-open', self.data_path])
  3447. self.inform.emit('[success] %s' %
  3448. _("FlatCAM Preferences Folder opened."))
  3449. def save_geometry(self, x, y, width, height, notebook_width):
  3450. """
  3451. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  3452. launch of the application.
  3453. :param x: X position of the main window
  3454. :param y: Y position of the main window
  3455. :param width: width of the main window
  3456. :param height: height of the main window
  3457. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  3458. :return: None
  3459. """
  3460. self.defaults["global_def_win_x"] = x
  3461. self.defaults["global_def_win_y"] = y
  3462. self.defaults["global_def_win_w"] = width
  3463. self.defaults["global_def_win_h"] = height
  3464. self.defaults["global_def_notebook_width"] = notebook_width
  3465. self.save_defaults()
  3466. def restore_main_win_geom(self):
  3467. try:
  3468. self.ui.setGeometry(self.defaults["global_def_win_x"],
  3469. self.defaults["global_def_win_y"],
  3470. self.defaults["global_def_win_w"],
  3471. self.defaults["global_def_win_h"])
  3472. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  3473. except KeyError as e:
  3474. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  3475. def message_dialog(self, title, message, kind="info"):
  3476. """
  3477. Builds and show a custom QMessageBox to be used in FlatCAM.
  3478. :param title: title of the QMessageBox
  3479. :param message: message to be displayed
  3480. :param kind: type of QMessageBox; will display a specific icon.
  3481. :return:
  3482. """
  3483. icon = {"info": QtWidgets.QMessageBox.Information,
  3484. "warning": QtWidgets.QMessageBox.Warning,
  3485. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3486. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  3487. dlg.setText(message)
  3488. dlg.exec_()
  3489. def register_recent(self, kind, filename):
  3490. """
  3491. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  3492. dictionary.
  3493. :param kind: type of file that was opened
  3494. :param filename: the path and file name for the file that was opened
  3495. :return:
  3496. """
  3497. self.log.debug("register_recent()")
  3498. self.log.debug(" %s" % kind)
  3499. self.log.debug(" %s" % filename)
  3500. record = {'kind': str(kind), 'filename': str(filename)}
  3501. if record in self.recent:
  3502. return
  3503. if record in self.recent_projects:
  3504. return
  3505. if record['kind'] == 'project':
  3506. self.recent_projects.insert(0, record)
  3507. else:
  3508. self.recent.insert(0, record)
  3509. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3510. self.recent.pop()
  3511. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3512. self.recent_projects.pop()
  3513. try:
  3514. f = open(self.data_path + '/recent.json', 'w')
  3515. except IOError:
  3516. App.log.error("Failed to open recent items file for writing.")
  3517. self.inform.emit('[ERROR_NOTCL] %s' %
  3518. _('Failed to open recent files file for writing.'))
  3519. return
  3520. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3521. f.close()
  3522. try:
  3523. fp = open(self.data_path + '/recent_projects.json', 'w')
  3524. except IOError:
  3525. App.log.error("Failed to open recent items file for writing.")
  3526. self.inform.emit('[ERROR_NOTCL] %s' %
  3527. _('Failed to open recent projects file for writing.'))
  3528. return
  3529. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3530. fp.close()
  3531. # Re-build the recent items menu
  3532. self.setup_recent_items()
  3533. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3534. """
  3535. Creates a new specialized FlatCAMObj and attaches it to the application,
  3536. this is, updates the GUI accordingly, any other records and plots it.
  3537. This method is thread-safe.
  3538. Notes:
  3539. * If the name is in use, the self.collection will modify it
  3540. when appending it to the collection. There is no need to handle
  3541. name conflicts here.
  3542. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3543. :type kind: str
  3544. :param name: Name for the object.
  3545. :type name: str
  3546. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3547. The function is called with 2 parameters: the new object and the App instance.
  3548. :type initialize: function
  3549. :param active:
  3550. :param fit:
  3551. :param plot: If to plot the resulting object
  3552. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3553. self.colleaction
  3554. :return: None
  3555. :rtype: None
  3556. """
  3557. App.log.debug("new_object()")
  3558. obj_plot = plot
  3559. obj_autoselected = autoselected
  3560. t0 = time.time() # Debug
  3561. # ## Create object
  3562. classdict = {
  3563. "gerber": FlatCAMGerber,
  3564. "excellon": FlatCAMExcellon,
  3565. "cncjob": FlatCAMCNCjob,
  3566. "geometry": FlatCAMGeometry,
  3567. "script": FlatCAMScript,
  3568. "document": FlatCAMDocument
  3569. }
  3570. App.log.debug("Calling object constructor...")
  3571. obj = classdict[kind](name)
  3572. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3573. # Set options from "Project options" form
  3574. self.options_read_form()
  3575. # IMPORTANT
  3576. # The key names in defaults and options dictionary's are not random:
  3577. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3578. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  3579. # the options from project options form into the self.options. After that, below, depending on the type of
  3580. # object that is created, it will strip the name of the object and the underline (if the original key was
  3581. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3582. # "toolchange"
  3583. for option in self.options:
  3584. if option.find(kind + "_") == 0:
  3585. oname = option[len(kind) + 1:]
  3586. obj.options[oname] = self.options[option]
  3587. obj.isHovering = False
  3588. obj.notHovering = True
  3589. # Initialize as per user request
  3590. # User must take care to implement initialize
  3591. # in a thread-safe way as is is likely that we
  3592. # have been invoked in a separate thread.
  3593. t1 = time.time()
  3594. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3595. try:
  3596. return_value = initialize(obj, self)
  3597. except Exception as e:
  3598. msg = '[ERROR_NOTCL] %s' % \
  3599. _("An internal error has ocurred. See shell.\n")
  3600. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3601. msg += traceback.format_exc()
  3602. self.inform.emit(msg)
  3603. # if str(e) == "Empty Geometry":
  3604. # self.inform.emit("[ERROR_NOTCL] )
  3605. # else:
  3606. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  3607. return "fail"
  3608. t2 = time.time()
  3609. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3610. if return_value == 'fail':
  3611. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3612. return "fail"
  3613. # Check units and convert if necessary
  3614. # This condition CAN be true because initialize() can change obj.units
  3615. if self.options["units"].upper() != obj.units.upper():
  3616. self.inform.emit('%s: %s' %
  3617. (_("Converting units to "), self.options["units"]))
  3618. obj.convert_units(self.options["units"])
  3619. t3 = time.time()
  3620. self.log.debug("%f seconds converting units." % (t3 - t2))
  3621. # Create the bounding box for the object and then add the results to the obj.options
  3622. # But not for Scripts or for Documents
  3623. if kind != 'document' and kind != 'script':
  3624. try:
  3625. xmin, ymin, xmax, ymax = obj.bounds()
  3626. obj.options['xmin'] = xmin
  3627. obj.options['ymin'] = ymin
  3628. obj.options['xmax'] = xmax
  3629. obj.options['ymax'] = ymax
  3630. except Exception as e:
  3631. log.warning("The object has no bounds properties. %s" % str(e))
  3632. return "fail"
  3633. # update the KeyWords list with the name of the file
  3634. self.myKeywords.append(obj.options['name'])
  3635. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3636. # Move the object to the main thread and let the app know that it is available.
  3637. obj.moveToThread(self.main_thread)
  3638. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3639. return obj
  3640. def new_excellon_object(self):
  3641. """
  3642. Creates a new, blank Excellon object.
  3643. :return: None
  3644. """
  3645. self.report_usage("new_excellon_object()")
  3646. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3647. def new_geometry_object(self):
  3648. """
  3649. Creates a new, blank and single-tool Geometry object.
  3650. :return: None
  3651. """
  3652. self.report_usage("new_geometry_object()")
  3653. def initialize(obj, self):
  3654. obj.multitool = False
  3655. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3656. def new_gerber_object(self):
  3657. """
  3658. Creates a new, blank Gerber object.
  3659. :return: None
  3660. """
  3661. self.report_usage("new_gerber_object()")
  3662. def initialize(grb_obj, self):
  3663. grb_obj.multitool = False
  3664. grb_obj.source_file = []
  3665. grb_obj.multigeo = False
  3666. grb_obj.follow = False
  3667. grb_obj.apertures = {}
  3668. grb_obj.solid_geometry = []
  3669. try:
  3670. grb_obj.options['xmin'] = 0
  3671. grb_obj.options['ymin'] = 0
  3672. grb_obj.options['xmax'] = 0
  3673. grb_obj.options['ymax'] = 0
  3674. except KeyError:
  3675. pass
  3676. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3677. def new_script_object(self, name=None, text=None):
  3678. """
  3679. Creates a new, blank TCL Script object.
  3680. :param name: a name for the new object
  3681. :return: None
  3682. """
  3683. self.report_usage("new_script_object()")
  3684. if text is not None:
  3685. new_source_file = text
  3686. else:
  3687. new_source_file = _(
  3688. "#\n"
  3689. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  3690. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  3691. "#\n\n"
  3692. "# FlatCAM commands list:\n"
  3693. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, "
  3694. "ClearCopper,\n"
  3695. "# Cncjob, Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, "
  3696. "GetNames,\n"
  3697. "# GetSys, ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillDrills,\n"
  3698. "# MillSlots, Mirror, New, NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"
  3699. "# Options, Paint, Panelize, Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, "
  3700. "SubtractPoly,\n"
  3701. "# SubtractRectangle, Version, WriteGCode\n"
  3702. "#\n\n"
  3703. )
  3704. def initialize(obj, self):
  3705. obj.source_file = deepcopy(new_source_file)
  3706. if name is None:
  3707. outname = 'new_script'
  3708. else:
  3709. outname = name
  3710. self.new_object('script', outname, initialize, plot=False)
  3711. def new_document_object(self):
  3712. """
  3713. Creates a new, blank Document object.
  3714. :return: None
  3715. """
  3716. self.report_usage("new_document_object()")
  3717. def initialize(obj, self):
  3718. obj.source_file = ""
  3719. self.new_object('document', 'new_document', initialize, plot=False)
  3720. def on_object_created(self, obj, plot, autoselect):
  3721. """
  3722. Event callback for object creation.
  3723. It will add the new object to the collection. After that it will plot the object in a threaded way
  3724. :param obj: The newly created FlatCAM object.
  3725. :param plot: if the newly create object t obe plotted
  3726. :param autoselect: if the newly created object to be autoselected after creation
  3727. :return: None
  3728. """
  3729. t0 = time.time() # DEBUG
  3730. self.log.debug("on_object_created()")
  3731. # The Collection might change the name if there is a collision
  3732. self.collection.append(obj)
  3733. # after adding the object to the collection always update the list of objects that are in the collection
  3734. self.all_objects_list = self.collection.get_list()
  3735. # self.inform.emit('[selected] %s created & selected: %s' %
  3736. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3737. if obj.kind == 'gerber':
  3738. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3739. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3740. elif obj.kind == 'excellon':
  3741. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3742. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3743. elif obj.kind == 'cncjob':
  3744. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3745. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3746. elif obj.kind == 'geometry':
  3747. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3748. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3749. elif obj.kind == 'script':
  3750. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3751. kind=obj.kind.capitalize(), color='orange', name=str(obj.options['name'])))
  3752. elif obj.kind == 'document':
  3753. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3754. kind=obj.kind.capitalize(), color='darkCyan', name=str(obj.options['name'])))
  3755. # update the SHELL auto-completer model with the name of the new object
  3756. self.shell._edit.set_model_data(self.myKeywords)
  3757. if autoselect:
  3758. # select the just opened object but deselect the previous ones
  3759. self.collection.set_all_inactive()
  3760. self.collection.set_active(obj.options["name"])
  3761. else:
  3762. self.collection.set_all_inactive()
  3763. # here it is done the object plotting
  3764. def worker_task(t_obj):
  3765. with self.proc_container.new(_("Plotting")):
  3766. if isinstance(t_obj, FlatCAMCNCjob):
  3767. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3768. else:
  3769. t_obj.plot()
  3770. t1 = time.time() # DEBUG
  3771. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3772. self.object_plotted.emit(t_obj)
  3773. # Send to worker
  3774. # self.worker.add_task(worker_task, [self])
  3775. if plot is True:
  3776. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3777. def on_object_changed(self, obj):
  3778. """
  3779. Called whenever the geometry of the object was changed in some way.
  3780. This require the update of it's bounding values so it can be the selected on canvas.
  3781. Update the bounding box data from obj.options
  3782. :param obj: the object that was changed
  3783. :return: None
  3784. """
  3785. xmin, ymin, xmax, ymax = obj.bounds()
  3786. obj.options['xmin'] = xmin
  3787. obj.options['ymin'] = ymin
  3788. obj.options['xmax'] = xmax
  3789. obj.options['ymax'] = ymax
  3790. log.debug("Object changed, updating the bounding box data on self.options")
  3791. # delete the old selection shape
  3792. self.delete_selection_shape()
  3793. self.should_we_save = True
  3794. def on_object_plotted(self, obj):
  3795. """
  3796. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3797. :param obj: object to be fit into view
  3798. :return: None
  3799. """
  3800. self.on_zoom_fit(None)
  3801. def options_read_form(self):
  3802. """
  3803. Same as it's equivalent from the defaults.
  3804. self.options use to store the preferences per project. No longer used.
  3805. :return: None
  3806. """
  3807. for option in self.options_form_fields:
  3808. self.options[option] = self.options_form_fields[option].get_value()
  3809. def options_write_form(self):
  3810. """
  3811. Same as it's equivalent from the defaults.
  3812. self.options use to store the preferences per project. No longer used.
  3813. :return: None
  3814. """
  3815. for option in self.options:
  3816. self.options_write_form_field(option)
  3817. def options_write_form_field(self, field):
  3818. """
  3819. Same as it's equivalent from the defaults.
  3820. self.options use to store the preferences per project. No longer used.
  3821. :return: None
  3822. """
  3823. try:
  3824. self.options_form_fields[field].set_value(self.options[field])
  3825. except KeyError:
  3826. # Changed from error to debug. This allows to have data stored
  3827. # which is not user-editable.
  3828. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  3829. pass
  3830. def on_about(self):
  3831. """
  3832. Displays the "about" dialog found in the Menu --> Help.
  3833. :return: None
  3834. """
  3835. self.report_usage("on_about")
  3836. version = self.version
  3837. version_date = self.version_date
  3838. beta = self.beta
  3839. class AboutDialog(QtWidgets.QDialog):
  3840. def __init__(self, parent=None):
  3841. QtWidgets.QDialog.__init__(self, parent)
  3842. # Icon and title
  3843. self.setWindowIcon(parent.app_icon)
  3844. self.setWindowTitle(_("About FlatCAM"))
  3845. self.resize(600, 200)
  3846. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3847. # self.setStyleSheet(
  3848. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3849. # "background-attachment: fixed"
  3850. # )
  3851. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3852. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3853. # palette = QtGui.QPalette()
  3854. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3855. # self.setPalette(palette)
  3856. logo = QtWidgets.QLabel()
  3857. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3858. title = QtWidgets.QLabel(
  3859. "<font size=8><B>FlatCAM</B></font><BR>"
  3860. "{title}<BR>"
  3861. "<BR>"
  3862. "<BR>"
  3863. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3864. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3865. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3866. "<B>{issue}</B></a><BR>".format(
  3867. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3868. devel=_("Development"),
  3869. down=_("DOWNLOAD"),
  3870. issue=_("Issue tracker"))
  3871. )
  3872. title.setOpenExternalLinks(True)
  3873. closebtn = QtWidgets.QPushButton(_("Close"))
  3874. tab_widget = QtWidgets.QTabWidget()
  3875. description_label = QtWidgets.QLabel(
  3876. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3877. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3878. version=version,
  3879. beta=('BETA' if beta else ''),
  3880. date=version_date,
  3881. arch=platform.architecture()[0])
  3882. )
  3883. description_label.setOpenExternalLinks(True)
  3884. lic_lbl_header = QtWidgets.QLabel(
  3885. '%s:<br>%s<br>' % (
  3886. _('Licensed under the MIT license'),
  3887. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  3888. "http://www.opensource.org/licenses/mit-license.php</a>"
  3889. )
  3890. )
  3891. lic_lbl_header.setOpenExternalLinks(True)
  3892. lic_lbl_body = QtWidgets.QLabel(
  3893. _(
  3894. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3895. 'of this software and associated documentation files (the "Software"), to deal\n'
  3896. 'in the Software without restriction, including without limitation the rights\n'
  3897. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3898. 'copies of the Software, and to permit persons to whom the Software is\n'
  3899. 'furnished to do so, subject to the following conditions:\n\n'
  3900. 'The above copyright notice and this permission notice shall be included in\n'
  3901. 'all copies or substantial portions of the Software.\n\n'
  3902. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3903. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3904. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3905. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3906. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3907. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3908. 'THE SOFTWARE.'
  3909. )
  3910. )
  3911. attributions_label = QtWidgets.QLabel(
  3912. _(
  3913. 'Some of the icons used are from the following sources:<br>'
  3914. '<div>Icons made by <a href="https://www.flaticon.com/authors/freepik" '
  3915. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  3916. 'title="Flaticon">www.flaticon.com</a></div>'
  3917. 'Icons by <a target="_blank" href="https://icons8.com">Icons8</a>'
  3918. )
  3919. )
  3920. # layouts
  3921. layout1 = QtWidgets.QVBoxLayout()
  3922. layout1_1 = QtWidgets.QHBoxLayout()
  3923. layout1_2 = QtWidgets.QHBoxLayout()
  3924. layout2 = QtWidgets.QHBoxLayout()
  3925. layout3 = QtWidgets.QHBoxLayout()
  3926. self.setLayout(layout1)
  3927. layout1.addLayout(layout1_1)
  3928. layout1.addLayout(layout1_2)
  3929. layout1.addLayout(layout2)
  3930. layout1.addLayout(layout3)
  3931. layout1_1.addStretch()
  3932. layout1_1.addWidget(description_label)
  3933. layout1_2.addWidget(tab_widget)
  3934. self.splash_tab = QtWidgets.QWidget()
  3935. self.splash_tab.setObjectName("splash_about")
  3936. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3937. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3938. tab_widget.addTab(self.splash_tab, _("Splash"))
  3939. self.programmmers_tab = QtWidgets.QWidget()
  3940. self.programmmers_tab.setObjectName("programmers_about")
  3941. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3942. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3943. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3944. self.translators_tab = QtWidgets.QWidget()
  3945. self.translators_tab.setObjectName("translators_about")
  3946. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3947. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3948. tab_widget.addTab(self.translators_tab, _("Translators"))
  3949. self.license_tab = QtWidgets.QWidget()
  3950. self.license_tab.setObjectName("license_about")
  3951. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3952. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3953. tab_widget.addTab(self.license_tab, _("License"))
  3954. self.attributions_tab = QtWidgets.QWidget()
  3955. self.attributions_tab.setObjectName("attributions_about")
  3956. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  3957. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  3958. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  3959. self.splash_tab_layout.addWidget(logo, stretch=0)
  3960. self.splash_tab_layout.addWidget(title, stretch=1)
  3961. pal = QtGui.QPalette()
  3962. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3963. self.prog_grid_lay = QtWidgets.QGridLayout()
  3964. self.prog_grid_lay.setHorizontalSpacing(20)
  3965. self.prog_grid_lay.setColumnStretch(0, 0)
  3966. self.prog_grid_lay.setColumnStretch(2, 1)
  3967. prog_widget = QtWidgets.QWidget()
  3968. prog_widget.setLayout(self.prog_grid_lay)
  3969. prog_scroll = QtWidgets.QScrollArea()
  3970. prog_scroll.setWidget(prog_widget)
  3971. prog_scroll.setWidgetResizable(True)
  3972. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3973. prog_scroll.setPalette(pal)
  3974. self.programmmers_tab_layout.addWidget(prog_scroll)
  3975. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  3976. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  3977. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3978. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  3979. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Program Author"), 1, 1)
  3980. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  3981. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  3982. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  3983. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  3984. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  3985. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  3986. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  3987. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 6, 0)
  3988. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  3989. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  3990. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  3991. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  3992. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 11, 0)
  3993. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  3994. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  3995. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 14, 0)
  3996. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 12, 0)
  3997. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 15, 0)
  3998. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 16, 0)
  3999. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 17, 0)
  4000. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 18, 0)
  4001. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 19, 0)
  4002. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 20, 0)
  4003. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 21, 0)
  4004. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 22, 0)
  4005. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 23, 0)
  4006. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 24, 0)
  4007. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 25, 0)
  4008. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 26, 0)
  4009. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 27, 0)
  4010. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 28, 0)
  4011. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 29, 0)
  4012. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 30, 0)
  4013. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 31, 0)
  4014. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 32, 0)
  4015. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 33, 0)
  4016. self.translator_grid_lay = QtWidgets.QGridLayout()
  4017. self.translator_grid_lay.setColumnStretch(0, 0)
  4018. self.translator_grid_lay.setColumnStretch(1, 0)
  4019. self.translator_grid_lay.setColumnStretch(2, 1)
  4020. self.translator_grid_lay.setColumnStretch(3, 0)
  4021. # trans_widget = QtWidgets.QWidget()
  4022. # trans_widget.setLayout(self.translator_grid_lay)
  4023. # self.translators_tab_layout.addWidget(trans_widget)
  4024. # self.translators_tab_layout.addStretch()
  4025. trans_widget = QtWidgets.QWidget()
  4026. trans_widget.setLayout(self.translator_grid_lay)
  4027. trans_scroll = QtWidgets.QScrollArea()
  4028. trans_scroll.setWidget(trans_widget)
  4029. trans_scroll.setWidgetResizable(True)
  4030. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  4031. trans_scroll.setPalette(pal)
  4032. self.translators_tab_layout.addWidget(trans_scroll)
  4033. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  4034. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  4035. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  4036. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  4037. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  4038. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  4039. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  4040. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  4041. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 2, 1)
  4042. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "(Google-Translation)"), 2, 2)
  4043. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  4044. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  4045. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 3, 1)
  4046. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt"), 3, 2)
  4047. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  4048. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  4049. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  4050. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 3)
  4051. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  4052. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  4053. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 3)
  4054. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  4055. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  4056. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "(Google-Translation)"), 6, 2)
  4057. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 3)
  4058. self.translator_grid_lay.setColumnStretch(0, 0)
  4059. self.translators_tab_layout.addStretch()
  4060. self.license_tab_layout.addWidget(lic_lbl_header)
  4061. self.license_tab_layout.addWidget(lic_lbl_body)
  4062. self.license_tab_layout.addStretch()
  4063. self.attributions_tab_layout.addWidget(attributions_label)
  4064. self.attributions_tab_layout.addStretch()
  4065. layout3.addStretch()
  4066. layout3.addWidget(closebtn)
  4067. closebtn.clicked.connect(self.accept)
  4068. AboutDialog(self.ui).exec_()
  4069. def install_bookmarks(self, book_dict=None):
  4070. """
  4071. Install the bookmarks actions in the Help menu -> Bookmarks
  4072. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  4073. :return: None
  4074. """
  4075. if book_dict is None:
  4076. self.defaults["global_bookmarks"].update(
  4077. {
  4078. '1': ['FlatCAM', "http://flatcam.org"],
  4079. '2': ['Backup Site', ""]
  4080. }
  4081. )
  4082. else:
  4083. self.defaults["global_bookmarks"].clear()
  4084. self.defaults["global_bookmarks"].update(book_dict)
  4085. # first try to disconnect if somehow they get connected from elsewhere
  4086. for act in self.ui.menuhelp_bookmarks.actions():
  4087. try:
  4088. act.triggered.disconnect()
  4089. except TypeError:
  4090. pass
  4091. # clear all actions except the last one who is the Bookmark manager
  4092. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  4093. pass
  4094. else:
  4095. self.ui.menuhelp_bookmarks.removeAction(act)
  4096. bm_limit = int(self.defaults["global_bookmarks_limit"])
  4097. if self.defaults["global_bookmarks"]:
  4098. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  4099. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  4100. # the JSON is first making the keys as strings (therefore I have to use strings too
  4101. # or do the conversion :(
  4102. # )
  4103. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  4104. # the '10' entry jsut after '1' therefore ordering as strings
  4105. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  4106. key=lambda x: int(x[0]))
  4107. for entry, bookmark in sorted_bookmarks:
  4108. title = bookmark[0]
  4109. weblink = bookmark[1]
  4110. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  4111. act.setText(title)
  4112. act.setIcon(QtGui.QIcon('share/link16.png'))
  4113. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  4114. if title == 'Backup Site' and weblink == "":
  4115. act.triggered.connect(self.on_backup_site)
  4116. else:
  4117. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  4118. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  4119. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  4120. def on_bookmarks_manager(self):
  4121. """
  4122. Adds the bookmark manager in a Tab in Plot Area
  4123. :return:
  4124. """
  4125. for idx in range(self.ui.plot_tab_area.count()):
  4126. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  4127. # there can be only one instance of Bookmark Manager at one time
  4128. return
  4129. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  4130. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  4131. # add the tab if it was closed
  4132. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  4133. # delete the absolute and relative position and messages in the infobar
  4134. self.ui.position_label.setText("")
  4135. self.ui.rel_position_label.setText("")
  4136. # Switch plot_area to preferences page
  4137. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  4138. def on_backup_site(self):
  4139. msgbox = QtWidgets.QMessageBox()
  4140. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  4141. "1. FlatCAM.org website is down\n"
  4142. "2. Someone forked FlatCAM project and wants to point\n"
  4143. "to his own website\n\n"
  4144. "If you can't get any informations about FlatCAM beta\n"
  4145. "use the YouTube channel link from the Help menu."))
  4146. msgbox.setWindowTitle(_("Alternative website"))
  4147. msgbox.setWindowIcon(QtGui.QIcon('share/globe16.png'))
  4148. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  4149. msgbox.setDefaultButton(bt_yes)
  4150. msgbox.exec_()
  4151. # response = msgbox.clickedButton()
  4152. def on_file_savedefaults(self):
  4153. """
  4154. Callback for menu item File->Save Defaults. Saves application default options
  4155. ``self.defaults`` to current_defaults.FlatConfig.
  4156. :return: None
  4157. """
  4158. self.save_defaults()
  4159. # def on_app_exit(self):
  4160. # self.report_usage("on_app_exit()")
  4161. #
  4162. # if self.collection.get_list():
  4163. # msgbox = QtWidgets.QMessageBox()
  4164. # # msgbox.setText("<B>Save changes ...</B>")
  4165. # msgbox.setText("There are files/objects opened in FlatCAM. "
  4166. # "\n"
  4167. # "Do you want to Save the project?")
  4168. # msgbox.setWindowTitle("Save changes")
  4169. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4170. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  4171. # QtWidgets.QMessageBox.Cancel)
  4172. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  4173. #
  4174. # response = msgbox.exec_()
  4175. #
  4176. # if response == QtWidgets.QMessageBox.Yes:
  4177. # self.on_file_saveprojectas(thread=False)
  4178. # elif response == QtWidgets.QMessageBox.Cancel:
  4179. # return
  4180. # self.save_defaults()
  4181. # else:
  4182. # self.save_defaults()
  4183. # log.debug("Application defaults saved ... Exit event.")
  4184. # QtWidgets.qApp.quit()
  4185. def save_defaults(self, silent=False, data_path=None, first_time=False):
  4186. """
  4187. Saves application default options
  4188. ``self.defaults`` to current_defaults.FlatConfig file.
  4189. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  4190. used at the next launch of the application.
  4191. :param silent: whether to display a message in status bar or not; boolean
  4192. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  4193. When the application is portable it should be a mobile location.
  4194. :return: None
  4195. """
  4196. self.report_usage("save_defaults")
  4197. if data_path is None:
  4198. data_path = self.data_path
  4199. # Read options from file
  4200. try:
  4201. f = open(data_path + "/current_defaults.FlatConfig")
  4202. defaults_file_content = f.read()
  4203. f.close()
  4204. except:
  4205. e = sys.exc_info()[0]
  4206. App.log.error("Could not load defaults file.")
  4207. App.log.error(str(e))
  4208. self.inform.emit('[ERROR_NOTCL] %s' %
  4209. _("Could not load defaults file."))
  4210. return
  4211. try:
  4212. defaults = json.loads(defaults_file_content)
  4213. except:
  4214. e = sys.exc_info()[0]
  4215. App.log.error("Failed to parse defaults file.")
  4216. App.log.error(str(e))
  4217. self.inform.emit('[ERROR_NOTCL] %s' %
  4218. _("Failed to parse defaults file."))
  4219. return
  4220. # Update options
  4221. self.defaults_read_form()
  4222. defaults.update(self.defaults)
  4223. self.propagate_defaults(silent=True)
  4224. # Save the toolbar view
  4225. tb_status = 0
  4226. if self.ui.toolbarfile.isVisible():
  4227. tb_status += 1
  4228. if self.ui.toolbargeo.isVisible():
  4229. tb_status += 2
  4230. if self.ui.toolbarview.isVisible():
  4231. tb_status += 4
  4232. if self.ui.toolbartools.isVisible():
  4233. tb_status += 8
  4234. if self.ui.exc_edit_toolbar.isVisible():
  4235. tb_status += 16
  4236. if self.ui.geo_edit_toolbar.isVisible():
  4237. tb_status += 32
  4238. if self.ui.grb_edit_toolbar.isVisible():
  4239. tb_status += 64
  4240. if self.ui.snap_toolbar.isVisible():
  4241. tb_status += 128
  4242. if self.ui.toolbarshell.isVisible():
  4243. tb_status += 256
  4244. if first_time is False:
  4245. self.defaults["global_toolbar_view"] = tb_status
  4246. # Save update options
  4247. try:
  4248. f = open(data_path + "/current_defaults.FlatConfig", "w")
  4249. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  4250. f.close()
  4251. except Exception as e:
  4252. log.debug("App.save_defaults() --> %s" % str(e))
  4253. self.inform.emit(f'[ERROR_NOTCL] {_("Failed to write defaults to file.")}')
  4254. return
  4255. if not silent:
  4256. self.inform.emit(f'[success] {_("Preferences saved.")}')
  4257. def save_factory_defaults(self, silent_message=False, data_path=None):
  4258. """
  4259. Saves application factory default options
  4260. ``self.defaults`` to factory_defaults.FlatConfig.
  4261. It's a one time job done just after the first install.
  4262. :param silent_message: whether to display a message in status bar or not; boolean
  4263. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  4264. When the application is portable it should be a mobile location.
  4265. :return: None
  4266. """
  4267. self.report_usage("save_factory_defaults")
  4268. if data_path is None:
  4269. data_path = self.data_path
  4270. # Read options from file
  4271. try:
  4272. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  4273. factory_defaults_file_content = f_f_def.read()
  4274. f_f_def.close()
  4275. except:
  4276. e = sys.exc_info()[0]
  4277. App.log.error("Could not load factory defaults file.")
  4278. App.log.error(str(e))
  4279. self.inform.emit(f'[ERROR_NOTCL] {_("Could not load factory defaults file.")}')
  4280. return
  4281. try:
  4282. factory_defaults = json.loads(factory_defaults_file_content)
  4283. except:
  4284. e = sys.exc_info()[0]
  4285. App.log.error("Failed to parse factory defaults file.")
  4286. App.log.error(str(e))
  4287. self.inform.emit(f'[ERROR_NOTCL] {_("Failed to parse factory defaults file.")}')
  4288. return
  4289. # Update options
  4290. self.defaults_read_form()
  4291. factory_defaults.update(self.defaults)
  4292. self.propagate_defaults(silent=True)
  4293. # Save update options
  4294. try:
  4295. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  4296. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  4297. f_f_def_s.close()
  4298. except Exception as e:
  4299. log.debug(f"App.save_factory_default() save update --> {str(e)}")
  4300. self.inform.emit(f'[ERROR_NOTCL] {_("Failed to write factory defaults to file.")}')
  4301. return
  4302. if silent_message is False:
  4303. self.inform.emit(f'{_("Factory defaults saved.")}')
  4304. def final_save(self):
  4305. """
  4306. Callback for doing a preferences save to file whenever the application is about to quit.
  4307. If the project has changes, it will ask the user to save the project.
  4308. :return: None
  4309. """
  4310. if self.save_in_progress:
  4311. self.inform.emit(f'[WARNING_NOTCL] {_("Application is saving the project. Please wait ...")}')
  4312. return
  4313. if self.should_we_save and self.collection.get_list():
  4314. msgbox = QtWidgets.QMessageBox()
  4315. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  4316. "\n"
  4317. "Do you want to Save the project?"))
  4318. msgbox.setWindowTitle(_("Save changes"))
  4319. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4320. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4321. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4322. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4323. msgbox.setDefaultButton(bt_yes)
  4324. msgbox.exec_()
  4325. response = msgbox.clickedButton()
  4326. if response == bt_yes:
  4327. try:
  4328. self.trayIcon.hide()
  4329. except:
  4330. pass
  4331. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  4332. elif response == bt_no:
  4333. try:
  4334. self.trayIcon.hide()
  4335. except:
  4336. pass
  4337. self.quit_application()
  4338. elif response == bt_cancel:
  4339. return
  4340. else:
  4341. try:
  4342. self.trayIcon.hide()
  4343. except:
  4344. pass
  4345. self.quit_application()
  4346. def quit_application(self):
  4347. """
  4348. Called (as a pyslot or not) when the application is quit.
  4349. :return: None
  4350. """
  4351. self.save_defaults()
  4352. log.debug("App.final_save() --> App Defaults saved.")
  4353. if self.cmd_line_headless != 1:
  4354. # save app state to file
  4355. settings = QSettings("Open Source", "FlatCAM")
  4356. settings.setValue('saved_gui_state', self.ui.saveState())
  4357. settings.setValue('maximized_gui', self.ui.isMaximized())
  4358. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  4359. settings.setValue(
  4360. 'notebook_font_size',
  4361. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  4362. )
  4363. settings.setValue('axis_font_size',
  4364. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value())
  4365. settings.setValue(
  4366. 'textbox_font_size',
  4367. self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  4368. )
  4369. settings.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  4370. # This will write the setting to the platform specific storage.
  4371. del settings
  4372. log.debug("App.final_save() --> App UI state saved.")
  4373. QtWidgets.qApp.quit()
  4374. def on_portable_checked(self, state):
  4375. """
  4376. Callback called when the checkbox in Preferences GUI is checked.
  4377. It will set the application as portable by creating the preferences and recent files in the
  4378. 'config' folder found in the FlatCAM installation folder.
  4379. :param state: boolean, the state of the checkbox when clicked/checked
  4380. :return:
  4381. """
  4382. line_no = 0
  4383. data = None
  4384. if sys.platform != 'win32':
  4385. # this won't work in Linux or MacOS
  4386. return
  4387. # test if the app was frozen and choose the path for the configuration file
  4388. if getattr(sys, "frozen", False) is True:
  4389. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  4390. else:
  4391. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  4392. config_file = current_data_path + '\\configuration.txt'
  4393. try:
  4394. with open(config_file, 'r') as f:
  4395. try:
  4396. data = f.readlines()
  4397. except Exception as e:
  4398. log.debug('App.__init__() -->%s' % str(e))
  4399. return
  4400. except FileNotFoundError:
  4401. pass
  4402. for line in data:
  4403. line = line.strip('\n')
  4404. param = str(line).rpartition('=')
  4405. if param[0] == 'portable':
  4406. break
  4407. line_no += 1
  4408. if state:
  4409. data[line_no] = 'portable=True\n'
  4410. # create the new defauults files
  4411. # create current_defaults.FlatConfig file if there is none
  4412. try:
  4413. f = open(current_data_path + '/current_defaults.FlatConfig')
  4414. f.close()
  4415. except IOError:
  4416. App.log.debug('Creating empty current_defaults.FlatConfig')
  4417. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  4418. json.dump({}, f)
  4419. f.close()
  4420. # create factory_defaults.FlatConfig file if there is none
  4421. try:
  4422. f = open(current_data_path + '/factory_defaults.FlatConfig')
  4423. f.close()
  4424. except IOError:
  4425. App.log.debug('Creating empty factory_defaults.FlatConfig')
  4426. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  4427. json.dump({}, f)
  4428. f.close()
  4429. try:
  4430. f = open(current_data_path + '/recent.json')
  4431. f.close()
  4432. except IOError:
  4433. App.log.debug('Creating empty recent.json')
  4434. f = open(current_data_path + '/recent.json', 'w')
  4435. json.dump([], f)
  4436. f.close()
  4437. try:
  4438. fp = open(current_data_path + '/recent_projects.json')
  4439. fp.close()
  4440. except IOError:
  4441. App.log.debug('Creating empty recent_projects.json')
  4442. fp = open(current_data_path + '/recent_projects.json', 'w')
  4443. json.dump([], fp)
  4444. fp.close()
  4445. # save the current defaults to the new defaults file
  4446. self.save_defaults(silent=True, data_path=current_data_path)
  4447. self.save_factory_defaults(silent_message=True, data_path=current_data_path)
  4448. else:
  4449. data[line_no] = 'portable=False\n'
  4450. with open(config_file, 'w') as f:
  4451. f.writelines(data)
  4452. def on_toggle_shell(self):
  4453. """
  4454. Toggle shell: if is visible close it, if it is closed then open it
  4455. :return:
  4456. """
  4457. self.report_usage("on_toggle_shell()")
  4458. if self.ui.shell_dock.isVisible():
  4459. self.ui.shell_dock.hide()
  4460. else:
  4461. self.ui.shell_dock.show()
  4462. def on_register_files(self, obj_type=None):
  4463. """
  4464. Called whenever there is a need to register file extensions with FlatCAM.
  4465. Works only in Windows and should be called only when FlatCAM is run in Windows.
  4466. :param obj_type: the type of object to be register for.
  4467. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  4468. :return: None
  4469. """
  4470. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  4471. new_reg_path = 'Software\\Classes\\'
  4472. # find if the current user is admin
  4473. try:
  4474. is_admin = os.getuid() == 0
  4475. except AttributeError:
  4476. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  4477. if is_admin is True:
  4478. root_path = winreg.HKEY_LOCAL_MACHINE
  4479. else:
  4480. root_path = winreg.HKEY_CURRENT_USER
  4481. # create the keys
  4482. def set_reg(name, root_path, new_reg_path, value):
  4483. try:
  4484. winreg.CreateKey(root_path, new_reg_path)
  4485. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  4486. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  4487. return True
  4488. except WindowsError:
  4489. return False
  4490. # delete key in registry
  4491. def delete_reg(root_path, reg_path, key_to_del):
  4492. key_to_del_path = reg_path + key_to_del
  4493. try:
  4494. winreg.DeleteKey(root_path, key_to_del_path)
  4495. return True
  4496. except WindowsError:
  4497. return False
  4498. if obj_type is None or obj_type == 'excellon':
  4499. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4500. exc_list = [x for x in exc_list if x != '']
  4501. # register all keys in the Preferences window
  4502. for ext in exc_list:
  4503. new_k = new_reg_path + '.%s' % ext
  4504. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4505. # and unregister those that are no longer in the Preferences windows but are in the file
  4506. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  4507. if ext not in exc_list:
  4508. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4509. # now write the updated extensions to the self.defaults
  4510. # new_ext = ''
  4511. # for ext in exc_list:
  4512. # new_ext = new_ext + ext + ', '
  4513. # self.defaults["fa_excellon"] = new_ext
  4514. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  4515. if obj_type is None or obj_type == 'gcode':
  4516. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4517. gco_list = [x for x in gco_list if x != '']
  4518. # register all keys in the Preferences window
  4519. for ext in gco_list:
  4520. new_k = new_reg_path + '.%s' % ext
  4521. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4522. # and unregister those that are no longer in the Preferences windows but are in the file
  4523. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  4524. if ext not in gco_list:
  4525. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4526. # now write the updated extensions to the self.defaults
  4527. # new_ext = ''
  4528. # for ext in gco_list:
  4529. # new_ext = new_ext + ext + ', '
  4530. # self.defaults["fa_gcode"] = new_ext
  4531. self.inform.emit('[success] %s' %
  4532. _("Selected GCode file extensions registered with FlatCAM."))
  4533. if obj_type is None or obj_type == 'gerber':
  4534. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4535. grb_list = [x for x in grb_list if x != '']
  4536. # register all keys in the Preferences window
  4537. for ext in grb_list:
  4538. new_k = new_reg_path + '.%s' % ext
  4539. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4540. # and unregister those that are no longer in the Preferences windows but are in the file
  4541. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  4542. if ext not in grb_list:
  4543. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4544. # now write the updated extensions to the self.defaults
  4545. # new_ext = ''
  4546. # for ext in grb_list:
  4547. # new_ext = new_ext + ext + ', '
  4548. # self.defaults["fa_gerber"] = new_ext
  4549. self.inform.emit('[success] %s' %
  4550. _("Selected Gerber file extensions registered with FlatCAM."))
  4551. def add_extension(self, ext_type):
  4552. if ext_type == 'excellon':
  4553. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4554. if new_ext == '':
  4555. return
  4556. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4557. if new_ext in old_val:
  4558. return
  4559. old_val.append(new_ext)
  4560. old_val.sort()
  4561. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4562. if ext_type == 'gcode':
  4563. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4564. if new_ext == '':
  4565. return
  4566. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4567. if new_ext in old_val:
  4568. return
  4569. old_val.append(new_ext)
  4570. old_val.sort()
  4571. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4572. if ext_type == 'gerber':
  4573. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4574. if new_ext == '':
  4575. return
  4576. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4577. if new_ext in old_val:
  4578. return
  4579. old_val.append(new_ext)
  4580. old_val.sort()
  4581. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4582. if ext_type == 'keyword':
  4583. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4584. if new_kw == '':
  4585. return
  4586. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4587. if new_kw in old_val:
  4588. return
  4589. old_val.append(new_kw)
  4590. old_val.sort()
  4591. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4592. # update the self.myKeywords so the model is updated
  4593. self.autocomplete_kw_list = \
  4594. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4595. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4596. self.shell._edit.set_model_data(self.myKeywords)
  4597. def del_extension(self, ext_type):
  4598. if ext_type == 'excellon':
  4599. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4600. if new_ext == '':
  4601. return
  4602. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4603. if new_ext not in old_val:
  4604. return
  4605. old_val.remove(new_ext)
  4606. old_val.sort()
  4607. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4608. if ext_type == 'gcode':
  4609. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4610. if new_ext == '':
  4611. return
  4612. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4613. if new_ext not in old_val:
  4614. return
  4615. old_val.remove(new_ext)
  4616. old_val.sort()
  4617. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4618. if ext_type == 'gerber':
  4619. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4620. if new_ext == '':
  4621. return
  4622. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4623. if new_ext not in old_val:
  4624. return
  4625. old_val.remove(new_ext)
  4626. old_val.sort()
  4627. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4628. if ext_type == 'keyword':
  4629. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4630. if new_kw == '':
  4631. return
  4632. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4633. if new_kw not in old_val:
  4634. return
  4635. old_val.remove(new_kw)
  4636. old_val.sort()
  4637. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4638. # update the self.myKeywords so the model is updated
  4639. self.autocomplete_kw_list = \
  4640. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4641. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4642. self.shell._edit.set_model_data(self.myKeywords)
  4643. def restore_extensions(self, ext_type):
  4644. if ext_type == 'excellon':
  4645. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  4646. # for the ability to open Excellon files with .txt extension
  4647. new_exc_list = deepcopy(self.exc_list)
  4648. try:
  4649. new_exc_list.remove('txt')
  4650. except ValueError:
  4651. pass
  4652. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  4653. if ext_type == 'gcode':
  4654. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  4655. if ext_type == 'gerber':
  4656. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  4657. if ext_type == 'keyword':
  4658. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  4659. # update the self.myKeywords so the model is updated
  4660. self.autocomplete_kw_list = self.default_keywords
  4661. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4662. self.shell._edit.set_model_data(self.myKeywords)
  4663. def delete_all_extensions(self, ext_type):
  4664. if ext_type == 'excellon':
  4665. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4666. if ext_type == 'gcode':
  4667. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4668. if ext_type == 'gerber':
  4669. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4670. if ext_type == 'keyword':
  4671. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4672. # update the self.myKeywords so the model is updated
  4673. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4674. self.shell._edit.set_model_data(self.myKeywords)
  4675. def on_edit_join(self, name=None):
  4676. """
  4677. Callback for Edit->Join. Joins the selected geometry objects into
  4678. a new one.
  4679. :return: None
  4680. """
  4681. self.report_usage("on_edit_join()")
  4682. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4683. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4684. geo_type_list = set()
  4685. objs = self.collection.get_selected()
  4686. if len(objs) < 2:
  4687. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4688. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4689. return 'fail'
  4690. for obj in objs:
  4691. geo_type_list.add(obj.multigeo)
  4692. # if len(geo_type_list) == 1 means that all list elements are the same
  4693. if len(geo_type_list) != 1:
  4694. self.inform.emit('[ERROR] %s' %
  4695. _("Failed join. The Geometry objects are of different types.\n"
  4696. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4697. "convert from one to another and retry joining \n"
  4698. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4699. "the result may not be what was expected. \n"
  4700. "Check the generated GCODE."))
  4701. return
  4702. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4703. if True in geo_type_list:
  4704. def initialize(obj, app):
  4705. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=True)
  4706. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4707. for v in obj.tools.values():
  4708. v['data']['name'] = obj_name_multi
  4709. self.new_object("geometry", obj_name_multi, initialize)
  4710. else:
  4711. def initialize(obj, app):
  4712. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=False)
  4713. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4714. for v in obj.tools.values():
  4715. v['data']['name'] = obj_name_single
  4716. self.new_object("geometry", obj_name_single, initialize)
  4717. self.should_we_save = True
  4718. def on_edit_join_exc(self):
  4719. """
  4720. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4721. a new Excellon.
  4722. :return: None
  4723. """
  4724. self.report_usage("on_edit_join_exc()")
  4725. objs = self.collection.get_selected()
  4726. for obj in objs:
  4727. if not isinstance(obj, FlatCAMExcellon):
  4728. self.inform.emit('[ERROR_NOTCL] %s' %
  4729. _("Failed. Excellon joining works only on Excellon objects."))
  4730. return
  4731. if len(objs) < 2:
  4732. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4733. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4734. return 'fail'
  4735. def initialize(obj, app):
  4736. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=obj)
  4737. self.new_object("excellon", 'Combo_Excellon', initialize)
  4738. self.should_we_save = True
  4739. def on_edit_join_grb(self):
  4740. """
  4741. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4742. a new Gerber object.
  4743. :return: None
  4744. """
  4745. self.report_usage("on_edit_join_grb()")
  4746. objs = self.collection.get_selected()
  4747. for obj in objs:
  4748. if not isinstance(obj, FlatCAMGerber):
  4749. self.inform.emit('[ERROR_NOTCL] %s' %
  4750. _("Failed. Gerber joining works only on Gerber objects."))
  4751. return
  4752. if len(objs) < 2:
  4753. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4754. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4755. return 'fail'
  4756. def initialize(obj, app):
  4757. FlatCAMGerber.merge(self, grb_list=objs, grb_final=obj)
  4758. self.new_object("gerber", 'Combo_Gerber', initialize)
  4759. self.should_we_save = True
  4760. def on_convert_singlegeo_to_multigeo(self):
  4761. """
  4762. Called for converting a Geometry object from single-geo to multi-geo.
  4763. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4764. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4765. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4766. the solid-geometry of that tool.
  4767. :return: None
  4768. """
  4769. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4770. obj = self.collection.get_active()
  4771. if obj is None:
  4772. self.inform.emit('[ERROR_NOTCL] %s' %
  4773. _("Failed. Select a Geometry Object and try again."))
  4774. return
  4775. if not isinstance(obj, FlatCAMGeometry):
  4776. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4777. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4778. return
  4779. obj.multigeo = True
  4780. for tooluid, dict_value in obj.tools.items():
  4781. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4782. if not isinstance(obj.solid_geometry, list):
  4783. obj.solid_geometry = [obj.solid_geometry]
  4784. obj.solid_geometry[:] = []
  4785. obj.plot()
  4786. self.should_we_save = True
  4787. self.inform.emit('[success] %s' %
  4788. _("A Geometry object was converted to MultiGeo type."))
  4789. def on_convert_multigeo_to_singlegeo(self):
  4790. """
  4791. Called for converting a Geometry object from multi-geo to single-geo.
  4792. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4793. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4794. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4795. the solid-geometry of that tool.
  4796. :return: None
  4797. """
  4798. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4799. obj = self.collection.get_active()
  4800. if obj is None:
  4801. self.inform.emit('[ERROR_NOTCL] %s' %
  4802. _("Failed. Select a Geometry Object and try again."))
  4803. return
  4804. if not isinstance(obj, FlatCAMGeometry):
  4805. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4806. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4807. return
  4808. obj.multigeo = False
  4809. total_solid_geometry = []
  4810. for tooluid, dict_value in obj.tools.items():
  4811. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4812. # clear the original geometry
  4813. dict_value['solid_geometry'][:] = []
  4814. obj.solid_geometry = deepcopy(total_solid_geometry)
  4815. obj.plot()
  4816. self.should_we_save = True
  4817. self.inform.emit('[success] %s' %
  4818. _("A Geometry object was converted to SingleGeo type."))
  4819. def on_options_dict_change(self, field):
  4820. """
  4821. Called whenever a key changed in the self.options dictionary. This dict was used to store the preferences of the
  4822. current project. This feature is no longer used.
  4823. :param field:
  4824. :return:
  4825. """
  4826. self.options_write_form_field(field)
  4827. if field == "units":
  4828. self.set_screen_units(self.options['units'])
  4829. def on_defaults_dict_change(self, field):
  4830. """
  4831. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4832. Edit -> Preferences tab window.
  4833. :param field: the key of the self.defaults dictionary that was changed.
  4834. :return: None
  4835. """
  4836. self.defaults_write_form_field(field)
  4837. if field == "units":
  4838. self.set_screen_units(self.defaults['units'])
  4839. def set_screen_units(self, units):
  4840. """
  4841. Set the FlatCAM units on the status bar.
  4842. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4843. :return: None
  4844. """
  4845. self.ui.units_label.setText("[" + units.lower() + "]")
  4846. def on_toggle_units(self, no_pref=False):
  4847. """
  4848. Callback for the Units radio-button change in the Preferences tab.
  4849. Changes the application's default units adn for the project too.
  4850. If changing the project's units, the change propagates to all of
  4851. the objects in the project.
  4852. :return: None
  4853. """
  4854. self.report_usage("on_toggle_units")
  4855. if self.toggle_units_ignore:
  4856. return
  4857. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4858. # If option is the same, then ignore
  4859. if new_units == self.defaults["units"].upper():
  4860. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4861. return
  4862. # Options to scale
  4863. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin', "gerber_isooverlap",
  4864. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  4865. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  4866. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4867. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  4868. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  4869. "excellon_editor_slot_lin_pitch",
  4870. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4871. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4872. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  4873. "geometry_feedrate_probe", "geometry_startz",
  4874. 'cncjob_tooldia',
  4875. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4876. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  4877. "tools_2sided_drilldia", "tools_film_boundary",
  4878. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4879. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4880. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4881. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4882. "tools_transform_offset_y",
  4883. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4884. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4885. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4886. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4887. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  4888. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  4889. "tools_cr_h2h_val", "tools_cr_dh_val",
  4890. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance"]
  4891. def scale_options(sfactor):
  4892. for dim in dimensions:
  4893. if dim == 'excellon_toolchangexy':
  4894. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4895. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4896. coords_xy[0] *= sfactor
  4897. coords_xy[1] *= sfactor
  4898. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4899. elif dim == 'geometry_toolchangexy':
  4900. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4901. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4902. coords_xy[0] *= sfactor
  4903. coords_xy[1] *= sfactor
  4904. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4905. elif dim == 'geometry_cnctooldia':
  4906. tools_diameters = []
  4907. try:
  4908. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4909. tools_diameters = [eval(a) for a in tools_string if a != '']
  4910. except Exception as e:
  4911. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4912. self.options['geometry_cnctooldia'] = ''
  4913. for t in range(len(tools_diameters)):
  4914. tools_diameters[t] *= sfactor
  4915. self.options['geometry_cnctooldia'] += "%f," % tools_diameters[t]
  4916. elif dim == 'tools_ncctools':
  4917. ncctools = []
  4918. try:
  4919. tools_string = self.defaults["tools_ncctools"].split(",")
  4920. ncctools = [eval(a) for a in tools_string if a != '']
  4921. except Exception as e:
  4922. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4923. self.options['tools_ncctools'] = ''
  4924. for t in range(len(ncctools)):
  4925. ncctools[t] *= sfactor
  4926. self.options['tools_ncctools'] += "%f," % ncctools[t]
  4927. elif dim == 'tools_solderpaste_tools':
  4928. sptools = []
  4929. try:
  4930. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4931. sptools = [eval(a) for a in tools_string if a != '']
  4932. except Exception as e:
  4933. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4934. self.options['tools_solderpaste_tools'] = ""
  4935. for t in range(len(sptools)):
  4936. sptools[t] *= sfactor
  4937. self.options['tools_solderpaste_tools'] += "%f," % sptools[t]
  4938. elif dim == 'tools_solderpaste_xy_toolchange':
  4939. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4940. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4941. sp_coords[0] *= sfactor
  4942. sp_coords[1] *= sfactor
  4943. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  4944. elif dim == 'global_gridx' or dim == 'global_gridy':
  4945. if new_units == 'IN':
  4946. val = 0.1
  4947. try:
  4948. val = float(self.defaults[dim]) * sfactor
  4949. except Exception as e:
  4950. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4951. self.options[dim] = float('%.6f' % val)
  4952. else:
  4953. val = 0.1
  4954. try:
  4955. val = float(self.defaults[dim]) * sfactor
  4956. except Exception as e:
  4957. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4958. self.options[dim] = float('%.4f' % val)
  4959. else:
  4960. val = 0.1
  4961. if self.options[dim]:
  4962. try:
  4963. val = float(self.options[dim]) * sfactor
  4964. except Exception as e:
  4965. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  4966. self.options[dim] = val
  4967. def scale_defaults(sfactor):
  4968. for dim in dimensions:
  4969. if dim == 'excellon_toolchangexy':
  4970. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4971. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4972. coords_xy[0] *= sfactor
  4973. coords_xy[1] *= sfactor
  4974. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4975. elif dim == 'geometry_toolchangexy':
  4976. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4977. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4978. coords_xy[0] *= sfactor
  4979. coords_xy[1] *= sfactor
  4980. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4981. elif dim == 'geometry_cnctooldia':
  4982. tools_diameters = []
  4983. try:
  4984. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4985. tools_diameters = [eval(a) for a in tools_string if a != '']
  4986. except Exception as e:
  4987. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4988. self.defaults['geometry_cnctooldia'] = ''
  4989. for t in range(len(tools_diameters)):
  4990. tools_diameters[t] *= sfactor
  4991. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  4992. elif dim == 'tools_ncctools':
  4993. ncctools = []
  4994. try:
  4995. tools_string = self.defaults["tools_ncctools"].split(",")
  4996. ncctools = [eval(a) for a in tools_string if a != '']
  4997. except Exception as e:
  4998. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4999. self.defaults['tools_ncctools'] = ''
  5000. for t in range(len(ncctools)):
  5001. ncctools[t] *= sfactor
  5002. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  5003. elif dim == 'tools_solderpaste_tools':
  5004. sptools = []
  5005. try:
  5006. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  5007. sptools = [eval(a) for a in tools_string if a != '']
  5008. except Exception as e:
  5009. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  5010. self.defaults['tools_solderpaste_tools'] = ""
  5011. for t in range(len(sptools)):
  5012. sptools[t] *= sfactor
  5013. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  5014. elif dim == 'tools_solderpaste_xy_toolchange':
  5015. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  5016. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  5017. sp_coords[0] *= sfactor
  5018. sp_coords[1] *= sfactor
  5019. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  5020. elif dim == 'global_gridx' or dim == 'global_gridy':
  5021. if new_units == 'IN':
  5022. val = 0.1
  5023. try:
  5024. val = float(self.defaults[dim]) * sfactor
  5025. except Exception as e:
  5026. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  5027. self.defaults[dim] = float('%.6f' % val)
  5028. else:
  5029. val = 0.1
  5030. try:
  5031. val = float(self.defaults[dim]) * sfactor
  5032. except Exception as e:
  5033. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  5034. self.defaults[dim] = float('%.4f' % val)
  5035. else:
  5036. val = 0.1
  5037. if self.defaults[dim]:
  5038. try:
  5039. val = float(self.defaults[dim]) * sfactor
  5040. except Exception as e:
  5041. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  5042. self.defaults[dim] = val
  5043. # The scaling factor depending on choice of units.
  5044. factor = 1/25.4
  5045. if new_units == 'MM':
  5046. factor = 25.4
  5047. # Changing project units. Warn user.
  5048. msgbox = QtWidgets.QMessageBox()
  5049. msgbox.setWindowTitle(_("Toggle Units"))
  5050. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  5051. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5052. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  5053. "properties of all objects to be scaled accordingly.\nContinue?"))
  5054. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5055. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5056. msgbox.setDefaultButton(bt_ok)
  5057. msgbox.exec_()
  5058. response = msgbox.clickedButton()
  5059. if response == bt_ok:
  5060. if no_pref is False:
  5061. self.options_read_form()
  5062. scale_options(factor)
  5063. self.options_write_form()
  5064. self.defaults_read_form()
  5065. scale_defaults(factor)
  5066. self.defaults_write_form(fl_units=new_units)
  5067. # save the defaults to file, some may assume that the conversion is enough and it's not
  5068. self.on_save_button()
  5069. self.should_we_save = True
  5070. # change this only if the workspace is active
  5071. if self.defaults['global_workspace'] is True:
  5072. self.plotcanvas.draw_workspace()
  5073. # adjust the grid values on the main toolbar
  5074. dec = 6 if new_units == 'IN'else 4
  5075. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  5076. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  5077. if not self.ui.grid_gap_link_cb.isChecked():
  5078. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  5079. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  5080. for obj in self.collection.get_list():
  5081. obj.convert_units(new_units)
  5082. # make that the properties stored in the object are also updated
  5083. self.object_changed.emit(obj)
  5084. obj.build_ui()
  5085. current = self.collection.get_active()
  5086. if current is not None:
  5087. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  5088. if not isinstance(current, FlatCAMGeometry):
  5089. current.to_form()
  5090. self.plot_all()
  5091. self.inform.emit('[success] %s: %s' %
  5092. (_("Converted units to"), new_units))
  5093. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  5094. self.set_screen_units(new_units)
  5095. else:
  5096. # Undo toggling
  5097. self.toggle_units_ignore = True
  5098. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  5099. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  5100. else:
  5101. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  5102. self.toggle_units_ignore = False
  5103. self.inform.emit('[WARNING_NOTCL]%s' %
  5104. _(" Units conversion cancelled."))
  5105. self.options_read_form()
  5106. self.defaults_read_form()
  5107. def on_toggle_units_click(self):
  5108. try:
  5109. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  5110. except (TypeError, AttributeError):
  5111. pass
  5112. if self.defaults["units"] == 'MM':
  5113. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  5114. else:
  5115. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  5116. self.on_toggle_units(no_pref=True)
  5117. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  5118. lambda: self.on_toggle_units(no_pref=False))
  5119. def on_fullscreen(self, disable=False):
  5120. self.report_usage("on_fullscreen()")
  5121. if self.toggle_fscreen is False and disable is False:
  5122. # self.ui.showFullScreen()
  5123. self.ui.setWindowFlags(self.ui.windowFlags() | Qt.FramelessWindowHint)
  5124. a = self.ui.geometry()
  5125. self.x_pos = a.x()
  5126. self.y_pos = a.y()
  5127. self.width = a.width()
  5128. self.height = a.height()
  5129. # set new geometry to full desktop rect
  5130. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  5131. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  5132. # everything else will not work without this hack. This happen in Windows.
  5133. # https://bugreports.qt.io/browse/QTBUG-41309
  5134. desktop = QtWidgets.QApplication.desktop()
  5135. screen = desktop.screenNumber(QtGui.QCursor.pos())
  5136. rec = desktop.screenGeometry(screen)
  5137. x = rec.x() - 1
  5138. y = rec.y() - 1
  5139. h = rec.height() + 2
  5140. w = rec.width() + 2
  5141. self.ui.setGeometry(x, y, w, h)
  5142. self.ui.show()
  5143. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  5144. tb.setVisible(False)
  5145. self.ui.splitter_left.setVisible(False)
  5146. self.toggle_fscreen = True
  5147. elif self.toggle_fscreen is True or disable is True:
  5148. self.ui.setWindowFlags(self.ui.windowFlags() & ~Qt.FramelessWindowHint)
  5149. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  5150. self.ui.showNormal()
  5151. self.restore_toolbar_view()
  5152. self.ui.splitter_left.setVisible(True)
  5153. self.toggle_fscreen = False
  5154. def on_toggle_plotarea(self):
  5155. self.report_usage("on_toggle_plotarea()")
  5156. try:
  5157. name = self.ui.plot_tab_area.widget(0).objectName()
  5158. except AttributeError:
  5159. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  5160. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  5161. self.ui.plot_tab_area.protectTab(0)
  5162. return
  5163. if name != 'plotarea':
  5164. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5165. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  5166. self.ui.plot_tab_area.protectTab(0)
  5167. else:
  5168. self.ui.plot_tab_area.closeTab(0)
  5169. def on_toggle_notebook(self):
  5170. if self.ui.splitter.sizes()[0] == 0:
  5171. self.ui.splitter.setSizes([1, 1])
  5172. self.ui.menu_toggle_nb.setChecked(True)
  5173. else:
  5174. self.ui.splitter.setSizes([0, 1])
  5175. self.ui.menu_toggle_nb.setChecked(False)
  5176. def on_toggle_axis(self):
  5177. self.report_usage("on_toggle_axis()")
  5178. if self.toggle_axis is False:
  5179. if self.is_legacy is False:
  5180. # self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  5181. # self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  5182. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  5183. parent=self.plotcanvas.view.scene)
  5184. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  5185. parent=self.plotcanvas.view.scene)
  5186. # self.plotcanvas.redraw()
  5187. else:
  5188. self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  5189. self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  5190. self.plotcanvas.canvas.draw()
  5191. pass
  5192. self.toggle_axis = True
  5193. else:
  5194. if self.is_legacy is False:
  5195. # self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  5196. # self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  5197. # self.plotcanvas.redraw()
  5198. self.plotcanvas.v_line.parent = None
  5199. self.plotcanvas.h_line.parent = None
  5200. else:
  5201. self.plotcanvas.axes.lines[:] = []
  5202. self.plotcanvas.canvas.draw()
  5203. self.toggle_axis = False
  5204. def on_toggle_grid(self):
  5205. self.report_usage("on_toggle_grid()")
  5206. self.ui.grid_snap_btn.trigger()
  5207. def on_toggle_grid_lines(self):
  5208. self.report_usage("on_toggle_grd_lines()")
  5209. settings = QtCore.QSettings("Open Source", "FlatCAM")
  5210. if settings.contains("theme"):
  5211. theme = settings.value('theme', type=str)
  5212. else:
  5213. theme = 'white'
  5214. if self.toggle_grid_lines is False:
  5215. if self.is_legacy is False:
  5216. if theme == 'white':
  5217. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  5218. else:
  5219. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  5220. else:
  5221. self.plotcanvas.axes.grid(True)
  5222. try:
  5223. self.plotcanvas.canvas.draw()
  5224. except IndexError:
  5225. pass
  5226. pass
  5227. self.toggle_grid_lines = True
  5228. else:
  5229. if self.is_legacy is False:
  5230. if theme == 'white':
  5231. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  5232. else:
  5233. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  5234. else:
  5235. self.plotcanvas.axes.grid(False)
  5236. try:
  5237. self.plotcanvas.canvas.draw()
  5238. except IndexError:
  5239. pass
  5240. self.toggle_grid_lines = False
  5241. def on_options_combo_change(self, sel):
  5242. """
  5243. Called when the combo box to choose between application defaults and
  5244. project option changes value. The corresponding variables are
  5245. copied to the UI.
  5246. :param sel: The option index that was chosen.
  5247. :return: None
  5248. """
  5249. # combo_sel = self.ui.notebook.combo_options.get_active()
  5250. App.log.debug("Options --> %s" % sel)
  5251. # form = [self.defaults_form, self.options_form][sel]
  5252. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  5253. if sel == 0:
  5254. self.gen_form = self.ui.general_defaults_form
  5255. self.ger_form = self.ui.gerber_defaults_form
  5256. self.exc_form = self.ui.excellon_defaults_form
  5257. self.geo_form = self.ui.geometry_defaults_form
  5258. self.cnc_form = self.ui.cncjob_defaults_form
  5259. self.tools_form = self.ui.tools_defaults_form
  5260. self.tools2_form = self.ui.tools2_defaults_form
  5261. self.fa_form = self.ui.util_defaults_form
  5262. elif sel == 1:
  5263. self.gen_form = self.ui.general_options_form
  5264. self.ger_form = self.ui.gerber_options_form
  5265. self.exc_form = self.ui.excellon_options_form
  5266. self.geo_form = self.ui.geometry_options_form
  5267. self.cnc_form = self.ui.cncjob_options_form
  5268. self.tools_form = self.ui.tools_options_form
  5269. self.tools2_form = self.ui.tools2_options_form
  5270. self.fa_form = self.ui.util_options_form
  5271. else:
  5272. return
  5273. try:
  5274. self.ui.general_scroll_area.takeWidget()
  5275. except:
  5276. self.log.debug("Nothing to remove")
  5277. self.ui.general_scroll_area.setWidget(self.gen_form)
  5278. self.gen_form.show()
  5279. try:
  5280. self.ui.gerber_scroll_area.takeWidget()
  5281. except:
  5282. self.log.debug("Nothing to remove")
  5283. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  5284. self.ger_form.show()
  5285. try:
  5286. self.ui.excellon_scroll_area.takeWidget()
  5287. except:
  5288. self.log.debug("Nothing to remove")
  5289. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  5290. self.exc_form.show()
  5291. try:
  5292. self.ui.geometry_scroll_area.takeWidget()
  5293. except:
  5294. self.log.debug("Nothing to remove")
  5295. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  5296. self.geo_form.show()
  5297. try:
  5298. self.ui.cncjob_scroll_area.takeWidget()
  5299. except:
  5300. self.log.debug("Nothing to remove")
  5301. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  5302. self.cnc_form.show()
  5303. try:
  5304. self.ui.tools_scroll_area.takeWidget()
  5305. except:
  5306. self.log.debug("Nothing to remove")
  5307. self.ui.tools_scroll_area.setWidget(self.tools_form)
  5308. self.tools_form.show()
  5309. try:
  5310. self.ui.tools2_scroll_area.takeWidget()
  5311. except:
  5312. self.log.debug("Nothing to remove")
  5313. self.ui.tools2_scroll_area.setWidget(self.tools2_form)
  5314. self.tools2_form.show()
  5315. try:
  5316. self.ui.fa_scroll_area.takeWidget()
  5317. except:
  5318. self.log.debug("Nothing to remove")
  5319. self.ui.fa_scroll_area.setWidget(self.fa_form)
  5320. self.fa_form.show()
  5321. self.log.debug("Finished GUI form initialization.")
  5322. # self.options2form()
  5323. def on_excellon_defaults_button(self):
  5324. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  5325. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  5326. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  5327. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  5328. self.defaults_form_fields["excellon_zeros"].set_value('L')
  5329. self.defaults_form_fields["excellon_units"].set_value('INCH')
  5330. log.debug("Excellon app defaults loaded ...")
  5331. def on_excellon_options_button(self):
  5332. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  5333. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  5334. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  5335. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  5336. self.options_form_fields["excellon_zeros"].set_value('L')
  5337. self.options_form_fields["excellon_units"].set_value('INCH')
  5338. log.debug("Excellon options defaults loaded ...")
  5339. def on_update_exc_export(self, state):
  5340. """
  5341. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  5342. if the update_excellon_cb checkbox is checked
  5343. :param state: state of the checkbox whose signals is tied to his slot
  5344. :return:
  5345. """
  5346. if state:
  5347. # first try to disconnect
  5348. try:
  5349. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.\
  5350. disconnect(self.on_excellon_format_changed)
  5351. except TypeError:
  5352. pass
  5353. try:
  5354. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.\
  5355. disconnect(self.on_excellon_format_changed)
  5356. except TypeError:
  5357. pass
  5358. try:
  5359. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.\
  5360. disconnect(self.on_excellon_format_changed)
  5361. except TypeError:
  5362. pass
  5363. try:
  5364. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.\
  5365. disconnect(self.on_excellon_format_changed)
  5366. except TypeError:
  5367. pass
  5368. try:
  5369. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  5370. disconnect(self.on_excellon_zeros_changed)
  5371. except TypeError:
  5372. pass
  5373. try:
  5374. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  5375. disconnect(self.on_excellon_zeros_changed)
  5376. except TypeError:
  5377. pass
  5378. # the connect them
  5379. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  5380. self.on_excellon_format_changed)
  5381. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  5382. self.on_excellon_format_changed)
  5383. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  5384. self.on_excellon_format_changed)
  5385. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  5386. self.on_excellon_format_changed)
  5387. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  5388. self.on_excellon_zeros_changed)
  5389. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  5390. self.on_excellon_units_changed)
  5391. else:
  5392. # disconnect the signals
  5393. try:
  5394. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  5395. disconnect(self.on_excellon_format_changed)
  5396. except TypeError:
  5397. pass
  5398. try:
  5399. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  5400. disconnect(self.on_excellon_format_changed)
  5401. except TypeError:
  5402. pass
  5403. try:
  5404. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  5405. disconnect(self.on_excellon_format_changed)
  5406. except TypeError:
  5407. pass
  5408. try:
  5409. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  5410. disconnect(self.on_excellon_format_changed)
  5411. except TypeError:
  5412. pass
  5413. try:
  5414. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  5415. disconnect(self.on_excellon_zeros_changed)
  5416. except TypeError:
  5417. pass
  5418. try:
  5419. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  5420. disconnect(self.on_excellon_zeros_changed)
  5421. except TypeError:
  5422. pass
  5423. def on_excellon_format_changed(self):
  5424. """
  5425. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  5426. :return: None
  5427. """
  5428. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  5429. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5430. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  5431. )
  5432. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5433. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  5434. )
  5435. else:
  5436. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5437. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  5438. )
  5439. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5440. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  5441. )
  5442. def on_excellon_zeros_changed(self):
  5443. """
  5444. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  5445. :return: None
  5446. """
  5447. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  5448. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  5449. )
  5450. def on_excellon_units_changed(self):
  5451. """
  5452. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  5453. :return: None
  5454. """
  5455. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  5456. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  5457. )
  5458. self.on_excellon_format_changed()
  5459. # Setting plot colors handlers
  5460. def on_pf_color_entry(self):
  5461. self.defaults['global_plot_fill'] = \
  5462. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  5463. self.defaults['global_plot_fill'][7:9]
  5464. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5465. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  5466. def on_pf_color_button(self):
  5467. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  5468. c_dialog = QtWidgets.QColorDialog()
  5469. plot_fill_color = c_dialog.getColor(initial=current_color)
  5470. if plot_fill_color.isValid() is False:
  5471. return
  5472. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5473. "background-color:%s" % str(plot_fill_color.name()))
  5474. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  5475. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  5476. self.defaults['global_plot_fill'] = new_val
  5477. def on_pf_color_spinner(self):
  5478. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  5479. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  5480. self.defaults['global_plot_fill'] = \
  5481. self.defaults['global_plot_fill'][:7] + \
  5482. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5483. self.defaults['global_plot_line'] = \
  5484. self.defaults['global_plot_line'][:7] + \
  5485. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5486. def on_pf_color_slider(self):
  5487. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  5488. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  5489. def on_pl_color_entry(self):
  5490. self.defaults['global_plot_line'] = \
  5491. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  5492. self.defaults['global_plot_line'][7:9]
  5493. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5494. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  5495. def on_pl_color_button(self):
  5496. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  5497. # print(current_color)
  5498. c_dialog = QtWidgets.QColorDialog()
  5499. plot_line_color = c_dialog.getColor(initial=current_color)
  5500. if plot_line_color.isValid() is False:
  5501. return
  5502. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5503. "background-color:%s" % str(plot_line_color.name()))
  5504. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  5505. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  5506. self.defaults['global_plot_line'] = new_val_line
  5507. # Setting selection colors (left - right) handlers
  5508. def on_sf_color_entry(self):
  5509. self.defaults['global_sel_fill'] = \
  5510. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  5511. self.defaults['global_sel_fill'][7:9]
  5512. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5513. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  5514. def on_sf_color_button(self):
  5515. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  5516. c_dialog = QtWidgets.QColorDialog()
  5517. plot_fill_color = c_dialog.getColor(initial=current_color)
  5518. if plot_fill_color.isValid() is False:
  5519. return
  5520. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5521. "background-color:%s" % str(plot_fill_color.name()))
  5522. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  5523. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  5524. self.defaults['global_sel_fill'] = new_val
  5525. def on_sf_color_spinner(self):
  5526. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  5527. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  5528. self.defaults['global_sel_fill'] = \
  5529. self.defaults['global_sel_fill'][:7] + \
  5530. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5531. self.defaults['global_sel_line'] = \
  5532. self.defaults['global_sel_line'][:7] + \
  5533. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5534. def on_sf_color_slider(self):
  5535. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  5536. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  5537. def on_sl_color_entry(self):
  5538. self.defaults['global_sel_line'] = \
  5539. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  5540. self.defaults['global_sel_line'][7:9]
  5541. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5542. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  5543. def on_sl_color_button(self):
  5544. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  5545. c_dialog = QtWidgets.QColorDialog()
  5546. plot_line_color = c_dialog.getColor(initial=current_color)
  5547. if plot_line_color.isValid() is False:
  5548. return
  5549. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5550. "background-color:%s" % str(plot_line_color.name()))
  5551. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  5552. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  5553. self.defaults['global_sel_line'] = new_val_line
  5554. # Setting selection colors (right - left) handlers
  5555. def on_alt_sf_color_entry(self):
  5556. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  5557. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  5558. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5559. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  5560. def on_alt_sf_color_button(self):
  5561. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  5562. c_dialog = QtWidgets.QColorDialog()
  5563. plot_fill_color = c_dialog.getColor(initial=current_color)
  5564. if plot_fill_color.isValid() is False:
  5565. return
  5566. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5567. "background-color:%s" % str(plot_fill_color.name()))
  5568. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  5569. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  5570. self.defaults['global_alt_sel_fill'] = new_val
  5571. def on_alt_sf_color_spinner(self):
  5572. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  5573. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  5574. self.defaults['global_alt_sel_fill'] = \
  5575. self.defaults['global_alt_sel_fill'][:7] + \
  5576. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5577. self.defaults['global_alt_sel_line'] = \
  5578. self.defaults['global_alt_sel_line'][:7] + \
  5579. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5580. def on_alt_sf_color_slider(self):
  5581. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  5582. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  5583. def on_alt_sl_color_entry(self):
  5584. self.defaults['global_alt_sel_line'] = \
  5585. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  5586. self.defaults['global_alt_sel_line'][7:9]
  5587. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5588. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  5589. def on_alt_sl_color_button(self):
  5590. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  5591. c_dialog = QtWidgets.QColorDialog()
  5592. plot_line_color = c_dialog.getColor(initial=current_color)
  5593. if plot_line_color.isValid() is False:
  5594. return
  5595. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5596. "background-color:%s" % str(plot_line_color.name()))
  5597. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  5598. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  5599. self.defaults['global_alt_sel_line'] = new_val_line
  5600. # Setting Editor colors
  5601. def on_draw_color_entry(self):
  5602. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5603. .draw_color_entry.get_value()
  5604. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5605. "background-color:%s" % str(self.defaults['global_draw_color']))
  5606. def on_draw_color_button(self):
  5607. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  5608. c_dialog = QtWidgets.QColorDialog()
  5609. draw_color = c_dialog.getColor(initial=current_color)
  5610. if draw_color.isValid() is False:
  5611. return
  5612. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5613. "background-color:%s" % str(draw_color.name()))
  5614. new_val = str(draw_color.name())
  5615. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  5616. self.defaults['global_draw_color'] = new_val
  5617. def on_sel_draw_color_entry(self):
  5618. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5619. .sel_draw_color_entry.get_value()
  5620. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5621. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  5622. def on_sel_draw_color_button(self):
  5623. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  5624. c_dialog = QtWidgets.QColorDialog()
  5625. sel_draw_color = c_dialog.getColor(initial=current_color)
  5626. if sel_draw_color.isValid() is False:
  5627. return
  5628. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5629. "background-color:%s" % str(sel_draw_color.name()))
  5630. new_val_sel = str(sel_draw_color.name())
  5631. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  5632. self.defaults['global_sel_draw_color'] = new_val_sel
  5633. def on_proj_color_entry(self):
  5634. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  5635. .proj_color_entry.get_value()
  5636. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5637. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  5638. def on_proj_color_button(self):
  5639. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  5640. c_dialog = QtWidgets.QColorDialog()
  5641. proj_color = c_dialog.getColor(initial=current_color)
  5642. if proj_color.isValid() is False:
  5643. return
  5644. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5645. "background-color:%s" % str(proj_color.name()))
  5646. new_val_sel = str(proj_color.name())
  5647. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  5648. self.defaults['global_proj_item_color'] = new_val_sel
  5649. def on_proj_color_dis_entry(self):
  5650. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  5651. .proj_color_dis_entry.get_value()
  5652. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5653. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  5654. def on_proj_color_dis_button(self):
  5655. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  5656. c_dialog = QtWidgets.QColorDialog()
  5657. proj_color = c_dialog.getColor(initial=current_color)
  5658. if proj_color.isValid() is False:
  5659. return
  5660. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5661. "background-color:%s" % str(proj_color.name()))
  5662. new_val_sel = str(proj_color.name())
  5663. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  5664. self.defaults['global_proj_item_dis_color'] = new_val_sel
  5665. def on_annotation_fontcolor_entry(self):
  5666. self.defaults['cncjob_annotation_fontcolor'] = \
  5667. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.get_value()
  5668. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5669. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  5670. def on_annotation_fontcolor_button(self):
  5671. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  5672. c_dialog = QtWidgets.QColorDialog()
  5673. annotation_color = c_dialog.getColor(initial=current_color)
  5674. if annotation_color.isValid() is False:
  5675. return
  5676. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5677. "background-color:%s" % str(annotation_color.name()))
  5678. new_val_sel = str(annotation_color.name())
  5679. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(new_val_sel)
  5680. self.defaults['cncjob_annotation_fontcolor'] = new_val_sel
  5681. def on_film_color_entry(self):
  5682. self.defaults['tools_film_color'] = \
  5683. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  5684. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5685. "background-color:%s;"
  5686. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  5687. )
  5688. def on_film_color_button(self):
  5689. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  5690. c_dialog = QtWidgets.QColorDialog()
  5691. film_color = c_dialog.getColor(initial=current_color)
  5692. if film_color.isValid() is False:
  5693. return
  5694. # if new color is different then mark that the Preferences are changed
  5695. if film_color != current_color:
  5696. self.on_preferences_edited()
  5697. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5698. "background-color:%s;"
  5699. "border-color: dimgray" % str(film_color.name())
  5700. )
  5701. new_val_sel = str(film_color.name())
  5702. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  5703. self.defaults['tools_film_color'] = new_val_sel
  5704. def on_qrcode_fill_color_entry(self):
  5705. self.defaults['tools_qrcode_fill_color'] = \
  5706. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  5707. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5708. "background-color:%s;"
  5709. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  5710. )
  5711. def on_qrcode_fill_color_button(self):
  5712. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  5713. c_dialog = QtWidgets.QColorDialog()
  5714. fill_color = c_dialog.getColor(initial=current_color)
  5715. if fill_color.isValid() is False:
  5716. return
  5717. # if new color is different then mark that the Preferences are changed
  5718. if fill_color != current_color:
  5719. self.on_preferences_edited()
  5720. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5721. "background-color:%s;"
  5722. "border-color: dimgray" % str(fill_color.name())
  5723. )
  5724. new_val_sel = str(fill_color.name())
  5725. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  5726. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  5727. def on_qrcode_back_color_entry(self):
  5728. self.defaults['tools_qrcode_back_color'] = \
  5729. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  5730. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5731. "background-color:%s;"
  5732. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  5733. )
  5734. def on_qrcode_back_color_button(self):
  5735. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  5736. c_dialog = QtWidgets.QColorDialog()
  5737. back_color = c_dialog.getColor(initial=current_color)
  5738. if back_color.isValid() is False:
  5739. return
  5740. # if new color is different then mark that the Preferences are changed
  5741. if back_color != current_color:
  5742. self.on_preferences_edited()
  5743. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5744. "background-color:%s;"
  5745. "border-color: dimgray" % str(back_color.name())
  5746. )
  5747. new_val_sel = str(back_color.name())
  5748. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  5749. self.defaults['tools_qrcode_back_color'] = new_val_sel
  5750. def on_splash_changed(self, state):
  5751. settings = QSettings("Open Source", "FlatCAM")
  5752. settings.setValue('splash_screen', 1) if state else settings.setValue('splash_screen', 0)
  5753. # This will write the setting to the platform specific storage.
  5754. del settings
  5755. def on_tab_rmb_click(self, checked):
  5756. self.ui.notebook.set_detachable(val=checked)
  5757. self.defaults["global_tabs_detachable"] = checked
  5758. self.ui.plot_tab_area.set_detachable(val=checked)
  5759. self.defaults["global_tabs_detachable"] = checked
  5760. def on_tab_setup_context_menu(self):
  5761. initial_checked = self.defaults["global_tabs_detachable"]
  5762. action_name = str(_("Detachable Tabs"))
  5763. action = QtWidgets.QAction(self)
  5764. action.setCheckable(True)
  5765. action.setText(action_name)
  5766. action.setChecked(initial_checked)
  5767. self.ui.notebook.tabBar.addAction(action)
  5768. self.ui.plot_tab_area.tabBar.addAction(action)
  5769. try:
  5770. action.triggered.disconnect()
  5771. except TypeError:
  5772. pass
  5773. action.triggered.connect(self.on_tab_rmb_click)
  5774. def on_deselect_all(self):
  5775. self.collection.set_all_inactive()
  5776. self.delete_selection_shape()
  5777. def on_workspace_modified(self):
  5778. self.save_defaults(silent=True)
  5779. self.plotcanvas.draw_workspace()
  5780. def on_workspace(self):
  5781. self.report_usage("on_workspace()")
  5782. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5783. self.plotcanvas.restore_workspace()
  5784. else:
  5785. self.plotcanvas.delete_workspace()
  5786. self.save_defaults(silent=True)
  5787. def on_workspace_menu(self):
  5788. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5789. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  5790. else:
  5791. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  5792. self.on_workspace()
  5793. def on_layout(self, index=None, lay=None):
  5794. """
  5795. Set the toolbars layout (location)
  5796. :param index:
  5797. :param lay: type of layout to be set on the toolbard
  5798. :return: None
  5799. """
  5800. self.report_usage("on_layout()")
  5801. if lay:
  5802. current_layout = lay
  5803. else:
  5804. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  5805. settings = QSettings("Open Source", "FlatCAM")
  5806. settings.setValue('layout', current_layout)
  5807. # This will write the setting to the platform specific storage.
  5808. del settings
  5809. # first remove the toolbars:
  5810. try:
  5811. self.ui.removeToolBar(self.ui.toolbarfile)
  5812. self.ui.removeToolBar(self.ui.toolbargeo)
  5813. self.ui.removeToolBar(self.ui.toolbarview)
  5814. self.ui.removeToolBar(self.ui.toolbarshell)
  5815. self.ui.removeToolBar(self.ui.toolbartools)
  5816. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  5817. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  5818. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  5819. self.ui.removeToolBar(self.ui.snap_toolbar)
  5820. self.ui.removeToolBar(self.ui.toolbarshell)
  5821. except Exception as e:
  5822. pass
  5823. if current_layout == 'standard':
  5824. # ## TOOLBAR INSTALLATION # ##
  5825. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5826. self.ui.toolbarfile.setObjectName('File_TB')
  5827. self.ui.addToolBar(self.ui.toolbarfile)
  5828. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5829. self.ui.toolbargeo.setObjectName('Edit_TB')
  5830. self.ui.addToolBar(self.ui.toolbargeo)
  5831. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5832. self.ui.toolbarview.setObjectName('View_TB')
  5833. self.ui.addToolBar(self.ui.toolbarview)
  5834. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5835. self.ui.toolbarshell.setObjectName('Shell_TB')
  5836. self.ui.addToolBar(self.ui.toolbarshell)
  5837. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5838. self.ui.toolbartools.setObjectName('Tools_TB')
  5839. self.ui.addToolBar(self.ui.toolbartools)
  5840. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5841. # self.ui.exc_edit_toolbar.setVisible(False)
  5842. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5843. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  5844. self.ui.addToolBarBreak()
  5845. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5846. # self.ui.geo_edit_toolbar.setVisible(False)
  5847. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5848. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  5849. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5850. # self.ui.grb_edit_toolbar.setVisible(False)
  5851. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5852. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  5853. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5854. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5855. # self.ui.snap_toolbar.setMaximumHeight(30)
  5856. self.ui.addToolBar(self.ui.snap_toolbar)
  5857. self.ui.corner_snap_btn.setVisible(False)
  5858. self.ui.snap_magnet.setVisible(False)
  5859. elif current_layout == 'compact':
  5860. # ## TOOLBAR INSTALLATION # ##
  5861. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5862. self.ui.toolbarfile.setObjectName('File_TB')
  5863. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  5864. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5865. self.ui.toolbargeo.setObjectName('Edit_TB')
  5866. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  5867. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5868. self.ui.toolbarshell.setObjectName('Shell_TB')
  5869. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  5870. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5871. self.ui.toolbartools.setObjectName('Tools_TB')
  5872. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  5873. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5874. # self.ui.geo_edit_toolbar.setVisible(False)
  5875. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5876. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  5877. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5878. self.ui.toolbarview.setObjectName('View_TB')
  5879. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  5880. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  5881. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5882. # self.ui.grb_edit_toolbar.setVisible(False)
  5883. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5884. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  5885. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5886. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5887. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  5888. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5889. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5890. self.ui.snap_toolbar.setMaximumHeight(30)
  5891. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  5892. self.ui.corner_snap_btn.setVisible(True)
  5893. self.ui.snap_magnet.setVisible(True)
  5894. # add all the actions to the toolbars
  5895. self.ui.populate_toolbars()
  5896. # reconnect all the signals to the toolbar actions
  5897. self.connect_toolbar_signals()
  5898. self.ui.grid_snap_btn.setChecked(True)
  5899. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  5900. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  5901. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  5902. self.ui.grid_gap_link_cb.setChecked(True)
  5903. def on_cursor_type(self, val):
  5904. """
  5905. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  5906. :return: None
  5907. """
  5908. self.app_cursor.enabled = False
  5909. if val == 'small':
  5910. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(False)
  5911. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(False)
  5912. self.app_cursor = self.plotcanvas.new_cursor()
  5913. else:
  5914. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(True)
  5915. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(True)
  5916. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  5917. if self.ui.grid_snap_btn.isChecked():
  5918. self.app_cursor.enabled = True
  5919. else:
  5920. self.app_cursor.enabled = False
  5921. def on_cnc_custom_parameters(self, signal_text):
  5922. if signal_text == 'Parameters':
  5923. return
  5924. else:
  5925. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  5926. def on_save_button(self):
  5927. log.debug("App.on_save_button() --> Saving preferences to file.")
  5928. self.preferences_changed_flag = False
  5929. self.save_defaults(silent=False)
  5930. # load the defaults so they are updated into the app
  5931. self.load_defaults(filename='current_defaults')
  5932. # Re-fresh project options
  5933. self.on_options_app2project()
  5934. settings = QSettings("Open Source", "FlatCAM")
  5935. # save the notebook font size
  5936. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  5937. settings.setValue('notebook_font_size', fsize)
  5938. # save the axis font size
  5939. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  5940. settings.setValue('axis_font_size', g_fsize)
  5941. # save the textbox font size
  5942. tb_fsize = self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  5943. settings.setValue('textbox_font_size', tb_fsize)
  5944. # This will write the setting to the platform specific storage.
  5945. del settings
  5946. def on_tool_add_keypress(self):
  5947. # ## Current application units in Upper Case
  5948. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5949. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5950. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5951. if notebook_widget_name == 'selected_tab':
  5952. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5953. # Tool add works for Geometry only if Advanced is True in Preferences
  5954. if self.defaults["global_app_level"] == 'a':
  5955. tool_add_popup = FCInputDialog(title="New Tool ...",
  5956. text='Enter a Tool Diameter:',
  5957. min=0.0000, max=99.9999, decimals=4)
  5958. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5959. val, ok = tool_add_popup.get_value()
  5960. if ok:
  5961. if float(val) == 0:
  5962. self.inform.emit('[WARNING_NOTCL] %s' %
  5963. _("Please enter a tool diameter with non-zero value, in Float format."))
  5964. return
  5965. self.collection.get_active().on_tool_add(dia=float(val))
  5966. else:
  5967. self.inform.emit('[WARNING_NOTCL] %s...' %
  5968. _("Adding Tool cancelled"))
  5969. else:
  5970. msgbox = QtWidgets.QMessageBox()
  5971. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5972. "Go to Preferences -> General - Show Advanced Options."))
  5973. msgbox.setWindowTitle("Tool adding ...")
  5974. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  5975. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5976. msgbox.setDefaultButton(bt_ok)
  5977. msgbox.exec_()
  5978. # work only if the notebook tab on focus is the Tools_Tab
  5979. if notebook_widget_name == 'tool_tab':
  5980. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5981. # and only if the tool is NCC Tool
  5982. if tool_widget == self.ncclear_tool.toolName:
  5983. self.ncclear_tool.on_add_tool_by_key()
  5984. # and only if the tool is Paint Area Tool
  5985. elif tool_widget == self.paint_tool.toolName:
  5986. self.paint_tool.on_add_tool_by_key()
  5987. # and only if the tool is Solder Paste Dispensing Tool
  5988. elif tool_widget == self.paste_tool.toolName:
  5989. self.paste_tool.on_add_tool_by_key()
  5990. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5991. # See description bellow.
  5992. def on_delete_keypress(self):
  5993. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5994. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5995. if notebook_widget_name == 'selected_tab':
  5996. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5997. self.collection.get_active().on_tool_delete()
  5998. # work only if the notebook tab on focus is the Tools_Tab
  5999. elif notebook_widget_name == 'tool_tab':
  6000. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  6001. # and only if the tool is NCC Tool
  6002. if tool_widget == self.ncclear_tool.toolName:
  6003. self.ncclear_tool.on_tool_delete()
  6004. # and only if the tool is Paint Tool
  6005. elif tool_widget == self.paint_tool.toolName:
  6006. self.paint_tool.on_tool_delete()
  6007. # and only if the tool is Solder Paste Dispensing Tool
  6008. elif tool_widget == self.paste_tool.toolName:
  6009. self.paste_tool.on_tool_delete()
  6010. else:
  6011. self.on_delete()
  6012. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  6013. # some screens you have to be careful where you hover with your mouse.
  6014. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  6015. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  6016. # Complicated, I know :)
  6017. def on_delete(self):
  6018. """
  6019. Delete the currently selected FlatCAMObjs.
  6020. :return: None
  6021. """
  6022. self.report_usage("on_delete()")
  6023. response = None
  6024. bt_ok = None
  6025. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  6026. # a geometry object before we update it.
  6027. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  6028. and self.grb_editor.editor_active is False:
  6029. if self.defaults["global_delete_confirmation"] is True:
  6030. msgbox = QtWidgets.QMessageBox()
  6031. msgbox.setWindowTitle(_("Delete objects"))
  6032. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  6033. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  6034. msgbox.setText(_("Are you sure you want to permanently delete\n"
  6035. "the selected objects?"))
  6036. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6037. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6038. msgbox.setDefaultButton(bt_ok)
  6039. msgbox.exec_()
  6040. response = msgbox.clickedButton()
  6041. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  6042. if self.collection.get_active():
  6043. self.log.debug("App.on_delete()")
  6044. while self.collection.get_active():
  6045. obj_active = self.collection.get_active()
  6046. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  6047. if isinstance(obj_active, FlatCAMGerber):
  6048. for el in obj_active.mark_shapes:
  6049. obj_active.mark_shapes[el].clear(update=True)
  6050. obj_active.mark_shapes[el].enabled = False
  6051. # obj_active.mark_shapes[el] = None
  6052. del el
  6053. elif isinstance(obj_active, FlatCAMCNCjob):
  6054. try:
  6055. obj_active.annotation.clear(update=True)
  6056. obj_active.annotation.enabled = False
  6057. except AttributeError:
  6058. pass
  6059. self.delete_first_selected()
  6060. self.inform.emit('%s...' %
  6061. _("Object(s) deleted"))
  6062. # make sure that the selection shape is deleted, too
  6063. self.delete_selection_shape()
  6064. else:
  6065. self.inform.emit(_("Failed. No object(s) selected..."))
  6066. else:
  6067. self.inform.emit(_("Save the work in Editor and try again ..."))
  6068. def delete_first_selected(self):
  6069. # Keep this for later
  6070. try:
  6071. sel_obj = self.collection.get_active()
  6072. name = sel_obj.options["name"]
  6073. isPlotted = sel_obj.options["plot"]
  6074. except AttributeError:
  6075. self.log.debug("Nothing selected for deletion")
  6076. return
  6077. if self.is_legacy is True:
  6078. # Remove plot only if the object was plotted otherwise delaxes will fail
  6079. if isPlotted:
  6080. try:
  6081. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  6082. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  6083. except Exception as e:
  6084. log.debug("App.delete_first_selected() --> %s" % str(e))
  6085. self.plotcanvas.auto_adjust_axes()
  6086. # Remove from dictionary
  6087. self.collection.delete_active()
  6088. # Clear form
  6089. self.setup_component_editor()
  6090. self.inform.emit('%s: %s' %
  6091. (_("Object deleted"), name))
  6092. def on_set_origin(self):
  6093. """
  6094. Set the origin to the left mouse click position
  6095. :return: None
  6096. """
  6097. # display the message for the user
  6098. # and ask him to click on the desired position
  6099. self.report_usage("on_set_origin()")
  6100. def origin_replot():
  6101. def worker_task():
  6102. with self.proc_container.new('%s...' % _("Plotting")):
  6103. for obj in self.collection.get_list():
  6104. obj.plot()
  6105. self.plotcanvas.fit_view()
  6106. if self.is_legacy:
  6107. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  6108. else:
  6109. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  6110. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6111. self.inform.emit(_('Click to set the origin ...'))
  6112. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  6113. # first disconnect it as it may have been used by something else
  6114. try:
  6115. self.replot_signal.disconnect()
  6116. except TypeError:
  6117. pass
  6118. self.replot_signal[list].connect(origin_replot)
  6119. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  6120. """
  6121. :param event:
  6122. :param location:
  6123. :param noplot:
  6124. :param use_thread:
  6125. :return:
  6126. """
  6127. noplot_sig = noplot
  6128. def worker_task():
  6129. with self.proc_container.new(_("Setting Origin...")):
  6130. for obj in self.collection.get_list():
  6131. obj.offset((x, y))
  6132. self.object_changed.emit(obj)
  6133. # Update the object bounding box options
  6134. a, b, c, d = obj.bounds()
  6135. obj.options['xmin'] = a
  6136. obj.options['ymin'] = b
  6137. obj.options['xmax'] = c
  6138. obj.options['ymax'] = d
  6139. self.inform.emit('[success] %s...' %
  6140. _('Origin set'))
  6141. if noplot_sig is False:
  6142. self.replot_signal.emit([])
  6143. if location is not None:
  6144. if len(location) != 2:
  6145. self.inform.emit('[ERROR_NOTCL] %s...' %
  6146. _("Origin coordinates specified but incomplete."))
  6147. return 'fail'
  6148. x, y = location
  6149. if use_thread is True:
  6150. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6151. else:
  6152. worker_task()
  6153. self.should_we_save = True
  6154. return
  6155. if event.button == 1:
  6156. if self.is_legacy is False:
  6157. event_pos = event.pos
  6158. else:
  6159. event_pos = (event.xdata, event.ydata)
  6160. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6161. if self.grid_status() == True:
  6162. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6163. else:
  6164. pos = pos_canvas
  6165. x = 0 - pos[0]
  6166. y = 0 - pos[1]
  6167. if use_thread is True:
  6168. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6169. else:
  6170. worker_task()
  6171. self.should_we_save = True
  6172. def on_jump_to(self, custom_location=None, fit_center=True):
  6173. """
  6174. Jump to a location by setting the mouse cursor location
  6175. :return:
  6176. """
  6177. self.report_usage("on_jump_to()")
  6178. # if self.is_legacy is True:
  6179. # self.inform.emit(_("Not available with the current Graphic Engine Legacy(2D)."))
  6180. # return
  6181. if not custom_location:
  6182. dia_box_location = None
  6183. try:
  6184. dia_box_location = eval(self.clipboard.text())
  6185. except Exception as e:
  6186. pass
  6187. if type(dia_box_location) == tuple:
  6188. dia_box_location = str(dia_box_location)
  6189. else:
  6190. dia_box_location = None
  6191. dia_box = Dialog_box(title=_("Jump to ..."),
  6192. label=_("Enter the coordinates in format X,Y:"),
  6193. icon=QtGui.QIcon('share/jump_to16.png'),
  6194. initial_text=dia_box_location)
  6195. if dia_box.ok is True:
  6196. try:
  6197. location = eval(dia_box.location)
  6198. if not isinstance(location, tuple):
  6199. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  6200. return
  6201. except:
  6202. return
  6203. else:
  6204. return
  6205. else:
  6206. location = custom_location
  6207. if fit_center:
  6208. self.plotcanvas.fit_center(loc=location)
  6209. cursor = QtGui.QCursor()
  6210. if self.is_legacy is False:
  6211. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6212. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  6213. j_pos = (canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  6214. cursor.setPos(j_pos[0], j_pos[1])
  6215. else:
  6216. # find the canvas origin which is in the top left corner
  6217. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6218. # determine the coordinates for the lowest left point of the canvas
  6219. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  6220. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  6221. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  6222. # canvas) and the point (width, height) is in the top-right location
  6223. loc = self.plotcanvas.axes.transData.transform_point(location)
  6224. j_pos = (x0 + loc[0], y0 - loc[1])
  6225. cursor.setPos(j_pos[0], j_pos[1])
  6226. if self.grid_status() == True:
  6227. # Update cursor
  6228. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  6229. symbol='++', edge_color=self.cursor_color_3D,
  6230. size=self.defaults["global_cursor_size"])
  6231. # Set the position label
  6232. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6233. "<b>Y</b>: %.4f" % (location[0], location[1]))
  6234. # Set the relative position label
  6235. dx = location[0] - float(self.rel_point1[0])
  6236. dy = location[1] - float(self.rel_point1[1])
  6237. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6238. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6239. self.inform.emit('[success] %s' %
  6240. _("Done."))
  6241. return location
  6242. def on_copy_object(self):
  6243. self.report_usage("on_copy_object()")
  6244. def initialize(obj_init, app):
  6245. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6246. try:
  6247. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  6248. except AttributeError:
  6249. pass
  6250. try:
  6251. obj_init.apertures = deepcopy(obj.apertures)
  6252. except AttributeError:
  6253. pass
  6254. try:
  6255. if obj.tools:
  6256. obj_init.tools = deepcopy(obj.tools)
  6257. except Exception as e:
  6258. log.debug("App.on_copy_object() --> %s" % str(e))
  6259. def initialize_excellon(obj_init, app):
  6260. obj_init.tools = deepcopy(obj.tools)
  6261. # drills are offset, so they need to be deep copied
  6262. obj_init.drills = deepcopy(obj.drills)
  6263. # slots are offset, so they need to be deep copied
  6264. obj_init.slots = deepcopy(obj.slots)
  6265. obj_init.create_geometry()
  6266. def initialize_script(obj_init, app_obj):
  6267. obj_init.source_file = deepcopy(obj.source_file)
  6268. def initialize_document(obj_init, app_obj):
  6269. obj_init.source_file = deepcopy(obj.source_file)
  6270. for obj in self.collection.get_selected():
  6271. obj_name = obj.options["name"]
  6272. try:
  6273. if isinstance(obj, FlatCAMExcellon):
  6274. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  6275. elif isinstance(obj, FlatCAMGerber):
  6276. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  6277. elif isinstance(obj, FlatCAMGeometry):
  6278. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  6279. elif isinstance(obj, FlatCAMScript):
  6280. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  6281. elif isinstance(obj, FlatCAMDocument):
  6282. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  6283. except Exception as e:
  6284. return "Operation failed: %s" % str(e)
  6285. def on_copy_object2(self, custom_name):
  6286. def initialize_geometry(obj_init, app):
  6287. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6288. try:
  6289. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  6290. except AttributeError:
  6291. pass
  6292. try:
  6293. obj_init.apertures = deepcopy(obj.apertures)
  6294. except AttributeError:
  6295. pass
  6296. try:
  6297. if obj.tools:
  6298. obj_init.tools = deepcopy(obj.tools)
  6299. except Exception as e:
  6300. log.debug("on_copy_object2() --> %s" % str(e))
  6301. def initialize_gerber(obj_init, app):
  6302. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6303. obj_init.apertures = deepcopy(obj.apertures)
  6304. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  6305. def initialize_excellon(obj_init, app):
  6306. obj_init.tools = deepcopy(obj.tools)
  6307. # drills are offset, so they need to be deep copied
  6308. obj_init.drills = deepcopy(obj.drills)
  6309. # slots are offset, so they need to be deep copied
  6310. obj_init.slots = deepcopy(obj.slots)
  6311. obj_init.create_geometry()
  6312. for obj in self.collection.get_selected():
  6313. obj_name = obj.options["name"]
  6314. try:
  6315. if isinstance(obj, FlatCAMExcellon):
  6316. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  6317. elif isinstance(obj, FlatCAMGerber):
  6318. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  6319. elif isinstance(obj, FlatCAMGeometry):
  6320. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  6321. except Exception as e:
  6322. return "Operation failed: %s" % str(e)
  6323. def on_rename_object(self, text):
  6324. self.report_usage("on_rename_object()")
  6325. named_obj = self.collection.get_active()
  6326. for obj in named_obj:
  6327. if obj is list:
  6328. self.on_rename_object(text)
  6329. else:
  6330. try:
  6331. obj.options['name'] = text
  6332. except Exception as e:
  6333. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  6334. def convert_any2geo(self):
  6335. self.report_usage("convert_any2geo()")
  6336. def initialize(obj_init, app):
  6337. obj_init.solid_geometry = obj.solid_geometry
  6338. try:
  6339. obj_init.follow_geometry = obj.follow_geometry
  6340. except AttributeError:
  6341. pass
  6342. try:
  6343. obj_init.apertures = obj.apertures
  6344. except AttributeError:
  6345. pass
  6346. try:
  6347. if obj.tools:
  6348. obj_init.tools = obj.tools
  6349. except AttributeError:
  6350. pass
  6351. def initialize_excellon(obj_init, app):
  6352. # objs = self.collection.get_selected()
  6353. # FlatCAMGeometry.merge(objs, obj)
  6354. solid_geo = []
  6355. for tool in obj.tools:
  6356. for geo in obj.tools[tool]['solid_geometry']:
  6357. solid_geo.append(geo)
  6358. obj_init.solid_geometry = deepcopy(solid_geo)
  6359. if not self.collection.get_selected():
  6360. log.warning("App.convert_any2geo --> No object selected")
  6361. self.inform.emit('[WARNING_NOTCL] %s' %
  6362. _("No object is selected. Select an object and try again."))
  6363. return
  6364. for obj in self.collection.get_selected():
  6365. obj_name = obj.options["name"]
  6366. try:
  6367. if isinstance(obj, FlatCAMExcellon):
  6368. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  6369. else:
  6370. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  6371. except Exception as e:
  6372. return "Operation failed: %s" % str(e)
  6373. def convert_any2gerber(self):
  6374. self.report_usage("convert_any2gerber()")
  6375. def initialize_geometry(obj_init, app):
  6376. apertures = {}
  6377. apid = 0
  6378. apertures[str(apid)] = {}
  6379. apertures[str(apid)]['geometry'] = []
  6380. for obj_orig in obj.solid_geometry:
  6381. new_elem = dict()
  6382. new_elem['solid'] = obj_orig
  6383. try:
  6384. new_elem['follow'] = obj_orig.exterior
  6385. except AttributeError:
  6386. pass
  6387. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  6388. apertures[str(apid)]['size'] = 0.0
  6389. apertures[str(apid)]['type'] = 'C'
  6390. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6391. obj_init.apertures = deepcopy(apertures)
  6392. def initialize_excellon(obj_init, app):
  6393. apertures = {}
  6394. apid = 10
  6395. for tool in obj.tools:
  6396. apertures[str(apid)] = {}
  6397. apertures[str(apid)]['geometry'] = []
  6398. for geo in obj.tools[tool]['solid_geometry']:
  6399. new_el = dict()
  6400. new_el['solid'] = geo
  6401. new_el['follow'] = geo.exterior
  6402. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  6403. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  6404. apertures[str(apid)]['type'] = 'C'
  6405. apid += 1
  6406. # create solid_geometry
  6407. solid_geometry = []
  6408. for apid in apertures:
  6409. for geo_el in apertures[apid]['geometry']:
  6410. solid_geometry.append(geo_el['solid'])
  6411. solid_geometry = MultiPolygon(solid_geometry)
  6412. solid_geometry = solid_geometry.buffer(0.0000001)
  6413. obj_init.solid_geometry = deepcopy(solid_geometry)
  6414. obj_init.apertures = deepcopy(apertures)
  6415. # clear the working objects (perhaps not necessary due of Python GC)
  6416. apertures.clear()
  6417. if not self.collection.get_selected():
  6418. log.warning("App.convert_any2gerber --> No object selected")
  6419. self.inform.emit('[WARNING_NOTCL] %s' %
  6420. _("No object is selected. Select an object and try again."))
  6421. return
  6422. for obj in self.collection.get_selected():
  6423. obj_name = obj.options["name"]
  6424. try:
  6425. if isinstance(obj, FlatCAMExcellon):
  6426. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  6427. elif isinstance(obj, FlatCAMGeometry):
  6428. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  6429. else:
  6430. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  6431. except Exception as e:
  6432. return "Operation failed: %s" % str(e)
  6433. def abort_all_tasks(self):
  6434. if self.abort_flag is False:
  6435. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  6436. self.abort_flag = True
  6437. def app_is_idle(self):
  6438. if self.abort_flag:
  6439. self.inform.emit('[WARNING_NOTCL] %s' %
  6440. _("The current task was gracefully closed on user request..."))
  6441. self.abort_flag = False
  6442. def on_selectall(self):
  6443. self.report_usage("on_selectall()")
  6444. # delete the possible selection box around a possible selected object
  6445. self.delete_selection_shape()
  6446. for name in self.collection.get_names():
  6447. self.collection.set_active(name)
  6448. curr_sel_obj = self.collection.get_by_name(name)
  6449. # create the selection box around the selected object
  6450. if self.defaults['global_selection_shape'] is True:
  6451. self.draw_selection_shape(curr_sel_obj)
  6452. def on_preferences(self):
  6453. # add the tab if it was closed
  6454. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  6455. # delete the absolute and relative position and messages in the infobar
  6456. self.ui.position_label.setText("")
  6457. self.ui.rel_position_label.setText("")
  6458. # Switch plot_area to preferences page
  6459. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  6460. # self.ui.show()
  6461. # detect changes in the preferences
  6462. for idx in range(self.ui.pref_tab_area.count()):
  6463. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6464. try:
  6465. try:
  6466. tb.textEdited.disconnect(self.on_preferences_edited)
  6467. except (TypeError, AttributeError):
  6468. pass
  6469. tb.textEdited.connect(self.on_preferences_edited)
  6470. except AttributeError:
  6471. pass
  6472. try:
  6473. try:
  6474. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6475. except (TypeError, AttributeError):
  6476. pass
  6477. tb.modificationChanged.connect(self.on_preferences_edited)
  6478. except AttributeError:
  6479. pass
  6480. try:
  6481. try:
  6482. tb.toggled.disconnect(self.on_preferences_edited)
  6483. except (TypeError, AttributeError):
  6484. pass
  6485. tb.toggled.connect(self.on_preferences_edited)
  6486. except AttributeError:
  6487. pass
  6488. try:
  6489. try:
  6490. tb.valueChanged.disconnect(self.on_preferences_edited)
  6491. except (TypeError, AttributeError):
  6492. pass
  6493. tb.valueChanged.connect(self.on_preferences_edited)
  6494. except AttributeError:
  6495. pass
  6496. try:
  6497. try:
  6498. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6499. except (TypeError, AttributeError):
  6500. pass
  6501. tb.currentIndexChanged.connect(self.on_preferences_edited)
  6502. except AttributeError:
  6503. pass
  6504. def on_preferences_edited(self):
  6505. self.inform.emit('[WARNING_NOTCL] %s' %
  6506. _("Preferences edited but not saved."))
  6507. self.preferences_changed_flag = True
  6508. def on_plot_area_tab_closed(self, title):
  6509. if title == _("Preferences"):
  6510. # disconnect
  6511. for idx in range(self.ui.pref_tab_area.count()):
  6512. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6513. try:
  6514. tb.textEdited.disconnect(self.on_preferences_edited)
  6515. except (TypeError, AttributeError):
  6516. pass
  6517. try:
  6518. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6519. except (TypeError, AttributeError):
  6520. pass
  6521. try:
  6522. tb.toggled.disconnect(self.on_preferences_edited)
  6523. except (TypeError, AttributeError):
  6524. pass
  6525. try:
  6526. tb.valueChanged.disconnect(self.on_preferences_edited)
  6527. except (TypeError, AttributeError):
  6528. pass
  6529. try:
  6530. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6531. except (TypeError, AttributeError):
  6532. pass
  6533. if self.preferences_changed_flag is True:
  6534. msgbox = QtWidgets.QMessageBox()
  6535. msgbox.setText(_("One or more values are changed.\n"
  6536. "Do you want to save the Preferences?"))
  6537. msgbox.setWindowTitle(_("Save Preferences"))
  6538. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6539. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6540. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6541. msgbox.setDefaultButton(bt_yes)
  6542. msgbox.exec_()
  6543. response = msgbox.clickedButton()
  6544. if response == bt_yes:
  6545. self.on_save_button()
  6546. self.inform.emit('[success] %s' %
  6547. _("Preferences saved."))
  6548. else:
  6549. self.preferences_changed_flag = False
  6550. return
  6551. if title == _("Code Editor"):
  6552. self.toggle_codeeditor = False
  6553. if title == _("Bookmarks Manager"):
  6554. self.book_dialog_tab.rebuild_actions()
  6555. self.book_dialog_tab.deleteLater()
  6556. def on_flipy(self):
  6557. self.report_usage("on_flipy()")
  6558. obj_list = self.collection.get_selected()
  6559. xminlist = []
  6560. yminlist = []
  6561. xmaxlist = []
  6562. ymaxlist = []
  6563. if not obj_list:
  6564. self.inform.emit('[WARNING_NOTCL] %s' %
  6565. _("No object selected to Flip on Y axis."))
  6566. else:
  6567. try:
  6568. # first get a bounding box to fit all
  6569. for obj in obj_list:
  6570. xmin, ymin, xmax, ymax = obj.bounds()
  6571. xminlist.append(xmin)
  6572. yminlist.append(ymin)
  6573. xmaxlist.append(xmax)
  6574. ymaxlist.append(ymax)
  6575. # get the minimum x,y and maximum x,y for all objects selected
  6576. xminimal = min(xminlist)
  6577. yminimal = min(yminlist)
  6578. xmaximal = max(xmaxlist)
  6579. ymaximal = max(ymaxlist)
  6580. px = 0.5 * (xminimal + xmaximal)
  6581. py = 0.5 * (yminimal + ymaximal)
  6582. # execute mirroring
  6583. for obj in obj_list:
  6584. obj.mirror('X', [px, py])
  6585. obj.plot()
  6586. self.object_changed.emit(obj)
  6587. self.inform.emit('[success] %s' %
  6588. _("Flip on Y axis done."))
  6589. except Exception as e:
  6590. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6591. (_("Flip action was not executed."), str(e)))
  6592. return
  6593. def on_flipx(self):
  6594. self.report_usage("on_flipx()")
  6595. obj_list = self.collection.get_selected()
  6596. xminlist = []
  6597. yminlist = []
  6598. xmaxlist = []
  6599. ymaxlist = []
  6600. if not obj_list:
  6601. self.inform.emit('[WARNING_NOTCL] %s' %
  6602. _("No object selected to Flip on X axis."))
  6603. else:
  6604. try:
  6605. # first get a bounding box to fit all
  6606. for obj in obj_list:
  6607. xmin, ymin, xmax, ymax = obj.bounds()
  6608. xminlist.append(xmin)
  6609. yminlist.append(ymin)
  6610. xmaxlist.append(xmax)
  6611. ymaxlist.append(ymax)
  6612. # get the minimum x,y and maximum x,y for all objects selected
  6613. xminimal = min(xminlist)
  6614. yminimal = min(yminlist)
  6615. xmaximal = max(xmaxlist)
  6616. ymaximal = max(ymaxlist)
  6617. px = 0.5 * (xminimal + xmaximal)
  6618. py = 0.5 * (yminimal + ymaximal)
  6619. # execute mirroring
  6620. for obj in obj_list:
  6621. obj.mirror('Y', [px, py])
  6622. obj.plot()
  6623. self.object_changed.emit(obj)
  6624. self.inform.emit('[success] %s' %
  6625. _("Flip on X axis done."))
  6626. except Exception as e:
  6627. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6628. (_("Flip action was not executed."), str(e)))
  6629. return
  6630. def on_rotate(self, silent=False, preset=None):
  6631. self.report_usage("on_rotate()")
  6632. obj_list = self.collection.get_selected()
  6633. xminlist = []
  6634. yminlist = []
  6635. xmaxlist = []
  6636. ymaxlist = []
  6637. if not obj_list:
  6638. self.inform.emit('[WARNING_NOTCL] %s' %
  6639. _("No object selected to Rotate."))
  6640. else:
  6641. if silent is False:
  6642. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6643. min=-360, max=360, decimals=4,
  6644. init_val=float(self.defaults['tools_transform_rotate']))
  6645. num, ok = rotatebox.get_value()
  6646. else:
  6647. num = preset
  6648. ok = True
  6649. if ok:
  6650. try:
  6651. # first get a bounding box to fit all
  6652. for obj in obj_list:
  6653. xmin, ymin, xmax, ymax = obj.bounds()
  6654. xminlist.append(xmin)
  6655. yminlist.append(ymin)
  6656. xmaxlist.append(xmax)
  6657. ymaxlist.append(ymax)
  6658. # get the minimum x,y and maximum x,y for all objects selected
  6659. xminimal = min(xminlist)
  6660. yminimal = min(yminlist)
  6661. xmaximal = max(xmaxlist)
  6662. ymaximal = max(ymaxlist)
  6663. px = 0.5 * (xminimal + xmaximal)
  6664. py = 0.5 * (yminimal + ymaximal)
  6665. for sel_obj in obj_list:
  6666. sel_obj.rotate(-float(num), point=(px, py))
  6667. sel_obj.plot()
  6668. self.object_changed.emit(sel_obj)
  6669. self.inform.emit('[success] %s' %
  6670. _("Rotation done."))
  6671. except Exception as e:
  6672. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6673. (_("Rotation movement was not executed."), str(e)))
  6674. return
  6675. def on_skewx(self):
  6676. self.report_usage("on_skewx()")
  6677. obj_list = self.collection.get_selected()
  6678. xminlist = []
  6679. yminlist = []
  6680. if not obj_list:
  6681. self.inform.emit('[WARNING_NOTCL] %s' %
  6682. _("No object selected to Skew/Shear on X axis."))
  6683. else:
  6684. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6685. min=-360, max=360, decimals=4,
  6686. init_val=float(self.defaults['tools_transform_skew_x']))
  6687. num, ok = skewxbox.get_value()
  6688. if ok:
  6689. # first get a bounding box to fit all
  6690. for obj in obj_list:
  6691. xmin, ymin, xmax, ymax = obj.bounds()
  6692. xminlist.append(xmin)
  6693. yminlist.append(ymin)
  6694. # get the minimum x,y and maximum x,y for all objects selected
  6695. xminimal = min(xminlist)
  6696. yminimal = min(yminlist)
  6697. for obj in obj_list:
  6698. obj.skew(num, 0, point=(xminimal, yminimal))
  6699. obj.plot()
  6700. self.object_changed.emit(obj)
  6701. self.inform.emit('[success] %s' %
  6702. _("Skew on X axis done."))
  6703. def on_skewy(self):
  6704. self.report_usage("on_skewy()")
  6705. obj_list = self.collection.get_selected()
  6706. xminlist = []
  6707. yminlist = []
  6708. if not obj_list:
  6709. self.inform.emit('[WARNING_NOTCL] %s' %
  6710. _("No object selected to Skew/Shear on Y axis."))
  6711. else:
  6712. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6713. min=-360, max=360, decimals=4,
  6714. init_val=float(self.defaults['tools_transform_skew_y']))
  6715. num, ok = skewybox.get_value()
  6716. if ok:
  6717. # first get a bounding box to fit all
  6718. for obj in obj_list:
  6719. xmin, ymin, xmax, ymax = obj.bounds()
  6720. xminlist.append(xmin)
  6721. yminlist.append(ymin)
  6722. # get the minimum x,y and maximum x,y for all objects selected
  6723. xminimal = min(xminlist)
  6724. yminimal = min(yminlist)
  6725. for obj in obj_list:
  6726. obj.skew(0, num, point=(xminimal, yminimal))
  6727. obj.plot()
  6728. self.object_changed.emit(obj)
  6729. self.inform.emit('[success] %s' %
  6730. _("Skew on Y axis done."))
  6731. def on_plots_updated(self):
  6732. """
  6733. Callback used to report when the plots have changed.
  6734. Adjust axes and zooms to fit.
  6735. :return: None
  6736. """
  6737. if self.is_legacy is False:
  6738. self.plotcanvas.update() # TODO: Need update canvas?
  6739. else:
  6740. self.plotcanvas.auto_adjust_axes()
  6741. self.on_zoom_fit(None)
  6742. self.collection.update_view()
  6743. # self.inform.emit(_("Plots updated ..."))
  6744. # TODO: Rework toolbar 'clear', 'replot' functions
  6745. def on_toolbar_replot(self):
  6746. """
  6747. Callback for toolbar button. Re-plots all objects.
  6748. :return: None
  6749. """
  6750. self.report_usage("on_toolbar_replot")
  6751. self.log.debug("on_toolbar_replot()")
  6752. try:
  6753. self.collection.get_active().read_form()
  6754. except AttributeError:
  6755. self.log.debug("on_toolbar_replot(): AttributeError")
  6756. pass
  6757. self.plot_all()
  6758. def on_row_activated(self, index):
  6759. if index.isValid():
  6760. if index.internalPointer().parent_item != self.collection.root_item:
  6761. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6762. self.collection.on_item_activated(index)
  6763. def on_row_selected(self, obj_name):
  6764. # this is a special string; when received it will make all entries unchecked
  6765. # it mean we clicked outside of the items and deselected all
  6766. if obj_name =='none':
  6767. for act in self.ui.menuobjects.actions():
  6768. act.setChecked(False)
  6769. return
  6770. # get the name of the selected objects and add them to a list
  6771. name_list = list()
  6772. for obj in self.collection.get_selected():
  6773. name_list.append(obj.options['name'])
  6774. # set all actions as unchecked but the ones selected make them checked
  6775. for act in self.ui.menuobjects.actions():
  6776. act.setChecked(False)
  6777. if act.text() in name_list:
  6778. act.setChecked(True)
  6779. def on_collection_updated(self, obj, state, old_name):
  6780. """
  6781. Create a menu from the object loaded in the collection.
  6782. TODO: should use the collection model to do this
  6783. :param obj: object that was changd (added, deleted, renamed)
  6784. :param state: what was done with the objectCand be: added, deleted, delete_all, renamed
  6785. :param old_name: the old name of the object before the action that triggered this slot happened
  6786. :return: None
  6787. """
  6788. icon_files = {
  6789. "gerber": "share/flatcam_icon16.png",
  6790. "excellon": "share/drill16.png",
  6791. "cncjob": "share/cnc16.png",
  6792. "geometry": "share/geometry16.png",
  6793. "script": "share/script_new16.png",
  6794. "document": "share/notes16_1.png"
  6795. }
  6796. if state == 'append':
  6797. for act in self.ui.menuobjects.actions():
  6798. try:
  6799. act.triggered.disconnect()
  6800. except TypeError:
  6801. pass
  6802. self.ui.menuobjects.clear()
  6803. gerber_list = list()
  6804. exc_list = list()
  6805. cncjob_list = list()
  6806. geo_list = list()
  6807. script_list = list()
  6808. doc_list = list()
  6809. for name in self.collection.get_names():
  6810. obj_named = self.collection.get_by_name(name)
  6811. if obj_named.kind == 'gerber':
  6812. gerber_list.append(name)
  6813. elif obj_named.kind == 'excellon':
  6814. exc_list.append(name)
  6815. elif obj_named.kind == 'cncjob':
  6816. cncjob_list.append(name)
  6817. elif obj_named.kind == 'geometry':
  6818. geo_list.append(name)
  6819. elif obj_named.kind == 'script':
  6820. script_list.append(name)
  6821. elif obj_named.kind == 'document':
  6822. doc_list.append(name)
  6823. def add_act(name):
  6824. obj_for_icon = self.collection.get_by_name(name)
  6825. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6826. add_action.setCheckable(True)
  6827. add_action.setText(name)
  6828. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  6829. add_action.triggered.connect(
  6830. lambda: self.collection.set_active(name) if add_action.isChecked() is True else
  6831. self.collection.set_inactive(name))
  6832. self.ui.menuobjects.addAction(add_action)
  6833. for name in gerber_list:
  6834. add_act(name)
  6835. self.ui.menuobjects.addSeparator()
  6836. for name in exc_list:
  6837. add_act(name)
  6838. self.ui.menuobjects.addSeparator()
  6839. for name in cncjob_list:
  6840. add_act(name)
  6841. self.ui.menuobjects.addSeparator()
  6842. for name in geo_list:
  6843. add_act(name)
  6844. self.ui.menuobjects.addSeparator()
  6845. for name in script_list:
  6846. add_act(name)
  6847. self.ui.menuobjects.addSeparator()
  6848. for name in doc_list:
  6849. add_act(name)
  6850. self.ui.menuobjects.addSeparator()
  6851. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  6852. QtGui.QIcon('share/select_all.png'),
  6853. _('Select All')
  6854. )
  6855. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  6856. QtGui.QIcon('share/deselect_all32.png'),
  6857. _('Deselect All')
  6858. )
  6859. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  6860. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  6861. elif state == 'delete':
  6862. for act in self.ui.menuobjects.actions():
  6863. if act.text() == obj.options['name']:
  6864. try:
  6865. act.triggered.disconnect()
  6866. except TypeError:
  6867. pass
  6868. self.ui.menuobjects.removeAction(act)
  6869. break
  6870. elif state == 'rename':
  6871. for act in self.ui.menuobjects.actions():
  6872. if act.text() == old_name:
  6873. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6874. add_action.setText(obj.options['name'])
  6875. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  6876. add_action.triggered.connect(
  6877. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  6878. self.collection.set_inactive(obj.options['name']))
  6879. self.ui.menuobjects.insertAction(act, add_action)
  6880. try:
  6881. act.triggered.disconnect()
  6882. except TypeError:
  6883. pass
  6884. self.ui.menuobjects.removeAction(act)
  6885. break
  6886. elif state =='delete_all':
  6887. for act in self.ui.menuobjects.actions():
  6888. try:
  6889. act.triggered.disconnect()
  6890. except TypeError:
  6891. pass
  6892. self.ui.menuobjects.clear()
  6893. self.ui.menuobjects.addSeparator()
  6894. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  6895. QtGui.QIcon('share/select_all.png'),
  6896. _('Select All')
  6897. )
  6898. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  6899. QtGui.QIcon('share/deselect_all32.png'),
  6900. _('Deselect All')
  6901. )
  6902. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  6903. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  6904. def on_objects_selection(self, on_off):
  6905. obj_list = self.collection.get_names()
  6906. if on_off is True:
  6907. self.collection.set_all_active()
  6908. for act in self.ui.menuobjects.actions():
  6909. try:
  6910. act.setChecked(True)
  6911. except:
  6912. pass
  6913. if obj_list:
  6914. self.inform.emit('[selected] %s' % _("All objects are selected."))
  6915. else:
  6916. self.collection.set_all_inactive()
  6917. for act in self.ui.menuobjects.actions():
  6918. try:
  6919. act.setChecked(False)
  6920. except:
  6921. pass
  6922. self.inform.emit('%s' % _("Objects selection is cleared."))
  6923. def grid_status(self):
  6924. if self.ui.grid_snap_btn.isChecked():
  6925. return True
  6926. else:
  6927. return False
  6928. def populate_cmenu_grids(self):
  6929. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6930. self.ui.cmenu_gridmenu.clear()
  6931. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  6932. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  6933. grid_toggle.setCheckable(True)
  6934. if self.grid_status() == True:
  6935. grid_toggle.setChecked(True)
  6936. else:
  6937. grid_toggle.setChecked(False)
  6938. self.ui.cmenu_gridmenu.addSeparator()
  6939. for grid in sorted_list:
  6940. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  6941. action.triggered.connect(self.set_grid)
  6942. self.ui.cmenu_gridmenu.addSeparator()
  6943. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  6944. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  6945. grid_add.triggered.connect(self.on_grid_add)
  6946. grid_delete.triggered.connect(self.on_grid_delete)
  6947. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  6948. def set_grid(self):
  6949. self.ui.grid_gap_x_entry.setText(self.sender().text())
  6950. self.ui.grid_gap_y_entry.setText(self.sender().text())
  6951. def on_grid_add(self):
  6952. # ## Current application units in lower Case
  6953. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6954. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  6955. text=_('Enter a Grid Value:'),
  6956. min=0.0000, max=99.9999, decimals=4)
  6957. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  6958. val, ok = grid_add_popup.get_value()
  6959. if ok:
  6960. if float(val) == 0:
  6961. self.inform.emit('[WARNING_NOTCL] %s' %
  6962. _("Please enter a grid value with non-zero value, in Float format."))
  6963. return
  6964. else:
  6965. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  6966. self.defaults["global_grid_context_menu"][str(units)].append(val)
  6967. self.inform.emit('[success] %s...' %
  6968. _("New Grid added"))
  6969. else:
  6970. self.inform.emit('[WARNING_NOTCL] %s...' %
  6971. _("Grid already exists"))
  6972. else:
  6973. self.inform.emit('[WARNING_NOTCL] %s...' %
  6974. _("Adding New Grid cancelled"))
  6975. def on_grid_delete(self):
  6976. # ## Current application units in lower Case
  6977. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6978. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  6979. text='Enter a Grid Value:',
  6980. min=0.0000, max=99.9999, decimals=4)
  6981. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  6982. val, ok = grid_del_popup.get_value()
  6983. if ok:
  6984. if float(val) == 0:
  6985. self.inform.emit('[WARNING_NOTCL] %s' %
  6986. _("Please enter a grid value with non-zero value, in Float format."))
  6987. return
  6988. else:
  6989. try:
  6990. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  6991. except ValueError:
  6992. self.inform.emit('[ERROR_NOTCL]%s...' %
  6993. _(" Grid Value does not exist"))
  6994. return
  6995. self.inform.emit('[success] %s...' %
  6996. _("Grid Value deleted"))
  6997. else:
  6998. self.inform.emit('[WARNING_NOTCL] %s...' %
  6999. _("Delete Grid value cancelled"))
  7000. def on_shortcut_list(self):
  7001. self.report_usage("on_shortcut_list()")
  7002. # add the tab if it was closed
  7003. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  7004. # delete the absolute and relative position and messages in the infobar
  7005. self.ui.position_label.setText("")
  7006. self.ui.rel_position_label.setText("")
  7007. # Switch plot_area to preferences page
  7008. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  7009. # self.ui.show()
  7010. def on_select_tab(self, name):
  7011. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  7012. if self.ui.splitter.sizes()[0] == 0:
  7013. self.ui.splitter.setSizes([1, 1])
  7014. else:
  7015. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  7016. self.ui.splitter.setSizes([0, 1])
  7017. if name == 'project':
  7018. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7019. elif name == 'selected':
  7020. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  7021. elif name == 'tool':
  7022. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  7023. def on_copy_name(self):
  7024. self.report_usage("on_copy_name()")
  7025. obj = self.collection.get_active()
  7026. try:
  7027. name = obj.options["name"]
  7028. except AttributeError:
  7029. log.debug("on_copy_name() --> No object selected to copy it's name")
  7030. self.inform.emit('[WARNING_NOTCL]%s' %
  7031. _(" No object selected to copy it's name"))
  7032. return
  7033. self.clipboard.setText(name)
  7034. self.inform.emit(_("Name copied on clipboard ..."))
  7035. def on_mouse_click_over_plot(self, event):
  7036. """
  7037. Default actions are:
  7038. :param event: Contains information about the event, like which button
  7039. was clicked, the pixel coordinates and the axes coordinates.
  7040. :return: None
  7041. """
  7042. self.pos = []
  7043. if self.is_legacy is False:
  7044. event_pos = event.pos
  7045. if self.defaults["global_pan_button"] == '2':
  7046. pan_button = 2
  7047. else:
  7048. pan_button = 3
  7049. # Set the mouse button for panning
  7050. self.plotcanvas.view.camera.pan_button_setting = pan_button
  7051. else:
  7052. event_pos = (event.xdata, event.ydata)
  7053. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7054. if self.defaults["global_pan_button"] == '2':
  7055. pan_button = 3
  7056. else:
  7057. pan_button = 2
  7058. # So it can receive key presses
  7059. self.plotcanvas.native.setFocus()
  7060. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7061. if self.grid_status() == True:
  7062. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  7063. else:
  7064. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  7065. try:
  7066. if event.button == 1:
  7067. # Reset here the relative coordinates so there is a new reference on the click position
  7068. if self.rel_point1 is None:
  7069. self.rel_point1 = self.pos
  7070. else:
  7071. self.rel_point2 = copy(self.rel_point1)
  7072. self.rel_point1 = self.pos
  7073. self.on_mouse_move_over_plot(event, origin_click=True)
  7074. except Exception as e:
  7075. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  7076. def on_mouse_double_click_over_plot(self, event):
  7077. if event.button == 1:
  7078. self.doubleclick = True
  7079. def on_mouse_move_over_plot(self, event, origin_click=None):
  7080. """
  7081. Callback for the mouse motion event over the plot.
  7082. :param event: Contains information about the event.
  7083. :param origin_click
  7084. :return: None
  7085. """
  7086. if self.is_legacy is False:
  7087. event_pos = event.pos
  7088. if self.defaults["global_pan_button"] == '2':
  7089. pan_button = 2
  7090. else:
  7091. pan_button = 3
  7092. event_is_dragging = event.is_dragging
  7093. else:
  7094. event_pos = (event.xdata, event.ydata)
  7095. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7096. if self.defaults["global_pan_button"] == '2':
  7097. pan_button = 3
  7098. else:
  7099. pan_button = 2
  7100. event_is_dragging = self.plotcanvas.is_dragging
  7101. # So it can receive key presses
  7102. self.plotcanvas.native.setFocus()
  7103. self.pos_jump = event_pos
  7104. self.ui.popMenu.mouse_is_panning = False
  7105. if not origin_click:
  7106. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  7107. if event.button == pan_button and event_is_dragging == 1:
  7108. self.ui.popMenu.mouse_is_panning = True
  7109. return
  7110. if self.rel_point1 is not None:
  7111. try: # May fail in case mouse not within axes
  7112. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7113. if self.grid_status() == True:
  7114. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  7115. # Update cursor
  7116. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  7117. symbol='++', edge_color=self.cursor_color_3D,
  7118. size=self.defaults["global_cursor_size"])
  7119. else:
  7120. pos = (pos_canvas[0], pos_canvas[1])
  7121. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  7122. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  7123. dx = pos[0] - float(self.rel_point1[0])
  7124. dy = pos[1] - float(self.rel_point1[1])
  7125. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  7126. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  7127. self.mouse = [pos[0], pos[1]]
  7128. # if the mouse is moved and the LMB is clicked then the action is a selection
  7129. if event_is_dragging == 1 and event.button == 1:
  7130. self.delete_selection_shape()
  7131. if dx < 0:
  7132. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  7133. face_color=self.defaults['global_alt_sel_fill'])
  7134. self.selection_type = False
  7135. elif dx > 0:
  7136. self.draw_moving_selection_shape(self.pos, pos)
  7137. self.selection_type = True
  7138. else:
  7139. self.selection_type = None
  7140. # hover effect - enabled in Preferences -> General -> GUI Settings
  7141. if self.defaults['global_hover']:
  7142. for obj in self.collection.get_list():
  7143. try:
  7144. # select the object(s) only if it is enabled (plotted)
  7145. if obj.options['plot']:
  7146. if obj not in self.collection.get_selected():
  7147. poly_obj = Polygon(
  7148. [(obj.options['xmin'], obj.options['ymin']),
  7149. (obj.options['xmax'], obj.options['ymin']),
  7150. (obj.options['xmax'], obj.options['ymax']),
  7151. (obj.options['xmin'], obj.options['ymax'])]
  7152. )
  7153. if Point(pos).within(poly_obj):
  7154. if obj.isHovering is False:
  7155. obj.isHovering = True
  7156. obj.notHovering = True
  7157. # create the selection box around the selected object
  7158. self.draw_hover_shape(obj, color='#d1e0e0FF')
  7159. else:
  7160. if obj.notHovering is True:
  7161. obj.notHovering = False
  7162. obj.isHovering = False
  7163. self.delete_hover_shape()
  7164. except:
  7165. # the Exception here will happen if we try to select on screen and we have an
  7166. # newly (and empty) just created Geometry or Excellon object that do not have the
  7167. # xmin, xmax, ymin, ymax options.
  7168. # In this case poly_obj creation (see above) will fail
  7169. pass
  7170. except:
  7171. self.ui.position_label.setText("")
  7172. self.ui.rel_position_label.setText("")
  7173. self.mouse = None
  7174. def on_mouse_click_release_over_plot(self, event):
  7175. """
  7176. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  7177. and has been registered in ''self.__init__()''.
  7178. :param event: contains information about the event.
  7179. :return:
  7180. """
  7181. pos = 0, 0
  7182. if self.is_legacy is False:
  7183. event_pos = event.pos
  7184. right_button = 2
  7185. else:
  7186. event_pos = (event.xdata, event.ydata)
  7187. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7188. right_button = 3
  7189. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7190. if self.grid_status() == True:
  7191. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  7192. else:
  7193. pos = (pos_canvas[0], pos_canvas[1])
  7194. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  7195. # canvas menu
  7196. if event.button == right_button: # right click
  7197. if self.ui.popMenu.mouse_is_panning is False:
  7198. self.cursor = QtGui.QCursor()
  7199. self.populate_cmenu_grids()
  7200. self.ui.popMenu.popup(self.cursor.pos())
  7201. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  7202. # selection and then select a type of selection ("enclosing" or "touching")
  7203. try:
  7204. if event.button == 1: # left click
  7205. modifiers = QtWidgets.QApplication.keyboardModifiers()
  7206. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  7207. if modifiers == QtCore.Qt.ShiftModifier:
  7208. # do not auto open the Project Tab
  7209. self.click_noproject = True
  7210. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  7211. self.inform.emit('[success] %s' %
  7212. _("Coordinates copied to clipboard."))
  7213. return
  7214. if self.doubleclick is True:
  7215. self.doubleclick = False
  7216. if self.collection.get_selected():
  7217. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  7218. if self.ui.splitter.sizes()[0] == 0:
  7219. self.ui.splitter.setSizes([1, 1])
  7220. # delete the selection shape(S) as it may be in the way
  7221. self.delete_selection_shape()
  7222. self.delete_hover_shape()
  7223. else:
  7224. if self.selection_type is not None:
  7225. self.selection_area_handler(self.pos, pos, self.selection_type)
  7226. self.selection_type = None
  7227. else:
  7228. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  7229. if key_modifier == QtCore.Qt.ShiftModifier:
  7230. mod_key = 'Shift'
  7231. elif key_modifier == QtCore.Qt.ControlModifier:
  7232. mod_key = 'Control'
  7233. else:
  7234. mod_key = None
  7235. if mod_key == self.defaults["global_mselect_key"]:
  7236. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  7237. # deselect, and if it's not selected then it will be selected
  7238. # If there is no active command (self.command_active is None) then we check if we clicked
  7239. # on a object by checking the bounding limits against mouse click position
  7240. if self.command_active is None:
  7241. self.select_objects(key='CTRL')
  7242. self.delete_hover_shape()
  7243. else:
  7244. # If there is no active command (self.command_active is None) then we check if we clicked
  7245. # on a object by checking the bounding limits against mouse click position
  7246. if self.command_active is None:
  7247. self.select_objects()
  7248. self.delete_hover_shape()
  7249. except Exception as e:
  7250. log.warning("Error: %s" % str(e))
  7251. return
  7252. def selection_area_handler(self, start_pos, end_pos, sel_type):
  7253. """
  7254. :param start_pos: mouse position when the selection LMB click was done
  7255. :param end_pos: mouse position when the left mouse button is released
  7256. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  7257. :return:
  7258. """
  7259. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  7260. # delete previous selection shape
  7261. self.delete_selection_shape()
  7262. # make all objects inactive
  7263. self.collection.set_all_inactive()
  7264. for obj in self.collection.get_list():
  7265. try:
  7266. # select the object(s) only if it is enabled (plotted)
  7267. if obj.options['plot']:
  7268. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  7269. (obj.options['xmax'], obj.options['ymin']),
  7270. (obj.options['xmax'], obj.options['ymax']),
  7271. (obj.options['xmin'], obj.options['ymax'])])
  7272. if sel_type is True:
  7273. if poly_obj.within(poly_selection):
  7274. # create the selection box around the selected object
  7275. if self.defaults['global_selection_shape'] is True:
  7276. self.draw_selection_shape(obj)
  7277. self.collection.set_active(obj.options['name'])
  7278. else:
  7279. if poly_selection.intersects(poly_obj):
  7280. # create the selection box around the selected object
  7281. if self.defaults['global_selection_shape'] is True:
  7282. self.draw_selection_shape(obj)
  7283. self.collection.set_active(obj.options['name'])
  7284. except Exception as e:
  7285. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  7286. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  7287. # In this case poly_obj creation (see above) will fail
  7288. log.debug("App.selection_area_handler() --> %s" % str(e))
  7289. def select_objects(self, key=None):
  7290. # list where we store the overlapped objects under our mouse left click position
  7291. objects_under_the_click_list = []
  7292. # Populate the list with the overlapped objects on the click position
  7293. curr_x, curr_y = self.pos
  7294. for obj in self.all_objects_list:
  7295. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  7296. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  7297. if obj.options['name'] not in objects_under_the_click_list:
  7298. if obj.options['plot']:
  7299. # add objects to the objects_under_the_click list only if the object is plotted
  7300. # (active and not disabled)
  7301. objects_under_the_click_list.append(obj.options['name'])
  7302. try:
  7303. if objects_under_the_click_list:
  7304. curr_sel_obj = self.collection.get_active()
  7305. # case when there is only an object under the click and we toggle it
  7306. if len(objects_under_the_click_list) == 1:
  7307. if curr_sel_obj is None:
  7308. self.collection.set_active(objects_under_the_click_list[0])
  7309. curr_sel_obj = self.collection.get_active()
  7310. # create the selection box around the selected object
  7311. if self.defaults['global_selection_shape'] is True:
  7312. self.draw_selection_shape(curr_sel_obj)
  7313. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  7314. self.on_objects_selection(False)
  7315. self.delete_selection_shape()
  7316. self.collection.set_active(objects_under_the_click_list[0])
  7317. curr_sel_obj = self.collection.get_active()
  7318. # create the selection box around the selected object
  7319. if self.defaults['global_selection_shape'] is True:
  7320. self.draw_selection_shape(curr_sel_obj)
  7321. self.selected_message(curr_sel_obj=curr_sel_obj)
  7322. else:
  7323. self.on_objects_selection(False)
  7324. self.delete_selection_shape()
  7325. if self.call_source != 'app':
  7326. self.call_source = 'app'
  7327. self.selected_message(curr_sel_obj=curr_sel_obj)
  7328. else:
  7329. # If there is no selected object
  7330. # make active the first element of the overlapped objects list
  7331. if self.collection.get_active() is None:
  7332. self.collection.set_active(objects_under_the_click_list[0])
  7333. name_sel_obj = self.collection.get_active().options['name']
  7334. # In case that there is a selected object but it is not in the overlapped object list
  7335. # make that object inactive and activate the first element in the overlapped object list
  7336. if name_sel_obj not in objects_under_the_click_list:
  7337. self.collection.set_inactive(name_sel_obj)
  7338. name_sel_obj = objects_under_the_click_list[0]
  7339. self.collection.set_active(name_sel_obj)
  7340. else:
  7341. sel_idx = objects_under_the_click_list.index(name_sel_obj)
  7342. self.collection.set_all_inactive()
  7343. self.collection.set_active(objects_under_the_click_list[(sel_idx + 1) %
  7344. len(objects_under_the_click_list)])
  7345. curr_sel_obj = self.collection.get_active()
  7346. # delete the possible selection box around a possible selected object
  7347. self.delete_selection_shape()
  7348. # create the selection box around the selected object
  7349. if self.defaults['global_selection_shape'] is True:
  7350. self.draw_selection_shape(curr_sel_obj)
  7351. self.selected_message(curr_sel_obj=curr_sel_obj)
  7352. else:
  7353. # deselect everything
  7354. self.on_objects_selection(False)
  7355. # delete the possible selection box around a possible selected object
  7356. self.delete_selection_shape()
  7357. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  7358. # only when working on App
  7359. if self.call_source == 'app':
  7360. if self.click_noproject is False:
  7361. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7362. else:
  7363. # restore auto open the Project Tab
  7364. self.click_noproject = False
  7365. # delete any text in the status bar, implicitly the last object name that was selected
  7366. # self.inform.emit("")
  7367. else:
  7368. self.call_source = 'app'
  7369. except Exception as e:
  7370. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  7371. def selected_message(self, curr_sel_obj):
  7372. if curr_sel_obj:
  7373. if curr_sel_obj.kind == 'gerber':
  7374. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7375. color='green', name=str(curr_sel_obj.options['name'])))
  7376. elif curr_sel_obj.kind == 'excellon':
  7377. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7378. color='brown', name=str(curr_sel_obj.options['name'])))
  7379. elif curr_sel_obj.kind == 'cncjob':
  7380. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7381. color='blue', name=str(curr_sel_obj.options['name'])))
  7382. elif curr_sel_obj.kind == 'geometry':
  7383. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7384. color='red', name=str(curr_sel_obj.options['name'])))
  7385. def delete_hover_shape(self):
  7386. self.hover_shapes.clear()
  7387. self.hover_shapes.redraw()
  7388. def draw_hover_shape(self, sel_obj, color=None):
  7389. """
  7390. :param sel_obj: the object for which the hover shape must be drawn
  7391. :return:
  7392. """
  7393. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7394. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7395. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7396. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7397. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  7398. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  7399. hover_rect = hover_rect.buffer(-0.1)
  7400. hover_rect = hover_rect.buffer(0.2)
  7401. else:
  7402. hover_rect = hover_rect.buffer(-0.00393)
  7403. hover_rect = hover_rect.buffer(0.00787)
  7404. # if color:
  7405. # face = Color(color)
  7406. # face.alpha = 0.2
  7407. # outline = Color(color, alpha=0.8)
  7408. # else:
  7409. # face = Color(self.defaults['global_sel_fill'])
  7410. # face.alpha = 0.2
  7411. # outline = self.defaults['global_sel_line']
  7412. if color:
  7413. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7414. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7415. else:
  7416. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7417. outline = self.defaults['global_sel_line']
  7418. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  7419. if self.is_legacy is True:
  7420. self.hover_shapes.redraw()
  7421. def delete_selection_shape(self):
  7422. self.move_tool.sel_shapes.clear()
  7423. self.move_tool.sel_shapes.redraw()
  7424. def draw_selection_shape(self, sel_obj, color=None):
  7425. """
  7426. :param sel_obj: the object for which the selection shape must be drawn
  7427. :return:
  7428. """
  7429. if sel_obj is None:
  7430. return
  7431. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7432. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7433. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7434. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7435. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7436. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  7437. sel_rect = sel_rect.buffer(-0.1)
  7438. sel_rect = sel_rect.buffer(0.2)
  7439. else:
  7440. sel_rect = sel_rect.buffer(-0.00393)
  7441. sel_rect = sel_rect.buffer(0.00787)
  7442. if color:
  7443. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7444. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7445. else:
  7446. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7447. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  7448. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  7449. color=outline,
  7450. face_color=face,
  7451. update=True,
  7452. layer=0,
  7453. tolerance=None))
  7454. if self.is_legacy is True:
  7455. self.move_tool.sel_shapes.redraw()
  7456. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  7457. """
  7458. :param old_coords: old coordinates
  7459. :param coords: new coordinates
  7460. :return:
  7461. """
  7462. if 'color' in kwargs:
  7463. color = kwargs['color']
  7464. else:
  7465. color = self.defaults['global_sel_line']
  7466. if 'face_color' in kwargs:
  7467. face_color = kwargs['face_color']
  7468. else:
  7469. face_color = self.defaults['global_sel_fill']
  7470. if 'face_alpha' in kwargs:
  7471. face_alpha = kwargs['face_alpha']
  7472. else:
  7473. face_alpha = 0.3
  7474. x0, y0 = old_coords
  7475. x1, y1 = coords
  7476. pt1 = (x0, y0)
  7477. pt2 = (x1, y0)
  7478. pt3 = (x1, y1)
  7479. pt4 = (x0, y1)
  7480. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7481. # color_t = Color(face_color)
  7482. # color_t.alpha = face_alpha
  7483. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  7484. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  7485. layer=0, tolerance=None)
  7486. if self.is_legacy is True:
  7487. self.move_tool.sel_shapes.redraw()
  7488. def on_file_new_click(self):
  7489. if self.collection.get_list() and self.should_we_save:
  7490. msgbox = QtWidgets.QMessageBox()
  7491. # msgbox.setText("<B>Save changes ...</B>")
  7492. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7493. "Creating a New project will delete them.\n"
  7494. "Do you want to Save the project?"))
  7495. msgbox.setWindowTitle(_("Save changes"))
  7496. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  7497. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7498. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7499. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7500. msgbox.setDefaultButton(bt_yes)
  7501. msgbox.exec_()
  7502. response = msgbox.clickedButton()
  7503. if response == bt_yes:
  7504. self.on_file_saveprojectas()
  7505. elif response == bt_cancel:
  7506. return
  7507. elif response == bt_no:
  7508. self.on_file_new()
  7509. else:
  7510. self.on_file_new()
  7511. self.inform.emit('[success] %s...' %
  7512. _("New Project created"))
  7513. def on_file_new(self, cli=None):
  7514. """
  7515. Callback for menu item File->New. Returns the application to its
  7516. startup state. This method is thread-safe.
  7517. :return: None
  7518. """
  7519. self.report_usage("on_file_new")
  7520. # Remove everything from memory
  7521. App.log.debug("on_file_new()")
  7522. if self.call_source != 'app':
  7523. self.editor2object(cleanup=True)
  7524. # ## EDITOR section
  7525. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  7526. self.exc_editor = FlatCAMExcEditor(self)
  7527. self.grb_editor = FlatCAMGrbEditor(self)
  7528. # Clear pool
  7529. self.clear_pool()
  7530. for obj in self.collection.get_list():
  7531. # delete shapes left drawn from mark shape_collections, if any
  7532. if isinstance(obj, FlatCAMGerber):
  7533. try:
  7534. obj.mark_shapes.enabled = False
  7535. obj.mark_shapes.clear(update=True)
  7536. except AttributeError:
  7537. pass
  7538. # also delete annotation shapes, if any
  7539. elif isinstance(obj, FlatCAMCNCjob):
  7540. try:
  7541. obj.annotation.enabled = False
  7542. obj.annotation.clear(update=True)
  7543. except AttributeError:
  7544. pass
  7545. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7546. self.init_tcl()
  7547. self.delete_selection_shape()
  7548. self.collection.delete_all()
  7549. self.setup_component_editor()
  7550. # Clear project filename
  7551. self.project_filename = None
  7552. # Load the application defaults
  7553. self.load_defaults(filename='current_defaults')
  7554. # Re-fresh project options
  7555. self.on_options_app2project()
  7556. # Init Tools
  7557. self.init_tools()
  7558. if cli is None:
  7559. # Close any Tabs opened in the Plot Tab Area section
  7560. for index in range(self.ui.plot_tab_area.count()):
  7561. self.ui.plot_tab_area.closeTab(index)
  7562. # for whatever reason previous command does not close the last tab so I do it manually
  7563. self.ui.plot_tab_area.closeTab(0)
  7564. # # And then add again the Plot Area
  7565. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  7566. self.ui.plot_tab_area.protectTab(0)
  7567. # take the focus of the Notebook on Project Tab.
  7568. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7569. self.set_ui_title(name=_("New Project - Not saved"))
  7570. def obj_properties(self):
  7571. self.report_usage("obj_properties()")
  7572. self.properties_tool.run(toggle=False)
  7573. def on_project_context_save(self):
  7574. obj = self.collection.get_active()
  7575. if type(obj) == FlatCAMGeometry:
  7576. self.on_file_exportdxf()
  7577. elif type(obj) == FlatCAMExcellon:
  7578. self.on_file_saveexcellon()
  7579. elif type(obj) == FlatCAMCNCjob:
  7580. obj.on_exportgcode_button_click()
  7581. elif type(obj) == FlatCAMGerber:
  7582. self.on_file_savegerber()
  7583. elif type(obj) == FlatCAMScript:
  7584. self.on_file_savescript()
  7585. elif type(obj) == FlatCAMDocument:
  7586. self.on_file_savedocument()
  7587. def obj_move(self):
  7588. self.report_usage("obj_move()")
  7589. self.move_tool.run(toggle=False)
  7590. def on_fileopengerber(self, checked=None, name=None):
  7591. """
  7592. File menu callback for opening a Gerber.
  7593. :return: None
  7594. """
  7595. self.report_usage("on_fileopengerber")
  7596. App.log.debug("on_fileopengerber()")
  7597. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  7598. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  7599. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  7600. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  7601. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  7602. "*.mil);;" \
  7603. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  7604. "Allegro Files (*.art);;" \
  7605. "Mentor Files (*.pho *.gdo);;" \
  7606. "All Files (*.*)"
  7607. if name is None:
  7608. try:
  7609. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  7610. directory=self.get_last_folder(),
  7611. filter=_filter_)
  7612. except TypeError:
  7613. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  7614. filenames = [str(filename) for filename in filenames]
  7615. else:
  7616. filenames = [name]
  7617. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7618. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7619. _("Opening Gerber file.")),
  7620. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7621. color=QtGui.QColor("gray"))
  7622. if len(filenames) == 0:
  7623. self.inform.emit('[WARNING_NOTCL] %s' %
  7624. _("Open Gerber cancelled."))
  7625. else:
  7626. for filename in filenames:
  7627. if filename != '':
  7628. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  7629. def on_fileopenexcellon(self, checked=None, name=None):
  7630. """
  7631. File menu callback for opening an Excellon file.
  7632. :return: None
  7633. """
  7634. self.report_usage("on_fileopenexcellon")
  7635. App.log.debug("on_fileopenexcellon()")
  7636. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  7637. "All Files (*.*)"
  7638. if name is None:
  7639. try:
  7640. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  7641. directory=self.get_last_folder(),
  7642. filter=_filter_)
  7643. except TypeError:
  7644. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  7645. filenames = [str(filename) for filename in filenames]
  7646. else:
  7647. filenames = [str(name)]
  7648. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7649. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7650. _("Opening Excellon file.")),
  7651. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7652. color=QtGui.QColor("gray"))
  7653. if len(filenames) == 0:
  7654. self.inform.emit('[WARNING_NOTCL]%s' %
  7655. _(" Open Excellon cancelled."))
  7656. else:
  7657. for filename in filenames:
  7658. if filename != '':
  7659. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  7660. def on_fileopengcode(self, checked=None, name=None):
  7661. """
  7662. File menu call back for opening gcode.
  7663. :return: None
  7664. """
  7665. self.report_usage("on_fileopengcode")
  7666. App.log.debug("on_fileopengcode()")
  7667. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  7668. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  7669. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  7670. "All Files (*.*)"
  7671. if name is None:
  7672. try:
  7673. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  7674. directory=self.get_last_folder(),
  7675. filter=_filter_)
  7676. except TypeError:
  7677. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  7678. filenames = [str(filename) for filename in filenames]
  7679. else:
  7680. filenames = [name]
  7681. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7682. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7683. _("Opening G-Code file.")),
  7684. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7685. color=QtGui.QColor("gray"))
  7686. if len(filenames) == 0:
  7687. self.inform.emit('[WARNING_NOTCL] %s' %
  7688. _("Open G-Code cancelled."))
  7689. else:
  7690. for filename in filenames:
  7691. if filename != '':
  7692. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  7693. def on_file_openproject(self, checked=None):
  7694. """
  7695. File menu callback for opening a project.
  7696. :return: None
  7697. """
  7698. self.report_usage("on_file_openproject")
  7699. App.log.debug("on_file_openproject()")
  7700. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  7701. try:
  7702. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  7703. directory=self.get_last_folder(), filter=_filter_)
  7704. except TypeError:
  7705. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  7706. # The Qt methods above will return a QString which can cause problems later.
  7707. # So far json.dump() will fail to serialize it.
  7708. # TODO: Improve the serialization methods and remove this fix.
  7709. filename = str(filename)
  7710. if filename == "":
  7711. self.inform.emit('[WARNING_NOTCL] %s' %
  7712. _("Open Project cancelled."))
  7713. else:
  7714. # self.worker_task.emit({'fcn': self.open_project,
  7715. # 'params': [filename]})
  7716. # The above was failing because open_project() is not
  7717. # thread safe. The new_project()
  7718. self.open_project(filename)
  7719. def on_file_openconfig(self, checked=None):
  7720. """
  7721. File menu callback for opening a config file.
  7722. :return: None
  7723. """
  7724. self.report_usage("on_file_openconfig")
  7725. App.log.debug("on_file_openconfig()")
  7726. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  7727. try:
  7728. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7729. directory=self.data_path, filter=_filter_)
  7730. except TypeError:
  7731. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7732. filter=_filter_)
  7733. if filename == "":
  7734. self.inform.emit('[WARNING_NOTCL] %s' %
  7735. _("Open Config cancelled."))
  7736. else:
  7737. self.open_config_file(filename)
  7738. def on_file_exportsvg(self):
  7739. """
  7740. Callback for menu item File->Export SVG.
  7741. :return: None
  7742. """
  7743. self.report_usage("on_file_exportsvg")
  7744. App.log.debug("on_file_exportsvg()")
  7745. obj = self.collection.get_active()
  7746. if obj is None:
  7747. self.inform.emit('[WARNING_NOTCL] %s' %
  7748. _("No object selected."))
  7749. msg = _("Please Select a Geometry object to export")
  7750. msgbox = QtWidgets.QMessageBox()
  7751. msgbox.setInformativeText(msg)
  7752. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7753. msgbox.setDefaultButton(bt_ok)
  7754. msgbox.exec_()
  7755. return
  7756. # Check for more compatible types and add as required
  7757. if (not isinstance(obj, FlatCAMGeometry)
  7758. and not isinstance(obj, FlatCAMGerber)
  7759. and not isinstance(obj, FlatCAMCNCjob)
  7760. and not isinstance(obj, FlatCAMExcellon)):
  7761. msg = '[ERROR_NOTCL] %s' % \
  7762. _("Only Geometry, Gerber and CNCJob objects can be used.")
  7763. msgbox = QtWidgets.QMessageBox()
  7764. msgbox.setInformativeText(msg)
  7765. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7766. msgbox.setDefaultButton(bt_ok)
  7767. msgbox.exec_()
  7768. return
  7769. name = obj.options["name"]
  7770. _filter = "SVG File (*.svg);;All Files (*.*)"
  7771. try:
  7772. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7773. caption=_("Export SVG"),
  7774. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  7775. filter=_filter)
  7776. except TypeError:
  7777. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  7778. filename = str(filename)
  7779. if filename == "":
  7780. self.inform.emit('[WARNING_NOTCL]%s' %
  7781. _(" Export SVG cancelled."))
  7782. return
  7783. else:
  7784. self.export_svg(name, filename)
  7785. if self.defaults["global_open_style"] is False:
  7786. self.file_opened.emit("SVG", filename)
  7787. self.file_saved.emit("SVG", filename)
  7788. def on_file_exportpng(self):
  7789. self.report_usage("on_file_exportpng")
  7790. App.log.debug("on_file_exportpng()")
  7791. self.date = str(datetime.today()).rpartition('.')[0]
  7792. self.date = ''.join(c for c in self.date if c not in ':-')
  7793. self.date = self.date.replace(' ', '_')
  7794. if self.is_legacy is False:
  7795. image = _screenshot()
  7796. data = np.asarray(image)
  7797. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  7798. self.inform.emit('[[WARNING_NOTCL]] %s' %
  7799. _('Data must be a 3D array with last dimension 3 or 4'))
  7800. return
  7801. filter_ = "PNG File (*.png);;All Files (*.*)"
  7802. try:
  7803. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7804. caption=_("Export PNG Image"),
  7805. directory=self.get_last_save_folder() + '/png_' + self.date,
  7806. filter=filter_)
  7807. except TypeError:
  7808. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  7809. filename = str(filename)
  7810. if filename == "":
  7811. self.inform.emit(_("Export PNG cancelled."))
  7812. return
  7813. else:
  7814. if self.is_legacy is False:
  7815. write_png(filename, data)
  7816. else:
  7817. self.plotcanvas.figure.savefig(filename)
  7818. if self.defaults["global_open_style"] is False:
  7819. self.file_opened.emit("png", filename)
  7820. self.file_saved.emit("png", filename)
  7821. def on_file_savegerber(self):
  7822. """
  7823. Callback for menu item in Project context menu.
  7824. :return: None
  7825. """
  7826. self.report_usage("on_file_savegerber")
  7827. App.log.debug("on_file_savegerber()")
  7828. obj = self.collection.get_active()
  7829. if obj is None:
  7830. self.inform.emit('[WARNING_NOTCL] %s' %
  7831. _("No object selected. Please select an Gerber object to export."))
  7832. return
  7833. # Check for more compatible types and add as required
  7834. if not isinstance(obj, FlatCAMGerber):
  7835. self.inform.emit('[ERROR_NOTCL] %s' %
  7836. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7837. return
  7838. name = self.collection.get_active().options["name"]
  7839. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  7840. try:
  7841. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7842. caption="Save Gerber source file",
  7843. directory=self.get_last_save_folder() + '/' + name,
  7844. filter=_filter)
  7845. except TypeError:
  7846. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  7847. filename = str(filename)
  7848. if filename == "":
  7849. self.inform.emit('[WARNING_NOTCL] %s' %
  7850. _("Save Gerber source file cancelled."))
  7851. return
  7852. else:
  7853. self.save_source_file(name, filename)
  7854. if self.defaults["global_open_style"] is False:
  7855. self.file_opened.emit("Gerber", filename)
  7856. self.file_saved.emit("Gerber", filename)
  7857. def on_file_savescript(self):
  7858. """
  7859. Callback for menu item in Project context menu.
  7860. :return: None
  7861. """
  7862. self.report_usage("on_file_savescript")
  7863. App.log.debug("on_file_savescript()")
  7864. obj = self.collection.get_active()
  7865. if obj is None:
  7866. self.inform.emit('[WARNING_NOTCL] %s' %
  7867. _("No object selected. Please select an Script object to export."))
  7868. return
  7869. # Check for more compatible types and add as required
  7870. if not isinstance(obj, FlatCAMScript):
  7871. self.inform.emit('[ERROR_NOTCL] %s' %
  7872. _("Failed. Only Script objects can be saved as TCL Script files..."))
  7873. return
  7874. name = self.collection.get_active().options["name"]
  7875. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  7876. try:
  7877. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7878. caption="Save Script source file",
  7879. directory=self.get_last_save_folder() + '/' + name,
  7880. filter=_filter)
  7881. except TypeError:
  7882. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Script source file"), filter=_filter)
  7883. filename = str(filename)
  7884. if filename == "":
  7885. self.inform.emit('[WARNING_NOTCL] %s' %
  7886. _("Save Script source file cancelled."))
  7887. return
  7888. else:
  7889. self.save_source_file(name, filename)
  7890. if self.defaults["global_open_style"] is False:
  7891. self.file_opened.emit("Script", filename)
  7892. self.file_saved.emit("Script", filename)
  7893. def on_file_savedocument(self):
  7894. """
  7895. Callback for menu item in Project context menu.
  7896. :return: None
  7897. """
  7898. self.report_usage("on_file_savedocument")
  7899. App.log.debug("on_file_savedocument()")
  7900. obj = self.collection.get_active()
  7901. if obj is None:
  7902. self.inform.emit('[WARNING_NOTCL] %s' %
  7903. _("No object selected. Please select an Document object to export."))
  7904. return
  7905. # Check for more compatible types and add as required
  7906. if not isinstance(obj, FlatCAMScript):
  7907. self.inform.emit('[ERROR_NOTCL] %s' %
  7908. _("Failed. Only Document objects can be saved as Document files..."))
  7909. return
  7910. name = self.collection.get_active().options["name"]
  7911. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  7912. try:
  7913. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7914. caption="Save Document source file",
  7915. directory=self.get_last_save_folder() + '/' + name,
  7916. filter=_filter)
  7917. except TypeError:
  7918. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Document source file"), filter=_filter)
  7919. filename = str(filename)
  7920. if filename == "":
  7921. self.inform.emit('[WARNING_NOTCL] %s' %
  7922. _("Save Document source file cancelled."))
  7923. return
  7924. else:
  7925. self.save_source_file(name, filename)
  7926. if self.defaults["global_open_style"] is False:
  7927. self.file_opened.emit("Document", filename)
  7928. self.file_saved.emit("Document", filename)
  7929. def on_file_saveexcellon(self):
  7930. """
  7931. Callback for menu item in project context menu.
  7932. :return: None
  7933. """
  7934. self.report_usage("on_file_saveexcellon")
  7935. App.log.debug("on_file_saveexcellon()")
  7936. obj = self.collection.get_active()
  7937. if obj is None:
  7938. self.inform.emit('[WARNING_NOTCL] %s' %
  7939. _("No object selected. Please select an Excellon object to export."))
  7940. return
  7941. # Check for more compatible types and add as required
  7942. if not isinstance(obj, FlatCAMExcellon):
  7943. self.inform.emit('[ERROR_NOTCL] %s' %
  7944. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7945. return
  7946. name = self.collection.get_active().options["name"]
  7947. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7948. try:
  7949. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7950. caption=_("Save Excellon source file"),
  7951. directory=self.get_last_save_folder() + '/' + name,
  7952. filter=_filter)
  7953. except TypeError:
  7954. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  7955. filename = str(filename)
  7956. if filename == "":
  7957. self.inform.emit('[WARNING_NOTCL] %s' %
  7958. _("Saving Excellon source file cancelled."))
  7959. return
  7960. else:
  7961. self.save_source_file(name, filename)
  7962. if self.defaults["global_open_style"] is False:
  7963. self.file_opened.emit("Excellon", filename)
  7964. self.file_saved.emit("Excellon", filename)
  7965. def on_file_exportexcellon(self):
  7966. """
  7967. Callback for menu item File->Export->Excellon.
  7968. :return: None
  7969. """
  7970. self.report_usage("on_file_exportexcellon")
  7971. App.log.debug("on_file_exportexcellon()")
  7972. obj = self.collection.get_active()
  7973. if obj is None:
  7974. self.inform.emit('[WARNING_NOTCL] %s' %
  7975. _("No object selected. Please Select an Excellon object to export."))
  7976. return
  7977. # Check for more compatible types and add as required
  7978. if not isinstance(obj, FlatCAMExcellon):
  7979. self.inform.emit('[ERROR_NOTCL] %s' %
  7980. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7981. return
  7982. name = self.collection.get_active().options["name"]
  7983. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7984. try:
  7985. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7986. caption=_("Export Excellon"),
  7987. directory=self.get_last_save_folder() + '/' + name,
  7988. filter=_filter)
  7989. except TypeError:
  7990. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  7991. filename = str(filename)
  7992. if filename == "":
  7993. self.inform.emit('[WARNING_NOTCL] %s' %
  7994. _("Export Excellon cancelled."))
  7995. return
  7996. else:
  7997. self.export_excellon(name, filename)
  7998. if self.defaults["global_open_style"] is False:
  7999. self.file_opened.emit("Excellon", filename)
  8000. self.file_saved.emit("Excellon", filename)
  8001. def on_file_exportgerber(self):
  8002. """
  8003. Callback for menu item File->Export->Gerber.
  8004. :return: None
  8005. """
  8006. self.report_usage("on_file_exportgerber")
  8007. App.log.debug("on_file_exportgerber()")
  8008. obj = self.collection.get_active()
  8009. if obj is None:
  8010. self.inform.emit('[WARNING_NOTCL] %s' %
  8011. _("No object selected. Please Select an Gerber object to export."))
  8012. return
  8013. # Check for more compatible types and add as required
  8014. if not isinstance(obj, FlatCAMGerber):
  8015. self.inform.emit('[ERROR_NOTCL] %s' %
  8016. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  8017. return
  8018. name = self.collection.get_active().options["name"]
  8019. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  8020. try:
  8021. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8022. caption=_("Export Gerber"),
  8023. directory=self.get_last_save_folder() + '/' + name,
  8024. filter=_filter_)
  8025. except TypeError:
  8026. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  8027. filename = str(filename)
  8028. if filename == "":
  8029. self.inform.emit('[WARNING_NOTCL] %s' %
  8030. _("Export Gerber cancelled."))
  8031. return
  8032. else:
  8033. self.export_gerber(name, filename)
  8034. if self.defaults["global_open_style"] is False:
  8035. self.file_opened.emit("Gerber", filename)
  8036. self.file_saved.emit("Gerber", filename)
  8037. def on_file_exportdxf(self):
  8038. """
  8039. Callback for menu item File->Export DXF.
  8040. :return: None
  8041. """
  8042. self.report_usage("on_file_exportdxf")
  8043. App.log.debug("on_file_exportdxf()")
  8044. obj = self.collection.get_active()
  8045. if obj is None:
  8046. self.inform.emit('[WARNING_NOTCL] %s' %
  8047. _("No object selected."))
  8048. msg = _("Please Select a Geometry object to export")
  8049. msgbox = QtWidgets.QMessageBox()
  8050. msgbox.setInformativeText(msg)
  8051. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8052. msgbox.setDefaultButton(bt_ok)
  8053. msgbox.exec_()
  8054. return
  8055. # Check for more compatible types and add as required
  8056. if not isinstance(obj, FlatCAMGeometry):
  8057. msg = '[ERROR_NOTCL] %s' % \
  8058. _("Only Geometry objects can be used.")
  8059. msgbox = QtWidgets.QMessageBox()
  8060. msgbox.setInformativeText(msg)
  8061. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8062. msgbox.setDefaultButton(bt_ok)
  8063. msgbox.exec_()
  8064. return
  8065. name = self.collection.get_active().options["name"]
  8066. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  8067. try:
  8068. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8069. caption=_("Export DXF"),
  8070. directory=self.get_last_save_folder() + '/' + name,
  8071. filter=_filter_)
  8072. except TypeError:
  8073. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  8074. filter=_filter_)
  8075. filename = str(filename)
  8076. if filename == "":
  8077. self.inform.emit('[WARNING_NOTCL] %s' %
  8078. _("Export DXF cancelled."))
  8079. return
  8080. else:
  8081. self.export_dxf(name, filename)
  8082. if self.defaults["global_open_style"] is False:
  8083. self.file_opened.emit("DXF", filename)
  8084. self.file_saved.emit("DXF", filename)
  8085. def on_file_importsvg(self, type_of_obj):
  8086. """
  8087. Callback for menu item File->Import SVG.
  8088. :param type_of_obj: to import the SVG as Geometry or as Gerber
  8089. :type type_of_obj: str
  8090. :return: None
  8091. """
  8092. self.report_usage("on_file_importsvg")
  8093. App.log.debug("on_file_importsvg()")
  8094. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  8095. try:
  8096. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  8097. directory=self.get_last_folder(), filter=_filter_)
  8098. except TypeError:
  8099. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  8100. filter=_filter_)
  8101. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  8102. type_of_obj = "geometry"
  8103. filenames = [str(filename) for filename in filenames]
  8104. if len(filenames) == 0:
  8105. self.inform.emit('[WARNING_NOTCL] %s' %
  8106. _("Open SVG cancelled."))
  8107. else:
  8108. for filename in filenames:
  8109. if filename != '':
  8110. self.worker_task.emit({'fcn': self.import_svg,
  8111. 'params': [filename, type_of_obj]})
  8112. def on_file_importdxf(self, type_of_obj):
  8113. """
  8114. Callback for menu item File->Import DXF.
  8115. :param type_of_obj: to import the DXF as Geometry or as Gerber
  8116. :type type_of_obj: str
  8117. :return: None
  8118. """
  8119. self.report_usage("on_file_importdxf")
  8120. App.log.debug("on_file_importdxf()")
  8121. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  8122. try:
  8123. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  8124. directory=self.get_last_folder(),
  8125. filter=_filter_)
  8126. except TypeError:
  8127. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  8128. filter=_filter_)
  8129. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  8130. type_of_obj = "geometry"
  8131. filenames = [str(filename) for filename in filenames]
  8132. if len(filenames) == 0:
  8133. self.inform.emit('[WARNING_NOTCL] %s' %
  8134. _("Open DXF cancelled."))
  8135. else:
  8136. for filename in filenames:
  8137. if filename != '':
  8138. self.worker_task.emit({'fcn': self.import_dxf,
  8139. 'params': [filename, type_of_obj]})
  8140. # ###############################################################################################################
  8141. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  8142. # ###############################################################################################################
  8143. def init_code_editor(self, name):
  8144. self.text_editor_tab = TextEditor(app=self)
  8145. # add the tab if it was closed
  8146. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  8147. self.text_editor_tab.setObjectName('text_editor_tab')
  8148. # delete the absolute and relative position and messages in the infobar
  8149. self.ui.position_label.setText("")
  8150. self.ui.rel_position_label.setText("")
  8151. # first clear previous text in text editor (if any)
  8152. self.text_editor_tab.code_editor.clear()
  8153. self.text_editor_tab.code_editor.setReadOnly(False)
  8154. self.toggle_codeeditor = True
  8155. self.text_editor_tab.code_editor.completer_enable = False
  8156. self.text_editor_tab.buttonRun.hide()
  8157. # make sure to keep a reference to the code editor
  8158. self.reference_code_editor = self.text_editor_tab.code_editor
  8159. # Switch plot_area to CNCJob tab
  8160. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  8161. def on_view_source(self):
  8162. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  8163. self.proc_container.view.set_busy(_("Loading..."))
  8164. try:
  8165. obj = self.collection.get_active()
  8166. except Exception as e:
  8167. log.debug("App.on_view_source() --> %s" % str(e))
  8168. self.inform.emit('[WARNING_NOTCL] %s' %
  8169. _("Select an Gerber or Excellon file to view it's source file."))
  8170. return 'fail'
  8171. if obj is None:
  8172. self.inform.emit('[WARNING_NOTCL] %s' %
  8173. _("Select an Gerber or Excellon file to view it's source file."))
  8174. return 'fail'
  8175. flt = "All Files (*.*)"
  8176. if obj.kind == 'gerber':
  8177. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  8178. elif obj.kind == 'excellon':
  8179. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  8180. elif obj.kind == 'cncjob':
  8181. "GCode Files (*.NC);;All Files (*.*)"
  8182. self.source_editor_tab = TextEditor(app=self)
  8183. # add the tab if it was closed
  8184. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  8185. self.source_editor_tab.setObjectName('source_editor_tab')
  8186. # delete the absolute and relative position and messages in the infobar
  8187. self.ui.position_label.setText("")
  8188. self.ui.rel_position_label.setText("")
  8189. # first clear previous text in text editor (if any)
  8190. self.source_editor_tab.code_editor.clear()
  8191. self.source_editor_tab.code_editor.setReadOnly(False)
  8192. self.source_editor_tab.code_editor.completer_enable = False
  8193. self.source_editor_tab.buttonRun.hide()
  8194. # Switch plot_area to CNCJob tab
  8195. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  8196. try:
  8197. self.source_editor_tab.buttonOpen.clicked.disconnect()
  8198. except TypeError:
  8199. pass
  8200. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  8201. try:
  8202. self.source_editor_tab.buttonSave.clicked.disconnect()
  8203. except TypeError:
  8204. pass
  8205. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  8206. # then append the text from GCode to the text editor
  8207. if obj.kind == 'cncjob':
  8208. try:
  8209. file = obj.export_gcode(
  8210. preamble=self.defaults["cncjob_prepend"],
  8211. postamble=self.defaults["cncjob_append"],
  8212. to_file=True)
  8213. if file == 'fail':
  8214. return 'fail'
  8215. except AttributeError:
  8216. self.inform.emit('[WARNING_NOTCL] %s' %
  8217. _("There is no selected object for which to see it's source file code."))
  8218. return 'fail'
  8219. else:
  8220. try:
  8221. file = StringIO(obj.source_file)
  8222. except AttributeError:
  8223. self.inform.emit('[WARNING_NOTCL] %s' %
  8224. _("There is no selected object for which to see it's source file code."))
  8225. return 'fail'
  8226. self.source_editor_tab.t_frame.hide()
  8227. try:
  8228. for line in file:
  8229. QtWidgets.QApplication.processEvents()
  8230. proc_line = str(line).strip('\n')
  8231. self.source_editor_tab.code_editor.append(proc_line)
  8232. except Exception as e:
  8233. log.debug('App.on_view_source() -->%s' % str(e))
  8234. self.inform.emit('[ERROR] %s: %s' %
  8235. (_('Failed to load the source code for the selected object'), str(e)))
  8236. return
  8237. self.source_editor_tab.handleTextChanged()
  8238. self.source_editor_tab.t_frame.show()
  8239. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  8240. self.proc_container.view.set_idle()
  8241. # self.ui.show()
  8242. def on_toggle_code_editor(self):
  8243. self.report_usage("on_toggle_code_editor()")
  8244. if self.toggle_codeeditor is False:
  8245. self.init_code_editor(name=_("Code Editor"))
  8246. self.text_editor_tab.buttonOpen.clicked.disconnect()
  8247. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  8248. self.text_editor_tab.buttonSave.clicked.disconnect()
  8249. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  8250. else:
  8251. for idx in range(self.ui.plot_tab_area.count()):
  8252. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  8253. self.ui.plot_tab_area.closeTab(idx)
  8254. break
  8255. self.toggle_codeeditor = False
  8256. def on_code_editor_close(self):
  8257. print("closed")
  8258. self.toggle_codeeditor = False
  8259. def on_filenewscript(self, silent=False, name=None, text=None):
  8260. """
  8261. Will create a new script file and open it in the Code Editor
  8262. :param silent: if True will not display status messages
  8263. :return: None
  8264. """
  8265. if silent is False:
  8266. self.inform.emit('[success] %s' %
  8267. _("New TCL script file created in Code Editor."))
  8268. # delete the absolute and relative position and messages in the infobar
  8269. self.ui.position_label.setText("")
  8270. self.ui.rel_position_label.setText("")
  8271. if name is not None:
  8272. self.new_script_object(name=name, text=text)
  8273. else:
  8274. self.new_script_object(text=text)
  8275. # script_text = script_obj.source_file
  8276. #
  8277. # self.proc_container.view.set_busy(_("Loading..."))
  8278. # script_obj.script_editor_tab.t_frame.hide()
  8279. #
  8280. # script_obj.script_editor_tab.t_frame.show()
  8281. # self.proc_container.view.set_idle()
  8282. def on_fileopenscript(self, name=None, silent=False):
  8283. """
  8284. Will open a Tcl script file into the Code Editor
  8285. :param silent: if True will not display status messages
  8286. :param name: name of a Tcl script file to open
  8287. :return:
  8288. """
  8289. self.report_usage("on_fileopenscript")
  8290. App.log.debug("on_fileopenscript()")
  8291. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  8292. if name:
  8293. filenames = [name]
  8294. else:
  8295. try:
  8296. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  8297. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  8298. except TypeError:
  8299. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  8300. if len(filenames) == 0:
  8301. if silent is False:
  8302. self.inform.emit('[WARNING_NOTCL] %s' % _("Open TCL script cancelled."))
  8303. else:
  8304. for filename in filenames:
  8305. if filename != '':
  8306. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  8307. def on_filerunscript(self, name=None, silent=False):
  8308. """
  8309. File menu callback for loading and running a TCL script.
  8310. :param silent: if True will not display status messages
  8311. :param name: name of a Tcl script file to be run by FlatCAM
  8312. :return: None
  8313. """
  8314. self.report_usage("on_filerunscript")
  8315. App.log.debug("on_file_runscript()")
  8316. if name:
  8317. filename = name
  8318. if self.cmd_line_headless != 1:
  8319. self.splash.showMessage('%s: %ssec\n%s' %
  8320. (_("Canvas initialization started.\n"
  8321. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8322. _("Executing FlatCAMScript file.")
  8323. ),
  8324. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8325. color=QtGui.QColor("gray"))
  8326. else:
  8327. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  8328. try:
  8329. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  8330. directory=self.get_last_folder(), filter=_filter_)
  8331. except TypeError:
  8332. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  8333. # The Qt methods above will return a QString which can cause problems later.
  8334. # So far json.dump() will fail to serialize it.
  8335. # TODO: Improve the serialization methods and remove this fix.
  8336. filename = str(filename)
  8337. if filename == "":
  8338. if silent is False:
  8339. self.inform.emit('[WARNING_NOTCL] %s' %
  8340. _("Run TCL script cancelled."))
  8341. else:
  8342. if self.cmd_line_headless != 1:
  8343. if self.ui.shell_dock.isHidden():
  8344. self.ui.shell_dock.show()
  8345. try:
  8346. with open(filename, "r") as tcl_script:
  8347. cmd_line_shellfile_content = tcl_script.read()
  8348. if self.cmd_line_headless != 1:
  8349. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  8350. else:
  8351. self.shell._sysShell.exec_command(cmd_line_shellfile_content, no_echo=True)
  8352. if silent is False:
  8353. self.inform.emit('[success] %s' %
  8354. _("TCL script file opened in Code Editor and executed."))
  8355. except Exception as e:
  8356. log.debug("App.on_filerunscript() -> %s" % str(e))
  8357. sys.exit(2)
  8358. def on_file_saveproject(self, silent=False):
  8359. """
  8360. Callback for menu item File->Save Project. Saves the project to
  8361. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  8362. if set to None. The project is saved by calling ``self.save_project()``.
  8363. :param silent: if True will not display status messages
  8364. :return: None
  8365. """
  8366. self.report_usage("on_file_saveproject")
  8367. if self.project_filename is None:
  8368. self.on_file_saveprojectas()
  8369. else:
  8370. self.worker_task.emit({'fcn': self.save_project,
  8371. 'params': [self.project_filename, silent]})
  8372. if self.defaults["global_open_style"] is False:
  8373. self.file_opened.emit("project", self.project_filename)
  8374. self.file_saved.emit("project", self.project_filename)
  8375. self.set_ui_title(name=self.project_filename)
  8376. self.should_we_save = False
  8377. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  8378. """
  8379. Callback for menu item File->Save Project As... Opens a file
  8380. chooser and saves the project to the given file via
  8381. ``self.save_project()``.
  8382. :param make_copy if to be create a copy of the project; boolean
  8383. :param use_thread: if to be run in a separate thread; boolean
  8384. :param quit_action: if to be followed by quiting the application; boolean
  8385. :return: None
  8386. """
  8387. self.report_usage("on_file_saveprojectas")
  8388. self.date = str(datetime.today()).rpartition('.')[0]
  8389. self.date = ''.join(c for c in self.date if c not in ':-')
  8390. self.date = self.date.replace(' ', '_')
  8391. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  8392. try:
  8393. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8394. caption=_("Save Project As ..."),
  8395. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  8396. filter=filter_)
  8397. except TypeError:
  8398. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  8399. filename = str(filename)
  8400. if filename == '':
  8401. self.inform.emit('[WARNING_NOTCL] %s' %
  8402. _("Save Project cancelled."))
  8403. return
  8404. try:
  8405. f = open(filename, 'r')
  8406. f.close()
  8407. except IOError:
  8408. pass
  8409. if use_thread is True:
  8410. self.worker_task.emit({'fcn': self.save_project,
  8411. 'params': [filename, quit_action]})
  8412. else:
  8413. self.save_project(filename, quit_action)
  8414. # self.save_project(filename)
  8415. if self.defaults["global_open_style"] is False:
  8416. self.file_opened.emit("project", filename)
  8417. self.file_saved.emit("project", filename)
  8418. if not make_copy:
  8419. self.project_filename = filename
  8420. self.set_ui_title(name=self.project_filename)
  8421. self.should_we_save = False
  8422. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  8423. """
  8424. Exports a Geometry Object to an SVG file.
  8425. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8426. :param filename: Path to the SVG file to save to.
  8427. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  8428. :return:
  8429. """
  8430. self.report_usage("export_svg()")
  8431. if filename is None:
  8432. filename = self.defaults["global_last_save_folder"]
  8433. self.log.debug("export_svg()")
  8434. try:
  8435. obj = self.collection.get_by_name(str(obj_name))
  8436. except:
  8437. # TODO: The return behavior has not been established... should raise exception?
  8438. return "Could not retrieve object: %s" % obj_name
  8439. with self.proc_container.new(_("Exporting SVG")) as proc:
  8440. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  8441. # Determine bounding area for svg export
  8442. bounds = obj.bounds()
  8443. size = obj.size()
  8444. # Convert everything to strings for use in the xml doc
  8445. svgwidth = str(size[0])
  8446. svgheight = str(size[1])
  8447. minx = str(bounds[0])
  8448. miny = str(bounds[1] - size[1])
  8449. uom = obj.units.lower()
  8450. # Add a SVG Header and footer to the svg output from shapely
  8451. # The transform flips the Y Axis so that everything renders
  8452. # properly within svg apps such as inkscape
  8453. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8454. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8455. svg_header += 'width="' + svgwidth + uom + '" '
  8456. svg_header += 'height="' + svgheight + uom + '" '
  8457. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  8458. svg_header += '<g transform="scale(1,-1)">'
  8459. svg_footer = '</g> </svg>'
  8460. svg_elem = svg_header + exported_svg + svg_footer
  8461. # Parse the xml through a xml parser just to add line feeds
  8462. # and to make it look more pretty for the output
  8463. svgcode = parse_xml_string(svg_elem)
  8464. svgcode = svgcode.toprettyxml()
  8465. try:
  8466. with open(filename, 'w') as fp:
  8467. fp.write(svgcode)
  8468. except PermissionError:
  8469. self.inform.emit('[WARNING] %s' %
  8470. _("Permission denied, saving not possible.\n"
  8471. "Most likely another app is holding the file open and not accessible."))
  8472. return 'fail'
  8473. if self.defaults["global_open_style"] is False:
  8474. self.file_opened.emit("SVG", filename)
  8475. self.file_saved.emit("SVG", filename)
  8476. self.inform.emit('[success] %s: %s' %
  8477. (_("SVG file exported to"), filename))
  8478. def export_svg_negative(self, obj_name, box_name, filename, boundary,
  8479. scale_stroke_factor=0.00,
  8480. scale_factor_x=None, scale_factor_y=None,
  8481. skew_factor_x=None, skew_factor_y=None, skew_reference='center',
  8482. mirror=None,
  8483. use_thread=True):
  8484. """
  8485. Exports a Geometry Object to an SVG file in negative.
  8486. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8487. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  8488. :param filename: Path to the SVG file to save to.
  8489. :param boundary: thickness of a black border to surround all the features
  8490. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  8491. :param scale_factor_x: factor to scale the svg geometry on the X axis
  8492. :param scale_factor_y: factor to scale the svg geometry on the Y axis
  8493. :param skew_factor_x: factor to skew the svg geometry on the X axis
  8494. :param skew_factor_y: factor to skew the svg geometry on the Y axis
  8495. :param skew_reference: reference to use for skew. Can be 'bottomleft', 'bottomright', 'topleft', 'topright' and
  8496. those are the 4 points of the bounding box of the geometry to be skewed.
  8497. :param mirror: can be 'x' or 'y' or 'both'. Axis on which to mirror the svg geometry
  8498. :param use_thread: if to be run in a separate thread; boolean
  8499. :return:
  8500. """
  8501. self.report_usage("export_negative()")
  8502. if filename is None:
  8503. filename = self.defaults["global_last_save_folder"]
  8504. self.log.debug("export_svg() negative")
  8505. try:
  8506. obj = self.collection.get_by_name(str(obj_name))
  8507. except:
  8508. # TODO: The return behavior has not been established... should raise exception?
  8509. return "Could not retrieve object: %s" % obj_name
  8510. try:
  8511. box = self.collection.get_by_name(str(box_name))
  8512. except:
  8513. # TODO: The return behavior has not been established... should raise exception?
  8514. return "Could not retrieve object: %s" % box_name
  8515. if box is None:
  8516. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  8517. (_("No object Box. Using instead"), obj))
  8518. box = obj
  8519. def make_negative_film():
  8520. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor,
  8521. scale_factor_x=scale_factor_x, scale_factor_y=scale_factor_y,
  8522. skew_factor_x=skew_factor_x, skew_factor_y=skew_factor_y,
  8523. mirror=mirror
  8524. )
  8525. # Determine bounding area for svg export
  8526. bounds = box.bounds()
  8527. size = box.size()
  8528. uom = obj.units.lower()
  8529. # Convert everything to strings for use in the xml doc
  8530. svgwidth = str(size[0] + (2 * boundary))
  8531. svgheight = str(size[1] + (2 * boundary))
  8532. minx = str(bounds[0] - boundary)
  8533. miny = str(bounds[1] + boundary + size[1])
  8534. miny_rect = str(bounds[1] - boundary)
  8535. # Add a SVG Header and footer to the svg output from shapely
  8536. # The transform flips the Y Axis so that everything renders
  8537. # properly within svg apps such as inkscape
  8538. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8539. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8540. svg_header += 'width="' + svgwidth + uom + '" '
  8541. svg_header += 'height="' + svgheight + uom + '" '
  8542. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  8543. svg_header += '>'
  8544. svg_header += '<g transform="scale(1,-1)">'
  8545. svg_footer = '</g> </svg>'
  8546. # Change the attributes of the exported SVG
  8547. # We don't need stroke-width - wrong, we do when we have lines with certain width
  8548. # We set opacity to maximum
  8549. # We set the color to WHITE
  8550. root = ET.fromstring(exported_svg)
  8551. for child in root:
  8552. child.set('fill', '#FFFFFF')
  8553. child.set('opacity', '1.0')
  8554. child.set('stroke', '#FFFFFF')
  8555. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  8556. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  8557. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  8558. first_svg_elem_tag = 'rect'
  8559. first_svg_elem_attribs = {
  8560. 'x': minx,
  8561. 'y': miny_rect,
  8562. 'width': svgwidth,
  8563. 'height': svgheight,
  8564. 'id': 'neg_rect',
  8565. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  8566. }
  8567. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  8568. exported_svg = ET.tostring(root)
  8569. svg_elem = svg_header + str(exported_svg) + svg_footer
  8570. # Parse the xml through a xml parser just to add line feeds
  8571. # and to make it look more pretty for the output
  8572. doc = parse_xml_string(svg_elem)
  8573. try:
  8574. with open(filename, 'w') as fp:
  8575. fp.write(doc.toprettyxml())
  8576. except PermissionError:
  8577. self.inform.emit('[WARNING] %s' %
  8578. _("Permission denied, saving not possible.\n"
  8579. "Most likely another app is holding the file open and not accessible."))
  8580. return 'fail'
  8581. if self.defaults["global_open_style"] is False:
  8582. self.file_opened.emit("SVG", filename)
  8583. self.file_saved.emit("SVG", filename)
  8584. self.inform.emit('[success] %s: %s' %
  8585. (_("SVG file exported to"), filename))
  8586. if use_thread is True:
  8587. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  8588. def job_thread_film(app_obj):
  8589. try:
  8590. make_negative_film()
  8591. except Exception as e:
  8592. proc.done()
  8593. return
  8594. proc.done()
  8595. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  8596. else:
  8597. make_negative_film()
  8598. def export_svg_positive(self, obj_name, box_name, filename,
  8599. scale_stroke_factor=0.00,
  8600. scale_factor_x=None, scale_factor_y=None,
  8601. skew_factor_x=None, skew_factor_y=None, skew_reference='center',
  8602. mirror=None,
  8603. use_thread=True):
  8604. """
  8605. Exports a Geometry Object to an SVG file in positive black.
  8606. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8607. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  8608. :param filename: Path to the SVG file to save to.
  8609. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  8610. :param scale_factor_x: factor to scale the svg geometry on the X axis
  8611. :param scale_factor_y: factor to scale the svg geometry on the Y axis
  8612. :param skew_factor_x: factor to skew the svg geometry on the X axis
  8613. :param skew_factor_y: factor to skew the svg geometry on the Y axis
  8614. :param skew_reference: reference to use for skew. Can be 'bottomleft', 'bottomright', 'topleft', 'topright' and
  8615. those are the 4 points of the bounding box of the geometry to be skewed.
  8616. :param mirror: can be 'x' or 'y' or 'both'. Axis on which to mirror the svg geometry
  8617. :param use_thread: if to be run in a separate thread; boolean
  8618. :return:
  8619. """
  8620. self.report_usage("export_svg_positive()")
  8621. if filename is None:
  8622. filename = self.defaults["global_last_save_folder"]
  8623. self.log.debug("export_svg() black")
  8624. try:
  8625. obj = self.collection.get_by_name(str(obj_name))
  8626. except:
  8627. # TODO: The return behavior has not been established... should raise exception?
  8628. return "Could not retrieve object: %s" % obj_name
  8629. try:
  8630. box = self.collection.get_by_name(str(box_name))
  8631. except:
  8632. # TODO: The return behavior has not been established... should raise exception?
  8633. return "Could not retrieve object: %s" % box_name
  8634. if box is None:
  8635. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  8636. (_("No object Box. Using instead"), obj))
  8637. box = obj
  8638. def make_positive_film():
  8639. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor,
  8640. scale_factor_x=scale_factor_x, scale_factor_y=scale_factor_y,
  8641. skew_factor_x=skew_factor_x, skew_factor_y=skew_factor_y,
  8642. mirror=mirror
  8643. )
  8644. self.progress.emit(40)
  8645. # Change the attributes of the exported SVG
  8646. # We don't need stroke-width
  8647. # We set opacity to maximum
  8648. # We set the colour to WHITE
  8649. root = ET.fromstring(exported_svg)
  8650. for child in root:
  8651. child.set('fill', str(self.defaults['tools_film_color']))
  8652. child.set('opacity', '1.0')
  8653. child.set('stroke', str(self.defaults['tools_film_color']))
  8654. exported_svg = ET.tostring(root)
  8655. # Determine bounding area for svg export
  8656. bounds = box.bounds()
  8657. size = box.size()
  8658. # This contain the measure units
  8659. uom = obj.units.lower()
  8660. # Define a boundary around SVG of about 1.0mm (~39mils)
  8661. if uom in "mm":
  8662. boundary = 1.0
  8663. else:
  8664. boundary = 0.0393701
  8665. self.progress.emit(80)
  8666. # Convert everything to strings for use in the xml doc
  8667. svgwidth = str(size[0] + (2 * boundary))
  8668. svgheight = str(size[1] + (2 * boundary))
  8669. minx = str(bounds[0] - boundary)
  8670. miny = str(bounds[1] + boundary + size[1])
  8671. self.log.debug(minx)
  8672. self.log.debug(miny)
  8673. # Add a SVG Header and footer to the svg output from shapely
  8674. # The transform flips the Y Axis so that everything renders
  8675. # properly within svg apps such as inkscape
  8676. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8677. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8678. svg_header += 'width="' + svgwidth + uom + '" '
  8679. svg_header += 'height="' + svgheight + uom + '" '
  8680. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  8681. svg_header += '>'
  8682. svg_header += '<g transform="scale(1,-1)">'
  8683. svg_footer = '</g> </svg>'
  8684. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  8685. self.progress.emit(90)
  8686. # Parse the xml through a xml parser just to add line feeds
  8687. # and to make it look more pretty for the output
  8688. doc = parse_xml_string(svg_elem)
  8689. try:
  8690. with open(filename, 'w') as fp:
  8691. fp.write(doc.toprettyxml())
  8692. except PermissionError:
  8693. self.inform.emit('[WARNING] %s' %
  8694. _("Permission denied, saving not possible.\n"
  8695. "Most likely another app is holding the file open and not accessible."))
  8696. return 'fail'
  8697. self.progress.emit(100)
  8698. if self.defaults["global_open_style"] is False:
  8699. self.file_opened.emit("SVG", filename)
  8700. self.file_saved.emit("SVG", filename)
  8701. self.inform.emit('[success] %s: %s' %
  8702. (_("SVG file exported to"), filename))
  8703. if use_thread is True:
  8704. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  8705. def job_thread_film(app_obj):
  8706. try:
  8707. make_positive_film()
  8708. except Exception as e:
  8709. proc.done()
  8710. return
  8711. proc.done()
  8712. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  8713. else:
  8714. make_positive_film()
  8715. def save_source_file(self, obj_name, filename, use_thread=True):
  8716. """
  8717. Exports a FlatCAM Object to an Gerber/Excellon file.
  8718. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8719. :param filename: Path to the Gerber file to save to.
  8720. :param use_thread: if to be run in a separate thread
  8721. :return:
  8722. """
  8723. self.report_usage("save source file()")
  8724. if filename is None:
  8725. filename = self.defaults["global_last_save_folder"]
  8726. self.log.debug("save source file()")
  8727. obj = self.collection.get_by_name(obj_name)
  8728. file_string = StringIO(obj.source_file)
  8729. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8730. try:
  8731. with open(filename, 'w') as file:
  8732. file.writelines('G04*\n')
  8733. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8734. (obj.kind.upper(), str(self.version), str(self.version_date)))
  8735. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8736. file.writelines('G04 Created on : %s*\n' % time_string)
  8737. for line in file_string:
  8738. file.writelines(line)
  8739. except PermissionError:
  8740. self.inform.emit('[WARNING] %s' %
  8741. _("Permission denied, saving not possible.\n"
  8742. "Most likely another app is holding the file open and not accessible."))
  8743. return 'fail'
  8744. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  8745. """
  8746. Exports a Excellon Object to an Excellon file.
  8747. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  8748. :param filename: Path to the Excellon file to save to.
  8749. :param use_thread: if to be run in a separate thread
  8750. :return:
  8751. """
  8752. self.report_usage("export_excellon()")
  8753. if filename is None:
  8754. filename = self.defaults["global_last_save_folder"]
  8755. self.log.debug("export_excellon()")
  8756. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  8757. self.defaults["excellon_exp_decimals"]
  8758. )
  8759. if local_use is None:
  8760. try:
  8761. obj = self.collection.get_by_name(str(obj_name))
  8762. except:
  8763. # TODO: The return behavior has not been established... should raise exception?
  8764. return "Could not retrieve object: %s" % obj_name
  8765. else:
  8766. obj = local_use
  8767. # updated units
  8768. eunits = self.defaults["excellon_exp_units"]
  8769. ewhole = self.defaults["excellon_exp_integer"]
  8770. efract = self.defaults["excellon_exp_decimals"]
  8771. ezeros = self.defaults["excellon_exp_zeros"]
  8772. eformat = self.defaults["excellon_exp_format"]
  8773. slot_type = self.defaults["excellon_exp_slot_type"]
  8774. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8775. if fc_units == 'MM':
  8776. factor = 1 if eunits == 'METRIC' else 0.03937
  8777. else:
  8778. factor = 25.4 if eunits == 'METRIC' else 1
  8779. def make_excellon():
  8780. try:
  8781. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8782. header = 'M48\n'
  8783. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  8784. (str(self.version), str(self.version_date))
  8785. header += ';Filename: %s' % str(obj_name) + '\n'
  8786. header += ';Created on : %s' % time_str + '\n'
  8787. if eformat == 'dec':
  8788. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  8789. header += eunits + '\n'
  8790. for tool in obj.tools:
  8791. if eunits == 'METRIC':
  8792. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8793. tool=str(tool),
  8794. dec=2)
  8795. else:
  8796. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8797. tool=str(tool),
  8798. dec=4)
  8799. else:
  8800. if ezeros == 'LZ':
  8801. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8802. form='ndec', e_zeros='LZ', factor=factor,
  8803. slot_type=slot_type)
  8804. header += '%s,%s\n' % (eunits, 'LZ')
  8805. header += format_exc
  8806. for tool in obj.tools:
  8807. if eunits == 'METRIC':
  8808. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8809. tool=str(tool),
  8810. dec=2)
  8811. else:
  8812. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8813. tool=str(tool),
  8814. dec=4)
  8815. else:
  8816. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8817. form='ndec', e_zeros='TZ', factor=factor,
  8818. slot_type=slot_type)
  8819. header += '%s,%s\n' % (eunits, 'TZ')
  8820. header += format_exc
  8821. for tool in obj.tools:
  8822. if eunits == 'METRIC':
  8823. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8824. tool=str(tool),
  8825. dec=2)
  8826. else:
  8827. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8828. tool=str(tool),
  8829. dec=4)
  8830. header += '%\n'
  8831. footer = 'M30\n'
  8832. exported_excellon = header
  8833. exported_excellon += excellon_code
  8834. exported_excellon += footer
  8835. if local_use is None:
  8836. try:
  8837. with open(filename, 'w') as fp:
  8838. fp.write(exported_excellon)
  8839. except PermissionError:
  8840. self.inform.emit('[WARNING] %s' %
  8841. _("Permission denied, saving not possible.\n"
  8842. "Most likely another app is holding the file open and not accessible."))
  8843. return 'fail'
  8844. if self.defaults["global_open_style"] is False:
  8845. self.file_opened.emit("Excellon", filename)
  8846. self.file_saved.emit("Excellon", filename)
  8847. self.inform.emit('[success] %s: %s' %
  8848. (_("Excellon file exported to"), filename))
  8849. else:
  8850. return exported_excellon
  8851. except Exception as e:
  8852. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  8853. return 'fail'
  8854. if use_thread is True:
  8855. with self.proc_container.new(_("Exporting Excellon")) as proc:
  8856. def job_thread_exc(app_obj):
  8857. ret = make_excellon()
  8858. if ret == 'fail':
  8859. self.inform.emit('[ERROR_NOTCL] %s' %
  8860. _('Could not export Excellon file.'))
  8861. return
  8862. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8863. else:
  8864. ret = make_excellon()
  8865. if ret == 'fail':
  8866. self.inform.emit('[ERROR_NOTCL] %s' %
  8867. _('Could not export Excellon file.'))
  8868. return 'fail'
  8869. if local_use is not None:
  8870. return ret
  8871. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  8872. """
  8873. Exports a Gerber Object to an Gerber file.
  8874. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  8875. :param filename: Path to the Gerber file to save to.
  8876. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8877. When not None, the value will be the actual Gerber object for which to create the Gerber code
  8878. :param use_thread: if to be run in a separate thread
  8879. :return:
  8880. """
  8881. self.report_usage("export_gerber()")
  8882. if filename is None:
  8883. filename = self.defaults["global_last_save_folder"]
  8884. self.log.debug("export_gerber()")
  8885. if local_use is None:
  8886. try:
  8887. obj = self.collection.get_by_name(str(obj_name))
  8888. except:
  8889. # TODO: The return behavior has not been established... should raise exception?
  8890. return "Could not retrieve object: %s" % obj_name
  8891. else:
  8892. obj = local_use
  8893. # updated units
  8894. gunits = self.defaults["gerber_exp_units"]
  8895. gwhole = self.defaults["gerber_exp_integer"]
  8896. gfract = self.defaults["gerber_exp_decimals"]
  8897. gzeros = self.defaults["gerber_exp_zeros"]
  8898. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8899. if fc_units == 'MM':
  8900. factor = 1 if gunits == 'MM' else 0.03937
  8901. else:
  8902. factor = 25.4 if gunits == 'MM' else 1
  8903. def make_gerber():
  8904. try:
  8905. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8906. header = 'G04*\n'
  8907. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  8908. (str(self.version), str(self.version_date))
  8909. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  8910. header += 'G04 Created on : %s*' % time_str + '\n'
  8911. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  8912. header += "%MO{units}*%\n".format(units=gunits)
  8913. for apid in obj.apertures:
  8914. if obj.apertures[apid]['type'] == 'C':
  8915. header += "%ADD{apid}{type},{size}*%\n".format(
  8916. apid=str(apid),
  8917. type='C',
  8918. size=(factor * obj.apertures[apid]['size'])
  8919. )
  8920. elif obj.apertures[apid]['type'] == 'R':
  8921. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8922. apid=str(apid),
  8923. type='R',
  8924. width=(factor * obj.apertures[apid]['width']),
  8925. height=(factor * obj.apertures[apid]['height'])
  8926. )
  8927. elif obj.apertures[apid]['type'] == 'O':
  8928. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8929. apid=str(apid),
  8930. type='O',
  8931. width=(factor * obj.apertures[apid]['width']),
  8932. height=(factor * obj.apertures[apid]['height'])
  8933. )
  8934. header += '\n'
  8935. # obsolete units but some software may need it
  8936. if gunits == 'IN':
  8937. header += 'G70*\n'
  8938. else:
  8939. header += 'G71*\n'
  8940. # Absolute Mode
  8941. header += 'G90*\n'
  8942. header += 'G01*\n'
  8943. # positive polarity
  8944. header += '%LPD*%\n'
  8945. footer = 'M02*\n'
  8946. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8947. exported_gerber = header
  8948. exported_gerber += gerber_code
  8949. exported_gerber += footer
  8950. if local_use is None:
  8951. try:
  8952. with open(filename, 'w') as fp:
  8953. fp.write(exported_gerber)
  8954. except PermissionError:
  8955. self.inform.emit('[WARNING] %s' %
  8956. _("Permission denied, saving not possible.\n"
  8957. "Most likely another app is holding the file open and not accessible."))
  8958. return 'fail'
  8959. if self.defaults["global_open_style"] is False:
  8960. self.file_opened.emit("Gerber", filename)
  8961. self.file_saved.emit("Gerber", filename)
  8962. self.inform.emit('[success] %s: %s' %
  8963. (_("Gerber file exported to"), filename))
  8964. else:
  8965. return exported_gerber
  8966. except Exception as e:
  8967. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8968. return 'fail'
  8969. if use_thread is True:
  8970. with self.proc_container.new(_("Exporting Gerber")) as proc:
  8971. def job_thread_grb(app_obj):
  8972. ret = make_gerber()
  8973. if ret == 'fail':
  8974. self.inform.emit('[ERROR_NOTCL] %s' %
  8975. _('Could not export Gerber file.'))
  8976. return
  8977. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8978. else:
  8979. ret = make_gerber()
  8980. if ret == 'fail':
  8981. self.inform.emit('[ERROR_NOTCL] %s' %
  8982. _('Could not export Gerber file.'))
  8983. return 'fail'
  8984. if local_use is not None:
  8985. return ret
  8986. def export_dxf(self, obj_name, filename, use_thread=True):
  8987. """
  8988. Exports a Geometry Object to an DXF file.
  8989. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8990. :param filename: Path to the DXF file to save to.
  8991. :param use_thread: if to be run in a separate thread
  8992. :return:
  8993. """
  8994. self.report_usage("export_dxf()")
  8995. if filename is None:
  8996. filename = self.defaults["global_last_save_folder"]
  8997. self.log.debug("export_dxf()")
  8998. format_exc = ''
  8999. units = ''
  9000. try:
  9001. obj = self.collection.get_by_name(str(obj_name))
  9002. except:
  9003. # TODO: The return behavior has not been established... should raise exception?
  9004. return "Could not retrieve object: %s" % obj_name
  9005. # updated units
  9006. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  9007. if units == 'IN' or units == 'INCH':
  9008. units = 'INCH'
  9009. elif units == 'MM' or units == 'METIRC':
  9010. units ='METRIC'
  9011. def make_dxf():
  9012. try:
  9013. dxf_code = obj.export_dxf()
  9014. dxf_code.saveas(filename)
  9015. if self.defaults["global_open_style"] is False:
  9016. self.file_opened.emit("DXF", filename)
  9017. self.file_saved.emit("DXF", filename)
  9018. self.inform.emit('[success] %s: %s' %
  9019. (_("DXF file exported to"), filename))
  9020. except:
  9021. return 'fail'
  9022. if use_thread is True:
  9023. with self.proc_container.new(_("Exporting DXF")) as proc:
  9024. def job_thread_exc(app_obj):
  9025. ret = make_dxf()
  9026. if ret == 'fail':
  9027. app_obj.inform.emit('[WARNING_NOTCL] %s' %
  9028. _('Could not export DXF file.'))
  9029. return
  9030. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  9031. else:
  9032. ret = make_dxf()
  9033. if ret == 'fail':
  9034. self.inform.emit('[WARNING_NOTCL] %s' %
  9035. _('Could not export DXF file.'))
  9036. return
  9037. def import_svg(self, filename, geo_type='geometry', outname=None):
  9038. """
  9039. Adds a new Geometry Object to the projects and populates
  9040. it with shapes extracted from the SVG file.
  9041. :param filename: Path to the SVG file.
  9042. :param geo_type: Type of FlatCAM object that will be created from SVG
  9043. :param outname:
  9044. :return:
  9045. """
  9046. self.report_usage("import_svg()")
  9047. obj_type = ""
  9048. if geo_type is None or geo_type == "geometry":
  9049. obj_type = "geometry"
  9050. elif geo_type == "gerber":
  9051. obj_type = geo_type
  9052. else:
  9053. self.inform.emit('[ERROR_NOTCL] %s' %
  9054. _("Not supported type is picked as parameter. "
  9055. "Only Geometry and Gerber are supported"))
  9056. return
  9057. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  9058. def obj_init(geo_obj, app_obj):
  9059. geo_obj.import_svg(filename, obj_type, units=units)
  9060. geo_obj.multigeo = False
  9061. with self.proc_container.new(_("Importing SVG")) as proc:
  9062. # Object name
  9063. name = outname or filename.split('/')[-1].split('\\')[-1]
  9064. self.new_object(obj_type, name, obj_init, autoselected=False)
  9065. self.progress.emit(20)
  9066. # Register recent file
  9067. self.file_opened.emit("svg", filename)
  9068. # GUI feedback
  9069. self.inform.emit('[success] %s: %s' %
  9070. (_("Opened"), filename))
  9071. self.progress.emit(100)
  9072. def import_dxf(self, filename, geo_type='geometry', outname=None):
  9073. """
  9074. Adds a new Geometry Object to the projects and populates
  9075. it with shapes extracted from the DXF file.
  9076. :param filename: Path to the DXF file.
  9077. :param geo_type: Type of FlatCAM object that will be created from DXF
  9078. :param outname:
  9079. :type putname: str
  9080. :return:
  9081. """
  9082. self.report_usage("import_dxf()")
  9083. obj_type = ""
  9084. if geo_type is None or geo_type == "geometry":
  9085. obj_type = "geometry"
  9086. elif geo_type == "gerber":
  9087. obj_type = geo_type
  9088. else:
  9089. self.inform.emit('[ERROR_NOTCL] %s' %
  9090. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  9091. return
  9092. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  9093. def obj_init(geo_obj, app_obj):
  9094. geo_obj.import_dxf(filename, obj_type, units=units)
  9095. geo_obj.multigeo = False
  9096. with self.proc_container.new(_("Importing DXF")) as proc:
  9097. # Object name
  9098. name = outname or filename.split('/')[-1].split('\\')[-1]
  9099. self.new_object(obj_type, name, obj_init, autoselected=False)
  9100. self.progress.emit(20)
  9101. # Register recent file
  9102. self.file_opened.emit("dxf", filename)
  9103. # GUI feedback
  9104. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9105. self.progress.emit(100)
  9106. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  9107. """
  9108. Adds a new Geometry Object to the projects and populates
  9109. it with shapes extracted from the SVG file.
  9110. :param filename: Path to the SVG file.
  9111. :param o_type: type of FlatCAM objeect
  9112. :param dpi: dot per inch
  9113. :param mode: black or color
  9114. :param mask: dictate the level of detail
  9115. :param outname: name for the resulting file
  9116. :return:
  9117. """
  9118. self.report_usage("import_image()")
  9119. if o_type is None or o_type == "geometry":
  9120. obj_type = "geometry"
  9121. elif o_type == "gerber":
  9122. obj_type = o_type
  9123. else:
  9124. self.inform.emit('[ERROR_NOTCL] %s' %
  9125. _("Not supported type is picked as parameter. "
  9126. "Only Geometry and Gerber are supported"))
  9127. return
  9128. def obj_init(geo_obj, app_obj):
  9129. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  9130. geo_obj.multigeo = False
  9131. with self.proc_container.new(_("Importing Image")) as proc:
  9132. # Object name
  9133. name = outname or filename.split('/')[-1].split('\\')[-1]
  9134. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  9135. self.new_object(obj_type, name, obj_init)
  9136. self.progress.emit(20)
  9137. # Register recent file
  9138. self.file_opened.emit("image", filename)
  9139. # GUI feedback
  9140. self.inform.emit('[success] %s: %s' %
  9141. (_("Opened"), filename))
  9142. self.progress.emit(100)
  9143. def open_gerber(self, filename, outname=None):
  9144. """
  9145. Opens a Gerber file, parses it and creates a new object for
  9146. it in the program. Thread-safe.
  9147. :param outname: Name of the resulting object. None causes the
  9148. name to be that of the file.
  9149. :param filename: Gerber file filename
  9150. :type filename: str
  9151. :param follow: If true, the parser will not create polygons, just lines
  9152. following the gerber path.
  9153. :type follow: bool
  9154. :return: None
  9155. """
  9156. # How the object should be initialized
  9157. def obj_init(gerber_obj, app_obj):
  9158. assert isinstance(gerber_obj, FlatCAMGerber), \
  9159. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  9160. # Opening the file happens here
  9161. self.progress.emit(30)
  9162. try:
  9163. gerber_obj.parse_file(filename)
  9164. except IOError:
  9165. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  9166. (_("Failed to open file"), filename))
  9167. app_obj.progress.emit(0)
  9168. return "fail"
  9169. except ParseError as err:
  9170. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' %
  9171. (_("Failed to parse file"), filename, str(err)))
  9172. app_obj.progress.emit(0)
  9173. self.log.error(str(err))
  9174. return "fail"
  9175. except Exception as e:
  9176. log.debug("App.open_gerber() --> %s" % str(e))
  9177. msg = '[ERROR] %s' % \
  9178. _("An internal error has occurred. See shell.\n")
  9179. msg += traceback.format_exc()
  9180. app_obj.inform.emit(msg)
  9181. return "fail"
  9182. if gerber_obj.is_empty():
  9183. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  9184. # self.collection.set_active(gerber_obj.options["name"])
  9185. # self.collection.delete_active()
  9186. self.inform.emit('[ERROR_NOTCL] %s' %
  9187. _("Object is not Gerber file or empty. Aborting object creation."))
  9188. return "fail"
  9189. # Further parsing
  9190. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  9191. App.log.debug("open_gerber()")
  9192. with self.proc_container.new(_("Opening Gerber")) as proc:
  9193. self.progress.emit(10)
  9194. # Object name
  9195. name = outname or filename.split('/')[-1].split('\\')[-1]
  9196. # # ## Object creation # ##
  9197. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  9198. if ret == 'fail':
  9199. self.inform.emit('[ERROR_NOTCL]%s' %
  9200. _(' Open Gerber failed. Probable not a Gerber file.'))
  9201. return
  9202. # Register recent file
  9203. self.file_opened.emit("gerber", filename)
  9204. self.progress.emit(100)
  9205. # GUI feedback
  9206. self.inform.emit('[success] %s: %s' %
  9207. (_("Opened"), filename))
  9208. def open_excellon(self, filename, outname=None, plot=True):
  9209. """
  9210. Opens an Excellon file, parses it and creates a new object for
  9211. it in the program. Thread-safe.
  9212. :param outname: Name of the resulting object. None causes the
  9213. name to be that of the file.
  9214. :param filename: Excellon file filename
  9215. :type filename: str
  9216. :return: None
  9217. """
  9218. App.log.debug("open_excellon()")
  9219. # How the object should be initialized
  9220. def obj_init(excellon_obj, app_obj):
  9221. # self.progress.emit(20)
  9222. try:
  9223. ret = excellon_obj.parse_file(filename=filename)
  9224. if ret == "fail":
  9225. log.debug("Excellon parsing failed.")
  9226. self.inform.emit('[ERROR_NOTCL] %s' %
  9227. _("This is not Excellon file."))
  9228. return "fail"
  9229. except IOError:
  9230. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  9231. (_("Cannot open file"), filename))
  9232. log.debug("Could not open Excellon object.")
  9233. self.progress.emit(0) # TODO: self and app_bjj mixed
  9234. return "fail"
  9235. except:
  9236. msg = '[ERROR_NOTCL] %s' % \
  9237. _("An internal error has occurred. See shell.\n")
  9238. msg += traceback.format_exc()
  9239. app_obj.inform.emit(msg)
  9240. return "fail"
  9241. ret = excellon_obj.create_geometry()
  9242. if ret == 'fail':
  9243. log.debug("Could not create geometry for Excellon object.")
  9244. return "fail"
  9245. for tool in excellon_obj.tools:
  9246. if excellon_obj.tools[tool]['solid_geometry']:
  9247. return
  9248. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  9249. (_("No geometry found in file"), filename))
  9250. return "fail"
  9251. with self.proc_container.new(_("Opening Excellon.")):
  9252. # Object name
  9253. name = outname or filename.split('/')[-1].split('\\')[-1]
  9254. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  9255. if ret_val == 'fail':
  9256. self.inform.emit('[ERROR_NOTCL] %s' %
  9257. _('Open Excellon file failed. Probable not an Excellon file.'))
  9258. return
  9259. # Register recent file
  9260. self.file_opened.emit("excellon", filename)
  9261. # GUI feedback
  9262. self.inform.emit('[success] %s: %s' %
  9263. (_("Opened"), filename))
  9264. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True):
  9265. """
  9266. Opens a G-gcode file, parses it and creates a new object for
  9267. it in the program. Thread-safe.
  9268. :param outname: Name of the resulting object. None causes the name to be that of the file.
  9269. :param filename: G-code file filename
  9270. :type filename: str
  9271. :return: None
  9272. """
  9273. App.log.debug("open_gcode()")
  9274. # How the object should be initialized
  9275. def obj_init(job_obj, app_obj_):
  9276. """
  9277. :param job_obj: the resulting object
  9278. :type app_obj_: App
  9279. """
  9280. assert isinstance(app_obj_, App), \
  9281. "Initializer expected App, got %s" % type(app_obj_)
  9282. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  9283. try:
  9284. f = open(filename)
  9285. gcode = f.read()
  9286. f.close()
  9287. except IOError:
  9288. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  9289. (_("Failed to open"), filename))
  9290. return "fail"
  9291. job_obj.gcode = gcode
  9292. ret = job_obj.gcode_parse(force_parsing=force_parsing)
  9293. if ret == "fail":
  9294. self.inform.emit('[ERROR_NOTCL] %s' %
  9295. _("This is not GCODE"))
  9296. return "fail"
  9297. job_obj.create_geometry()
  9298. with self.proc_container.new(_("Opening G-Code.")):
  9299. # Object name
  9300. name = outname or filename.split('/')[-1].split('\\')[-1]
  9301. # New object creation and file processing
  9302. ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  9303. if ret == 'fail':
  9304. self.inform.emit('[ERROR_NOTCL] %s' %
  9305. _("Failed to create CNCJob Object. Probable not a GCode file. "
  9306. "Try to load it from File menu.\n "
  9307. "Attempting to create a FlatCAM CNCJob Object from "
  9308. "G-Code file failed during processing"))
  9309. return "fail"
  9310. # Register recent file
  9311. self.file_opened.emit("cncjob", filename)
  9312. # GUI feedback
  9313. self.inform.emit('[success] %s: %s' %
  9314. (_("Opened"), filename))
  9315. def open_script(self, filename, outname=None, silent=False):
  9316. """
  9317. Opens a Script file, parses it and creates a new object for
  9318. it in the program. Thread-safe.
  9319. :param outname: Name of the resulting object. None causes the name to be that of the file.
  9320. :param filename: Script file filename
  9321. :type filename: str
  9322. :return: None
  9323. """
  9324. App.log.debug("open_script()")
  9325. with self.proc_container.new(_("Opening TCL Script...")):
  9326. try:
  9327. with open(filename, "r") as opened_script:
  9328. script_content = opened_script.readlines()
  9329. script_content = ''.join(script_content)
  9330. if silent is False:
  9331. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  9332. except Exception as e:
  9333. log.debug("App.open_script() -> %s" % str(e))
  9334. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to open TCL Script."))
  9335. return
  9336. # Object name
  9337. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  9338. # New object creation and file processing
  9339. self.on_filenewscript(name=script_name, text=script_content)
  9340. # Register recent file
  9341. self.file_opened.emit("script", filename)
  9342. # GUI feedback
  9343. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9344. def open_config_file(self, filename, run_from_arg=None):
  9345. """
  9346. Loads a config file from the specified file.
  9347. :param filename: Name of the file from which to load.
  9348. :type filename: str
  9349. :return: None
  9350. """
  9351. App.log.debug("Opening config file: " + filename)
  9352. if run_from_arg:
  9353. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  9354. "Canvas initialization finished in"), '%.2f' % self.used_time,
  9355. _("Opening FlatCAM Config file.")),
  9356. alignment=Qt.AlignBottom | Qt.AlignLeft,
  9357. color=QtGui.QColor("gray"))
  9358. # add the tab if it was closed
  9359. self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  9360. # first clear previous text in text editor (if any)
  9361. self.ui.text_editor_tab.code_editor.clear()
  9362. # Switch plot_area to CNCJob tab
  9363. self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  9364. try:
  9365. if filename:
  9366. f = QtCore.QFile(filename)
  9367. if f.open(QtCore.QIODevice.ReadOnly):
  9368. stream = QtCore.QTextStream(f)
  9369. gcode_edited = stream.readAll()
  9370. self.ui.text_editor_tab.code_editor.setPlainText(gcode_edited)
  9371. f.close()
  9372. except IOError:
  9373. App.log.error("Failed to open config file: %s" % filename)
  9374. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9375. (_("Failed to open config file"), filename))
  9376. return
  9377. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  9378. """
  9379. Loads a project from the specified file.
  9380. 1) Loads and parses file
  9381. 2) Registers the file as recently opened.
  9382. 3) Calls on_file_new()
  9383. 4) Updates options
  9384. 5) Calls new_object() with the object's from_dict() as init method.
  9385. 6) Calls plot_all() if plot=True
  9386. :param filename: Name of the file from which to load.
  9387. :type filename: str
  9388. :param run_from_arg: True if run for arguments
  9389. :param plot: If True plot all objects in the project
  9390. :param cli: run from command line
  9391. :return: None
  9392. """
  9393. App.log.debug("Opening project: " + filename)
  9394. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9395. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9396. if cli is None:
  9397. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  9398. if run_from_arg:
  9399. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  9400. "Canvas initialization finished in"), '%.2f' % self.used_time,
  9401. _("Opening FlatCAM Project file.")),
  9402. alignment=Qt.AlignBottom | Qt.AlignLeft,
  9403. color=QtGui.QColor("gray"))
  9404. # Open and parse an uncompressed Project file
  9405. try:
  9406. f = open(filename, 'r')
  9407. except IOError:
  9408. App.log.error("Failed to open project file: %s" % filename)
  9409. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9410. (_("Failed to open project file"), filename))
  9411. return
  9412. try:
  9413. d = json.load(f, object_hook=dict2obj)
  9414. except Exception as e:
  9415. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  9416. (filename, str(e)))
  9417. f.close()
  9418. # Open and parse a compressed Project file
  9419. try:
  9420. with lzma.open(filename) as f:
  9421. file_content = f.read().decode('utf-8')
  9422. d = json.loads(file_content, object_hook=dict2obj)
  9423. except Exception as e:
  9424. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  9425. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9426. (_("Failed to open project file"), filename))
  9427. return
  9428. # Clear the current project
  9429. # # NOT THREAD SAFE # ##
  9430. if run_from_arg is True:
  9431. pass
  9432. elif cli is True:
  9433. self.delete_selection_shape()
  9434. else:
  9435. self.on_file_new()
  9436. # Project options
  9437. self.options.update(d['options'])
  9438. self.project_filename = filename
  9439. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9440. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9441. if cli is None:
  9442. self.set_screen_units(self.options["units"])
  9443. # Re create objects
  9444. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  9445. for obj in d['objs']:
  9446. def obj_init(obj_inst, app_inst):
  9447. obj_inst.from_dict(obj)
  9448. App.log.debug("Recreating from opened project an %s object: %s" %
  9449. (obj['kind'].capitalize(), obj['options']['name']))
  9450. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9451. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9452. if cli is None:
  9453. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  9454. obj['kind'].upper(),
  9455. obj['options']['name']
  9456. )
  9457. )
  9458. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  9459. self.inform.emit('[success] %s: %s' %
  9460. (_("Project loaded from"), filename))
  9461. self.should_we_save = False
  9462. self.file_opened.emit("project", filename)
  9463. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9464. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9465. if cli is None:
  9466. self.set_ui_title(name=self.project_filename)
  9467. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  9468. def propagate_defaults(self, silent=False):
  9469. """
  9470. This method is used to set default values in classes. It's
  9471. an alternative to project options but allows the use
  9472. of values invisible to the user.
  9473. :return: None
  9474. """
  9475. if silent is False:
  9476. self.log.debug("propagate_defaults()")
  9477. # Which objects to update the given parameters.
  9478. routes = {
  9479. "global_zdownrate": CNCjob,
  9480. "excellon_zeros": Excellon,
  9481. "excellon_format_upper_in": Excellon,
  9482. "excellon_format_lower_in": Excellon,
  9483. "excellon_format_upper_mm": Excellon,
  9484. "excellon_format_lower_mm": Excellon,
  9485. "excellon_units": Excellon,
  9486. "gerber_use_buffer_for_union": Gerber,
  9487. "geometry_multidepth": Geometry
  9488. }
  9489. for param in routes:
  9490. if param in routes[param].defaults:
  9491. try:
  9492. routes[param].defaults[param] = self.defaults[param]
  9493. if silent is False:
  9494. self.log.debug(" " + param + " OK")
  9495. except KeyError:
  9496. if silent is False:
  9497. self.log.debug(" ERROR: " + param + " not in defaults.")
  9498. else:
  9499. # Try extracting the name:
  9500. # classname_param here is param in the object
  9501. if param.find(routes[param].__name__.lower() + "_") == 0:
  9502. p = param[len(routes[param].__name__) + 1:]
  9503. if p in routes[param].defaults:
  9504. routes[param].defaults[p] = self.defaults[param]
  9505. if silent is False:
  9506. self.log.debug(" " + param + " OK!")
  9507. def plot_all(self, zoom=True):
  9508. """
  9509. Re-generates all plots from all objects.
  9510. :return: None
  9511. """
  9512. self.log.debug("Plot_all()")
  9513. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  9514. for obj in self.collection.get_list():
  9515. def worker_task(obj):
  9516. with self.proc_container.new("Plotting"):
  9517. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  9518. if zoom:
  9519. self.object_plotted.emit(obj)
  9520. # Send to worker
  9521. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  9522. def register_folder(self, filename):
  9523. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  9524. def register_save_folder(self, filename):
  9525. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  9526. def set_progress_bar(self, percentage, text=""):
  9527. self.ui.progress_bar.setValue(int(percentage))
  9528. def setup_shell(self):
  9529. """
  9530. Creates shell functions. Runs once at startup.
  9531. :return: None
  9532. """
  9533. self.log.debug("setup_shell()")
  9534. def shelp(p=None):
  9535. if not p:
  9536. return _("Available commands:\n") + \
  9537. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  9538. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  9539. if p not in commands:
  9540. return "Unknown command: %s" % p
  9541. return commands[p]["help"]
  9542. # --- Migrated to new architecture ---
  9543. # def options(name):
  9544. # ops = self.collection.get_by_name(str(name)).options
  9545. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  9546. def h(*args):
  9547. """
  9548. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  9549. and standalone parameters into list.
  9550. """
  9551. kwa = {}
  9552. a = []
  9553. n = len(args)
  9554. name = None
  9555. for i in range(n):
  9556. match = re.search(r'^-([a-zA-Z].*)', args[i])
  9557. if match:
  9558. assert name is None
  9559. name = match.group(1)
  9560. continue
  9561. if name is None:
  9562. a.append(args[i])
  9563. else:
  9564. kwa[name] = args[i]
  9565. name = None
  9566. return a, kwa
  9567. @contextmanager
  9568. def wait_signal(signal, timeout=10000):
  9569. """
  9570. Block loop until signal emitted, timeout (ms) elapses
  9571. or unhandled exception happens in a thread.
  9572. :param timeout: time after which the loop is exited
  9573. :param signal: Signal to wait for.
  9574. """
  9575. loop = QtCore.QEventLoop()
  9576. # Normal termination
  9577. signal.connect(loop.quit)
  9578. # Termination by exception in thread
  9579. self.thread_exception.connect(loop.quit)
  9580. status = {'timed_out': False}
  9581. def report_quit():
  9582. status['timed_out'] = True
  9583. loop.quit()
  9584. yield
  9585. # Temporarily change how exceptions are managed.
  9586. oeh = sys.excepthook
  9587. ex = []
  9588. def except_hook(type_, value, traceback_):
  9589. ex.append(value)
  9590. oeh(type_, value, traceback_)
  9591. sys.excepthook = except_hook
  9592. # Terminate on timeout
  9593. if timeout is not None:
  9594. QtCore.QTimer.singleShot(timeout, report_quit)
  9595. # # ## Block ## ##
  9596. loop.exec_()
  9597. # Restore exception management
  9598. sys.excepthook = oeh
  9599. if ex:
  9600. self.raiseTclError(str(ex[0]))
  9601. if status['timed_out']:
  9602. raise Exception('Timed out!')
  9603. def make_docs():
  9604. output = ''
  9605. import collections
  9606. od = collections.OrderedDict(sorted(commands.items()))
  9607. for cmd_, val in od.items():
  9608. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  9609. t = val['help']
  9610. usage_i = t.find('>')
  9611. if usage_i < 0:
  9612. expl = t
  9613. output += expl + '\n\n'
  9614. continue
  9615. expl = t[:usage_i - 1]
  9616. output += expl + '\n\n'
  9617. end_usage_i = t[usage_i:].find('\n')
  9618. if end_usage_i < 0:
  9619. end_usage_i = len(t[usage_i:])
  9620. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  9621. else:
  9622. extras = t[usage_i+end_usage_i+1:]
  9623. parts = [s.strip() for s in extras.split('\n')]
  9624. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  9625. for p in parts:
  9626. output += ' ' + p + '\n\n'
  9627. return output
  9628. '''
  9629. Howto implement TCL shell commands:
  9630. All parameters passed to command should be possible to set as None and test it afterwards.
  9631. This is because we need to see error caused in tcl,
  9632. if None value as default parameter is not allowed TCL will return empty error.
  9633. Use:
  9634. def mycommand(name=None,...):
  9635. Test it like this:
  9636. if name is None:
  9637. self.raise_tcl_error('Argument name is missing.')
  9638. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  9639. otherwise we will miss it and processing will silently continue.
  9640. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  9641. which is catched in exec_command and displayed in TCL shell console with red background.
  9642. Error in console is displayed with TCL trace.
  9643. This behavior works only within main thread,
  9644. errors with promissed tasks can be catched and detected only with log.
  9645. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  9646. TCL shell.
  9647. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  9648. '''
  9649. commands = {
  9650. 'help': {
  9651. 'fcn': shelp,
  9652. 'help': _("Shows list of commands.")
  9653. },
  9654. }
  9655. # Import/overwrite tcl commands as objects of TclCommand descendants
  9656. # This modifies the variable 'commands'.
  9657. tclCommands.register_all_commands(self, commands)
  9658. # Add commands to the tcl interpreter
  9659. for cmd in commands:
  9660. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  9661. # Make the tcl puts function return instead of print to stdout
  9662. self.tcl.eval('''
  9663. rename puts original_puts
  9664. proc puts {args} {
  9665. if {[llength $args] == 1} {
  9666. return "[lindex $args 0]"
  9667. } else {
  9668. eval original_puts $args
  9669. }
  9670. }
  9671. ''')
  9672. def setup_recent_items(self):
  9673. # TODO: Move this to constructor
  9674. icons = {
  9675. "gerber": "share/flatcam_icon16.png",
  9676. "excellon": "share/drill16.png",
  9677. 'geometry': "share/geometry16.png",
  9678. "cncjob": "share/cnc16.png",
  9679. "script": "share/script_new24.png",
  9680. "document": "share/notes16_1.png",
  9681. "project": "share/project16.png",
  9682. "svg": "share/geometry16.png",
  9683. "dxf": "share/dxf16.png",
  9684. "pdf": "share/pdf32.png",
  9685. "image": "share/image16.png"
  9686. }
  9687. openers = {
  9688. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  9689. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  9690. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  9691. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  9692. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  9693. "document": None,
  9694. 'project': self.open_project,
  9695. 'svg': self.import_svg,
  9696. 'dxf': self.import_dxf,
  9697. 'image': self.import_image,
  9698. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  9699. }
  9700. # Open recent file for files
  9701. try:
  9702. f = open(self.data_path + '/recent.json')
  9703. except IOError:
  9704. App.log.error("Failed to load recent item list.")
  9705. self.inform.emit('[ERROR_NOTCL] %s' %
  9706. _("Failed to load recent item list."))
  9707. return
  9708. try:
  9709. self.recent = json.load(f)
  9710. except json.scanner.JSONDecodeError:
  9711. App.log.error("Failed to parse recent item list.")
  9712. self.inform.emit('[ERROR_NOTCL] %s' %
  9713. _("Failed to parse recent item list."))
  9714. f.close()
  9715. return
  9716. f.close()
  9717. # Open recent file for projects
  9718. try:
  9719. fp = open(self.data_path + '/recent_projects.json')
  9720. except IOError:
  9721. App.log.error("Failed to load recent project item list.")
  9722. self.inform.emit('[ERROR_NOTCL] %s' %
  9723. _("Failed to load recent projects item list."))
  9724. return
  9725. try:
  9726. self.recent_projects = json.load(fp)
  9727. except json.scanner.JSONDecodeError:
  9728. App.log.error("Failed to parse recent project item list.")
  9729. self.inform.emit('[ERROR_NOTCL] %s' %
  9730. _("Failed to parse recent project item list."))
  9731. fp.close()
  9732. return
  9733. fp.close()
  9734. # Closure needed to create callbacks in a loop.
  9735. # Otherwise late binding occurs.
  9736. def make_callback(func, fname):
  9737. def opener():
  9738. func(fname)
  9739. return opener
  9740. def reset_recent_files():
  9741. # Reset menu
  9742. self.ui.recent.clear()
  9743. self.recent = []
  9744. try:
  9745. f = open(self.data_path + '/recent.json', 'w')
  9746. except IOError:
  9747. App.log.error("Failed to open recent items file for writing.")
  9748. return
  9749. json.dump(self.recent, f)
  9750. def reset_recent_projects():
  9751. # Reset menu
  9752. self.ui.recent_projects.clear()
  9753. self.recent_projects = []
  9754. try:
  9755. fp = open(self.data_path + '/recent_projects.json', 'w')
  9756. except IOError:
  9757. App.log.error("Failed to open recent projects items file for writing.")
  9758. return
  9759. json.dump(self.recent, fp)
  9760. # Reset menu
  9761. self.ui.recent.clear()
  9762. self.ui.recent_projects.clear()
  9763. # Create menu items for projects
  9764. for recent in self.recent_projects:
  9765. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9766. if recent['kind'] == 'project':
  9767. try:
  9768. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9769. # Attach callback
  9770. o = make_callback(openers[recent["kind"]], recent['filename'])
  9771. action.triggered.connect(o)
  9772. self.ui.recent_projects.addAction(action)
  9773. except KeyError:
  9774. App.log.error("Unsupported file type: %s" % recent["kind"])
  9775. # Last action in Recent Files menu is one that Clear the content
  9776. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent projects")), self)
  9777. clear_action_proj.triggered.connect(reset_recent_projects)
  9778. self.ui.recent_projects.addSeparator()
  9779. self.ui.recent_projects.addAction(clear_action_proj)
  9780. # Create menu items for files
  9781. for recent in self.recent:
  9782. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9783. if recent['kind'] != 'project':
  9784. try:
  9785. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9786. # Attach callback
  9787. o = make_callback(openers[recent["kind"]], recent['filename'])
  9788. action.triggered.connect(o)
  9789. self.ui.recent.addAction(action)
  9790. except KeyError:
  9791. App.log.error("Unsupported file type: %s" % recent["kind"])
  9792. # Last action in Recent Files menu is one that Clear the content
  9793. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  9794. clear_action.triggered.connect(reset_recent_files)
  9795. self.ui.recent.addSeparator()
  9796. self.ui.recent.addAction(clear_action)
  9797. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  9798. # self.ui.menufilerecent.set_submenu(recent_menu)
  9799. # recent_menu.show_all()
  9800. # self.ui.recent.show()
  9801. self.log.debug("Recent items list has been populated.")
  9802. def setup_component_editor(self):
  9803. # label = QtWidgets.QLabel("Choose an item from Project")
  9804. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  9805. sel_title = QtWidgets.QTextEdit(
  9806. _('<b>Shortcut Key List</b>'))
  9807. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  9808. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  9809. settings = QSettings("Open Source", "FlatCAM")
  9810. if settings.contains("notebook_font_size"):
  9811. fsize = settings.value('notebook_font_size', type=int)
  9812. else:
  9813. fsize = 12
  9814. tsize = fsize + int(fsize / 2)
  9815. # selected_text = (_('''
  9816. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  9817. #
  9818. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  9819. # The normal flow when working in FlatCAM is the following:</span></p>
  9820. #
  9821. # <ol>
  9822. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  9823. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  9824. # even dragging and dropping the files on the GUI.<br />
  9825. # <br />
  9826. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  9827. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  9828. # &nbsp;</li>
  9829. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  9830. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  9831. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  9832. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  9833. # <br />
  9834. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  9835. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  9836. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  9837. # it even if it was out of focus.<br />
  9838. # <br />
  9839. # You can change the parameters in this screen and the flow direction is like this:<br />
  9840. # <br />
  9841. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  9842. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  9843. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  9844. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  9845. # </ol>
  9846. #
  9847. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  9848. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  9849. # <strong>F3</strong>.</span></p>
  9850. #
  9851. # ''').format(fsize=fsize, tsize=tsize))
  9852. selected_text = '''
  9853. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  9854. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  9855. {s1}</span></p>
  9856. <ol>
  9857. <li><span style="font-size:{fsize}px">{s2}<br />
  9858. <br />
  9859. {s3}</span><br />
  9860. &nbsp;</li>
  9861. <li><span style="font-size:{fsize}px">{s4}<br />
  9862. &nbsp;</li>
  9863. <br />
  9864. <li><span style="font-size:{fsize}px">{s5}<br />
  9865. &nbsp;</li>
  9866. <br />
  9867. <li><span style="font-size:{fsize}px">{s6}<br />
  9868. <br />
  9869. {s7}</span></li>
  9870. </ol>
  9871. <p><span style="font-size:{fsize}px">{s8}</span></p>
  9872. '''.format(
  9873. title=_("Selected Tab - Choose an Item from Project Tab"),
  9874. subtitle=_("Details"),
  9875. s1=_("The normal flow when working in FlatCAM is the following:"),
  9876. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  9877. "using either the toolbars, key shortcuts or even dragging and dropping the "
  9878. "files on the GUI."),
  9879. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  9880. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  9881. "actions offered within the app."),
  9882. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  9883. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  9884. "SELECTED TAB will be updated with the object properties according to its kind: "
  9885. "Gerber, Excellon, Geometry or CNCJob object."),
  9886. s5=_("If the selection of the object is done on the canvas by single click instead, "
  9887. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  9888. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  9889. "the SELECTED TAB and populate it even if it was out of focus."),
  9890. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  9891. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  9892. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  9893. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  9894. "(again, done in SELECTED TAB) --> Save GCode."),
  9895. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  9896. "or through its own key shortcut: <b>F3</b>."),
  9897. tsize=tsize,
  9898. fsize=fsize
  9899. )
  9900. sel_title.setText(selected_text)
  9901. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  9902. self.ui.selected_scroll_area.setWidget(sel_title)
  9903. def setup_obj_classes(self):
  9904. """
  9905. Sets up application specifics on the FlatCAMObj class.
  9906. :return: None
  9907. """
  9908. FlatCAMObj.app = self
  9909. ObjectCollection.app = self
  9910. Gerber.app = self
  9911. Excellon.app = self
  9912. Geometry.app = self
  9913. CNCjob.app = self
  9914. FCProcess.app = self
  9915. FCProcessContainer.app = self
  9916. def version_check(self):
  9917. """
  9918. Checks for the latest version of the program. Alerts the
  9919. user if theirs is outdated. This method is meant to be run
  9920. in a separate thread.
  9921. :return: None
  9922. """
  9923. self.log.debug("version_check()")
  9924. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  9925. full_url = App.version_url + \
  9926. "?s=" + str(self.defaults['global_serial']) + \
  9927. "&v=" + str(self.version) + \
  9928. "&os=" + str(self.os) + \
  9929. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  9930. else:
  9931. # no_stats dict; just so it won't break things on website
  9932. no_ststs_dict = {}
  9933. no_ststs_dict["global_ststs"] = {}
  9934. full_url = App.version_url + \
  9935. "?s=" + str(self.defaults['global_serial']) + \
  9936. "&v=" + str(self.version) + \
  9937. "&os=" + str(self.os) + \
  9938. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  9939. App.log.debug("Checking for updates @ %s" % full_url)
  9940. # ## Get the data
  9941. try:
  9942. f = urllib.request.urlopen(full_url)
  9943. except:
  9944. # App.log.warning("Failed checking for latest version. Could not connect.")
  9945. self.log.warning("Failed checking for latest version. Could not connect.")
  9946. self.inform.emit('[WARNING_NOTCL] %s' %
  9947. _("Failed checking for latest version. Could not connect."))
  9948. return
  9949. try:
  9950. data = json.load(f)
  9951. except Exception as e:
  9952. App.log.error("Could not parse information about latest version.")
  9953. self.inform.emit('[ERROR_NOTCL] %s' %
  9954. _("Could not parse information about latest version."))
  9955. App.log.debug("json.load(): %s" % str(e))
  9956. f.close()
  9957. return
  9958. f.close()
  9959. # ## Latest version?
  9960. if self.version >= data["version"]:
  9961. App.log.debug("FlatCAM is up to date!")
  9962. self.inform.emit('[success] %s' %
  9963. _("FlatCAM is up to date!"))
  9964. return
  9965. App.log.debug("Newer version available.")
  9966. self.message.emit(
  9967. _("Newer Version Available"),
  9968. _("There is a newer version of FlatCAM available for download:\n\n") +
  9969. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  9970. _("info")
  9971. )
  9972. def on_plotcanvas_setup(self, container=None):
  9973. """
  9974. This is doing the setup for the plot area (VisPy canvas)
  9975. :param container: widget where to install the canvas
  9976. :return: None
  9977. """
  9978. if container:
  9979. plot_container = container
  9980. else:
  9981. plot_container = self.ui.right_layout
  9982. if self.is_legacy is False:
  9983. self.plotcanvas = PlotCanvas(plot_container, self)
  9984. else:
  9985. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  9986. # So it can receive key presses
  9987. self.plotcanvas.native.setFocus()
  9988. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  9989. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  9990. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  9991. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  9992. # Keys over plot enabled
  9993. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  9994. if self.defaults['global_cursor_type'] == 'small':
  9995. self.app_cursor = self.plotcanvas.new_cursor()
  9996. else:
  9997. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  9998. if self.ui.grid_snap_btn.isChecked():
  9999. self.app_cursor.enabled = True
  10000. else:
  10001. self.app_cursor.enabled = False
  10002. if self.is_legacy is False:
  10003. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  10004. else:
  10005. # will use the default Matplotlib axes
  10006. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  10007. def on_zoom_fit(self, event):
  10008. """
  10009. Callback for zoom-out request. This can be either from the corresponding
  10010. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  10011. with axes limits from the geometry bounds of all objects.
  10012. :param event: Ignored.
  10013. :return: None
  10014. """
  10015. if self.is_legacy is False:
  10016. self.plotcanvas.fit_view()
  10017. else:
  10018. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  10019. width = xmax - xmin
  10020. height = ymax - ymin
  10021. xmin -= 0.05 * width
  10022. xmax += 0.05 * width
  10023. ymin -= 0.05 * height
  10024. ymax += 0.05 * height
  10025. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  10026. def on_zoom_in(self):
  10027. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  10028. def on_zoom_out(self):
  10029. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  10030. def disable_all_plots(self):
  10031. self.report_usage("disable_all_plots()")
  10032. self.disable_plots(self.collection.get_list())
  10033. self.inform.emit('[success] %s' %
  10034. _("All plots disabled."))
  10035. def disable_other_plots(self):
  10036. self.report_usage("disable_other_plots()")
  10037. self.disable_plots(self.collection.get_non_selected())
  10038. self.inform.emit('[success] %s' %
  10039. _("All non selected plots disabled."))
  10040. def enable_all_plots(self):
  10041. self.report_usage("enable_all_plots()")
  10042. self.enable_plots(self.collection.get_list())
  10043. self.inform.emit('[success] %s' %
  10044. _("All plots enabled."))
  10045. def on_enable_sel_plots(self):
  10046. log.debug("App.on_enable_sel_plot()")
  10047. object_list = self.collection.get_selected()
  10048. self.enable_plots(objects=object_list)
  10049. self.inform.emit('[success] %s' %
  10050. _("Selected plots enabled..."))
  10051. def on_disable_sel_plots(self):
  10052. log.debug("App.on_disable_sel_plot()")
  10053. # self.inform.emit(_("Disabling plots ..."))
  10054. object_list = self.collection.get_selected()
  10055. self.disable_plots(objects=object_list)
  10056. self.inform.emit('[success] %s' %
  10057. _("Selected plots disabled..."))
  10058. def enable_plots(self, objects):
  10059. """
  10060. Disables plots
  10061. :param objects: list of Objects to be enabled
  10062. :return:
  10063. """
  10064. log.debug("Enabling plots ...")
  10065. # self.inform.emit(_("Working ..."))
  10066. for obj in objects:
  10067. if obj.options['plot'] is False:
  10068. obj.options.set_change_callback(lambda x: None)
  10069. obj.options['plot'] = True
  10070. obj.options.set_change_callback(obj.on_options_change)
  10071. def worker_task(objects):
  10072. with self.proc_container.new(_("Enabling plots ...")):
  10073. for obj in objects:
  10074. # obj.options['plot'] = True
  10075. if isinstance(obj, FlatCAMCNCjob):
  10076. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  10077. else:
  10078. obj.plot(visible=True)
  10079. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  10080. # self.plots_updated.emit()
  10081. def disable_plots(self, objects):
  10082. """
  10083. Disables plots
  10084. :param objects: list of Objects to be disabled
  10085. :return:
  10086. """
  10087. # if no objects selected then do nothing
  10088. if not self.collection.get_selected():
  10089. return
  10090. log.debug("Disabling plots ...")
  10091. # self.inform.emit(_("Working ..."))
  10092. for obj in objects:
  10093. if obj.options['plot'] is True:
  10094. obj.options.set_change_callback(lambda x: None)
  10095. obj.options['plot'] = False
  10096. obj.options.set_change_callback(obj.on_options_change)
  10097. try:
  10098. self.delete_selection_shape()
  10099. except Exception as e:
  10100. log.debug("App.disable_plots() --> %s" % str(e))
  10101. # self.plots_updated.emit()
  10102. def worker_task(objects):
  10103. with self.proc_container.new(_("Disabling plots ...")):
  10104. for obj in objects:
  10105. # obj.options['plot'] = True
  10106. if isinstance(obj, FlatCAMCNCjob):
  10107. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  10108. else:
  10109. obj.plot(visible=False)
  10110. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  10111. def toggle_plots(self, objects):
  10112. """
  10113. Toggle plots visibility
  10114. :param objects: list of Objects for which to be toggled the visibility
  10115. :return:
  10116. """
  10117. # if no objects selected then do nothing
  10118. if not self.collection.get_selected():
  10119. return
  10120. log.debug("Toggling plots ...")
  10121. self.inform.emit(_("Working ..."))
  10122. for obj in objects:
  10123. if obj.options['plot'] is False:
  10124. obj.options['plot'] = True
  10125. else:
  10126. obj.options['plot'] = False
  10127. self.plots_updated.emit()
  10128. def clear_plots(self):
  10129. objects = self.collection.get_list()
  10130. for obj in objects:
  10131. obj.clear(obj == objects[-1])
  10132. # Clear pool to free memory
  10133. self.clear_pool()
  10134. def generate_cnc_job(self, objects):
  10135. self.report_usage("generate_cnc_job()")
  10136. # for obj in objects:
  10137. # obj.generatecncjob()
  10138. for obj in objects:
  10139. obj.on_generatecnc_button_click()
  10140. def save_project(self, filename, quit_action=False, silent=False):
  10141. """
  10142. Saves the current project to the specified file.
  10143. :param filename: Name of the file in which to save.
  10144. :type filename: str
  10145. :param quit_action: if the project saving will be followed by an app quit; boolean
  10146. :param silent: if True will not display status messages
  10147. :return: None
  10148. """
  10149. self.log.debug("save_project()")
  10150. self.save_in_progress = True
  10151. with self.proc_container.new(_("Saving FlatCAM Project")):
  10152. # Capture the latest changes
  10153. # Current object
  10154. try:
  10155. self.collection.get_active().read_form()
  10156. except:
  10157. self.log.debug("There was no active object")
  10158. pass
  10159. # Project options
  10160. self.options_read_form()
  10161. # Serialize the whole project
  10162. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  10163. "options": self.options,
  10164. "version": self.version}
  10165. if self.defaults["global_save_compressed"] is True:
  10166. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  10167. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  10168. # # Write
  10169. f.write(g)
  10170. self.inform.emit('[success] %s: %s' %
  10171. (_("Project saved to"), filename))
  10172. else:
  10173. # Open file
  10174. try:
  10175. f = open(filename, 'w')
  10176. except IOError:
  10177. App.log.error("Failed to open file for saving: %s", filename)
  10178. return
  10179. # Write
  10180. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  10181. f.close()
  10182. # verification of the saved project
  10183. # Open and parse
  10184. try:
  10185. saved_f = open(filename, 'r')
  10186. except IOError:
  10187. if silent is False:
  10188. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  10189. (_("Failed to verify project file"), filename, _("Retry to save it."))
  10190. )
  10191. return
  10192. try:
  10193. saved_d = json.load(saved_f, object_hook=dict2obj)
  10194. except:
  10195. if silent is False:
  10196. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  10197. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  10198. )
  10199. f.close()
  10200. return
  10201. saved_f.close()
  10202. if silent is False:
  10203. if 'version' in saved_d:
  10204. self.inform.emit('[success] %s: %s' %
  10205. (_("Project saved to"), filename))
  10206. else:
  10207. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  10208. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  10209. )
  10210. settings = QSettings("Open Source", "FlatCAM")
  10211. lock_state = self.ui.lock_action.isChecked()
  10212. settings.setValue('toolbar_lock', lock_state)
  10213. # This will write the setting to the platform specific storage.
  10214. del settings
  10215. # if quit:
  10216. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  10217. # t.start()
  10218. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  10219. def start_delayed_quit(self, delay, filename, should_quit=None):
  10220. """
  10221. :param delay: period of checking if project file size is more than zero; in seconds
  10222. :param filename: the name of the project file to be checked periodically for size more than zero
  10223. :param should_quit: if the task finished will be followed by an app quit; boolean
  10224. :return:
  10225. """
  10226. to_quit = should_quit
  10227. self.save_timer = QtCore.QTimer()
  10228. self.save_timer.setInterval(delay)
  10229. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  10230. self.save_timer.start()
  10231. def check_project_file_size(self, filename, should_quit=None):
  10232. """
  10233. :param filename: the name of the project file to be checked periodically for size more than zero
  10234. :param should_quit: will quit the app if True; boolean
  10235. :return:
  10236. """
  10237. try:
  10238. if os.stat(filename).st_size > 0:
  10239. self.save_in_progress = False
  10240. self.save_timer.stop()
  10241. if should_quit:
  10242. self.app_quit.emit()
  10243. except Exception as e:
  10244. traceback.print_exc()
  10245. def on_plotarea_tab_closed(self, tab_idx):
  10246. widget = self.ui.plot_tab_area.widget(tab_idx)
  10247. if widget is not None:
  10248. print(widget.objectName())
  10249. if widget.objectName() == 'text_editor_tab':
  10250. print("aha")
  10251. widget.deleteLater()
  10252. self.ui.plot_tab_area.removeTab(tab_idx)
  10253. def on_options_app2project(self):
  10254. """
  10255. Callback for Options->Transfer Options->App=>Project. Copies options
  10256. from application defaults to project defaults.
  10257. :return: None
  10258. """
  10259. self.report_usage("on_options_app2project")
  10260. self.defaults_read_form()
  10261. self.options.update(self.defaults)
  10262. self.options_write_form()
  10263. # def on_options_project2app(self):
  10264. # """
  10265. # Callback for Options->Transfer Options->Project=>App. Copies options
  10266. # from project defaults to application defaults.
  10267. #
  10268. # :return: None
  10269. # """
  10270. #
  10271. # self.report_usage("on_options_project2app")
  10272. #
  10273. # self.options_read_form()
  10274. # self.defaults.update(self.options)
  10275. # self.defaults_write_form()
  10276. # def on_options_project2object(self):
  10277. # """
  10278. # Callback for Options->Transfer Options->Project=>Object. Copies options
  10279. # from project defaults to the currently selected object.
  10280. #
  10281. # :return: None
  10282. # """
  10283. #
  10284. # self.report_usage("on_options_project2object")
  10285. #
  10286. # self.options_read_form()
  10287. # obj = self.collection.get_active()
  10288. # if obj is None:
  10289. # self.inform.emit('[WARNING_NOTCL] %s' %
  10290. # _("No object selected."))
  10291. # return
  10292. # for option in self.options:
  10293. # if option.find(obj.kind + "_") == 0:
  10294. # oname = option[len(obj.kind) + 1:]
  10295. # obj.options[oname] = self.options[option]
  10296. # obj.to_form() # Update UI
  10297. # def on_options_object2project(self):
  10298. # """
  10299. # Callback for Options->Transfer Options->Object=>Project. Copies options
  10300. # from the currently selected object to project defaults.
  10301. #
  10302. # :return: None
  10303. # """
  10304. #
  10305. # self.report_usage("on_options_object2project")
  10306. #
  10307. # obj = self.collection.get_active()
  10308. # if obj is None:
  10309. # self.inform.emit('[WARNING_NOTCL] %s' %
  10310. # _("No object selected."))
  10311. # return
  10312. # obj.read_form()
  10313. # for option in obj.options:
  10314. # if option in ['name']: # TODO: Handle this better...
  10315. # continue
  10316. # self.options[obj.kind + "_" + option] = obj.options[option]
  10317. # self.options_write_form()
  10318. # def on_options_object2app(self):
  10319. # """
  10320. # Callback for Options->Transfer Options->Object=>App. Copies options
  10321. # from the currently selected object to application defaults.
  10322. #
  10323. # :return: None
  10324. # """
  10325. #
  10326. # self.report_usage("on_options_object2app")
  10327. #
  10328. # obj = self.collection.get_active()
  10329. # if obj is None:
  10330. # self.inform.emit('[WARNING_NOTCL] %s' %
  10331. # _("No object selected."))
  10332. # return
  10333. # obj.read_form()
  10334. # for option in obj.options:
  10335. # if option in ['name']: # TODO: Handle this better...
  10336. # continue
  10337. # self.defaults[obj.kind + "_" + option] = obj.options[option]
  10338. # self.defaults_write_form()
  10339. # def on_options_app2object(self):
  10340. # """
  10341. # Callback for Options->Transfer Options->App=>Object. Copies options
  10342. # from application defaults to the currently selected object.
  10343. #
  10344. # :return: None
  10345. # """
  10346. #
  10347. # self.report_usage("on_options_app2object")
  10348. #
  10349. # self.defaults_read_form()
  10350. # obj = self.collection.get_active()
  10351. # if obj is None:
  10352. # self.inform.emit('[WARNING_NOTCL] %s' %
  10353. # _("No object selected."))
  10354. # return
  10355. # for option in self.defaults:
  10356. # if option.find(obj.kind + "_") == 0:
  10357. # oname = option[len(obj.kind) + 1:]
  10358. # obj.options[oname] = self.defaults[option]
  10359. # obj.to_form() # Update UI
  10360. class ArgsThread(QtCore.QObject):
  10361. open_signal = pyqtSignal(list)
  10362. start = pyqtSignal()
  10363. if sys.platform == 'win32':
  10364. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  10365. else:
  10366. address = ('/tmp/testipc', 'AF_UNIX')
  10367. def __init__(self):
  10368. super(ArgsThread, self).__init__()
  10369. self.start.connect(self.run)
  10370. def my_loop(self, address):
  10371. try:
  10372. listener = Listener(*address)
  10373. while True:
  10374. conn = listener.accept()
  10375. self.serve(conn)
  10376. except socket.error as e:
  10377. conn = Client(*address)
  10378. conn.send(sys.argv)
  10379. conn.send('close')
  10380. # close the current instance only if there are args
  10381. if len(sys.argv) > 1:
  10382. sys.exit()
  10383. def serve(self, conn):
  10384. while True:
  10385. msg = conn.recv()
  10386. if msg == 'close':
  10387. break
  10388. self.open_signal.emit(msg)
  10389. conn.close()
  10390. # the decorator is a must; without it this technique will not work unless the start signal is connected
  10391. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  10392. @pyqtSlot()
  10393. def run(self):
  10394. self.my_loop(self.address)
  10395. class GracefulException(Exception):
  10396. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  10397. def __init__(self):
  10398. super().__init__()
  10399. def __str__(self):
  10400. return '\n\n%s' % _("The user requested a graceful exit of the current task.")
  10401. # end of file