FlatCAMApp.py 410 KB

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