FlatCAMApp.py 592 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957
  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 shutil
  16. import stat
  17. from datetime import datetime
  18. import time
  19. from stat import S_IREAD, S_IRGRP, S_IROTH
  20. import ctypes
  21. import traceback
  22. from shapely.geometry import Point, MultiPolygon
  23. from io import StringIO
  24. from reportlab.graphics import renderPDF
  25. from reportlab.pdfgen import canvas
  26. from reportlab.lib.units import inch, mm
  27. from reportlab.lib.pagesizes import landscape, portrait
  28. from svglib.svglib import svg2rlg
  29. import gc
  30. from xml.dom.minidom import parseString as parse_xml_string
  31. from multiprocessing.connection import Listener, Client
  32. from multiprocessing import Pool
  33. import socket
  34. # ####################################################################################################################
  35. # ################################### Imports part of FlatCAM #############################################
  36. # ####################################################################################################################
  37. # Diverse
  38. from FlatCAMCommon import LoudDict, color_variant
  39. from FlatCAMBookmark import BookmarkManager
  40. from FlatCAMDB import ToolsDB2
  41. from vispy.gloo.util import _screenshot
  42. from vispy.io import write_png
  43. # FlatCAM Objects
  44. from flatcamObjects.ObjectCollection import *
  45. from flatcamObjects.FlatCAMObj import FlatCAMObj
  46. from flatcamObjects.FlatCAMCNCJob import CNCJobObject
  47. from flatcamObjects.FlatCAMDocument import DocumentObject
  48. from flatcamObjects.FlatCAMExcellon import ExcellonObject
  49. from flatcamObjects.FlatCAMGeometry import GeometryObject
  50. from flatcamObjects.FlatCAMGerber import GerberObject
  51. from flatcamObjects.FlatCAMScript import ScriptObject
  52. # FlatCAM Parsing files
  53. from flatcamParsers.ParseExcellon import Excellon
  54. from flatcamParsers.ParseGerber import Gerber
  55. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  56. # FlatCAM GUI
  57. from flatcamGUI.PlotCanvas import *
  58. from flatcamGUI.PlotCanvasLegacy import *
  59. from flatcamGUI.FlatCAMGUI import *
  60. from flatcamGUI.GUIElements import FCFileSaveDialog
  61. # FlatCAM Pre-processors
  62. from FlatCAMPostProc import load_preprocessors
  63. # FlatCAM Editors
  64. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  65. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  66. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  67. from flatcamEditors.FlatCAMTextEditor import TextEditor
  68. from flatcamParsers.ParseHPGL2 import HPGL2
  69. # FlatCAM Workers
  70. from FlatCAMProcess import *
  71. from FlatCAMWorkerStack import WorkerStack
  72. # FlatCAM Tools
  73. from flatcamTools import *
  74. # FlatCAM Translation
  75. import gettext
  76. import FlatCAMTranslation as fcTranslate
  77. import builtins
  78. if sys.platform == 'win32':
  79. import winreg
  80. fcTranslate.apply_language('strings')
  81. if '_' not in builtins.__dict__:
  82. _ = gettext.gettext
  83. class App(QtCore.QObject):
  84. """
  85. The main application class. The constructor starts the GUI.
  86. """
  87. # ###############################################################################################################
  88. # ########################################## App ################################################################
  89. # ###############################################################################################################
  90. # ###############################################################################################################
  91. # ######################################### LOGGING #############################################################
  92. # ###############################################################################################################
  93. log = logging.getLogger('base')
  94. log.setLevel(logging.DEBUG)
  95. # log.setLevel(logging.WARNING)
  96. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  97. handler = logging.StreamHandler()
  98. handler.setFormatter(formatter)
  99. log.addHandler(handler)
  100. # ###############################################################################################################
  101. # #################################### Get Cmd Line Options #####################################################
  102. # ###############################################################################################################
  103. cmd_line_shellfile = ''
  104. cmd_line_shellvar = ''
  105. cmd_line_headless = None
  106. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  107. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  108. "FlatCam.py --headless=1"
  109. try:
  110. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  111. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  112. "shellvar=",
  113. "headless=",
  114. "multiprocessing-fork="])
  115. except getopt.GetoptError:
  116. print(cmd_line_help)
  117. sys.exit(2)
  118. for opt, arg in cmd_line_options:
  119. if opt == '-h':
  120. print(cmd_line_help)
  121. sys.exit()
  122. elif opt == '--shellfile':
  123. cmd_line_shellfile = arg
  124. elif opt == '--shellvar':
  125. cmd_line_shellvar = arg
  126. elif opt == '--headless':
  127. try:
  128. cmd_line_headless = eval(arg)
  129. except NameError:
  130. pass
  131. # ###############################################################################################################
  132. # ################################### Version and VERSION DATE ##################################################
  133. # ###############################################################################################################
  134. version = 8.992
  135. version_date = "2020/05/01"
  136. beta = True
  137. engine = '3D'
  138. # current date now
  139. date = str(datetime.today()).rpartition('.')[0]
  140. date = ''.join(c for c in date if c not in ':-')
  141. date = date.replace(' ', '_')
  142. # ###############################################################################################################
  143. # ############################################ URLS's ###########################################################
  144. # ###############################################################################################################
  145. # URL for update checks and statistics
  146. version_url = "http://flatcam.org/version"
  147. # App URL
  148. app_url = "http://flatcam.org"
  149. # Manual URL
  150. manual_url = "http://flatcam.org/manual/index.html"
  151. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  152. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  153. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  154. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  155. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  156. # this variable will hold the project status
  157. # if True it will mean that the project was modified and not saved
  158. should_we_save = False
  159. # flag is True if saving action has been triggered
  160. save_in_progress = False
  161. # ###############################################################################################################
  162. # ####################################### APP Signals ######################################################
  163. # ###############################################################################################################
  164. # Inform the user
  165. # Handled by:
  166. # * App.info() --> Print on the status bar
  167. inform = QtCore.pyqtSignal(str)
  168. app_quit = QtCore.pyqtSignal()
  169. # General purpose background task
  170. worker_task = QtCore.pyqtSignal(dict)
  171. # File opened
  172. # Handled by:
  173. # * register_folder()
  174. # * register_recent()
  175. # Note: Setting the parameters to unicode does not seem
  176. # to have an effect. Then are received as Qstring
  177. # anyway.
  178. # File type and filename
  179. file_opened = QtCore.pyqtSignal(str, str)
  180. # File type and filename
  181. file_saved = QtCore.pyqtSignal(str, str)
  182. # Percentage of progress
  183. progress = QtCore.pyqtSignal(int)
  184. plots_updated = QtCore.pyqtSignal()
  185. # Emitted by new_object() and passes the new object as argument, plot flag.
  186. # on_object_created() adds the object to the collection, plots on appropriate flag
  187. # and emits new_object_available.
  188. object_created = QtCore.pyqtSignal(object, bool, bool)
  189. # Emitted when a object has been changed (like scaled, mirrored)
  190. object_changed = QtCore.pyqtSignal(object)
  191. # Emitted after object has been plotted.
  192. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  193. object_plotted = QtCore.pyqtSignal(object)
  194. # Emitted when a new object has been added or deleted from/to the collection
  195. object_status_changed = QtCore.pyqtSignal(object, str, str)
  196. message = QtCore.pyqtSignal(str, str, str)
  197. # Emmited when shell command is finished(one command only)
  198. shell_command_finished = QtCore.pyqtSignal(object)
  199. # Emitted when multiprocess pool has been recreated
  200. pool_recreated = QtCore.pyqtSignal(object)
  201. # Emitted when an unhandled exception happens
  202. # in the worker task.
  203. thread_exception = QtCore.pyqtSignal(object)
  204. # used to signal that there are arguments for the app
  205. args_at_startup = QtCore.pyqtSignal(list)
  206. # a reusable signal to replot a list of objects
  207. # should be disconnected after use so it can be reused
  208. replot_signal = pyqtSignal(list)
  209. # signal emitted when jumping
  210. jump_signal = pyqtSignal(tuple)
  211. # signal emitted when jumping
  212. locate_signal = pyqtSignal(tuple, str)
  213. # close app signal
  214. close_app_signal = pyqtSignal()
  215. # will perform the cleanup operation after a Graceful Exit
  216. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  217. # graphic residues behind
  218. cleanup = pyqtSignal()
  219. def __init__(self, user_defaults=True):
  220. """
  221. Starts the application.
  222. :return: app
  223. :rtype: App
  224. """
  225. App.log.info("FlatCAM Starting...")
  226. self.main_thread = QtWidgets.QApplication.instance().thread()
  227. # ############################################################################################################
  228. # ################# Setup the listening thread for another instance launching with args ######################
  229. # ############################################################################################################
  230. if sys.platform == 'win32' or sys.platform == 'linux':
  231. # make sure the thread is stored by using a self. otherwise it's garbage collected
  232. self.th = QtCore.QThread()
  233. self.th.start(priority=QtCore.QThread.LowestPriority)
  234. self.new_launch = ArgsThread()
  235. self.new_launch.open_signal[list].connect(self.on_startup_args)
  236. self.new_launch.moveToThread(self.th)
  237. self.new_launch.start.emit()
  238. # ############################################################################################################
  239. # # ######################################## OS-specific #####################################################
  240. # ############################################################################################################
  241. portable = False
  242. # Folder for user settings.
  243. if sys.platform == 'win32':
  244. from win32comext.shell import shell, shellcon
  245. if platform.architecture()[0] == '32bit':
  246. App.log.debug("Win32!")
  247. else:
  248. App.log.debug("Win64!")
  249. # #######################################################################################################
  250. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  251. # #######################################################################################################
  252. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  253. try:
  254. with open(config_file, 'r'):
  255. pass
  256. except FileNotFoundError:
  257. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  258. try:
  259. with open(config_file, 'r') as f:
  260. try:
  261. for line in f:
  262. param = str(line).replace('\n', '').rpartition('=')
  263. if param[0] == 'portable':
  264. try:
  265. portable = eval(param[2])
  266. except NameError:
  267. portable = False
  268. if param[0] == 'headless':
  269. if param[2].lower() == 'true':
  270. self.cmd_line_headless = 1
  271. else:
  272. self.cmd_line_headless = None
  273. except Exception as e:
  274. log.debug('App.__init__() -->%s' % str(e))
  275. return
  276. except FileNotFoundError as e:
  277. log.debug(str(e))
  278. pass
  279. if portable is False:
  280. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  281. else:
  282. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  283. self.os = 'windows'
  284. else: # Linux/Unix/MacOS
  285. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  286. self.os = 'unix'
  287. # ############################################################################################################
  288. # ################################# Setup folders and files ##################################################
  289. # ############################################################################################################
  290. if not os.path.exists(self.data_path):
  291. os.makedirs(self.data_path)
  292. App.log.debug('Created data folder: ' + self.data_path)
  293. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  294. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  295. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  296. if not os.path.exists(self.preprocessorpaths):
  297. os.makedirs(self.preprocessorpaths)
  298. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  299. # create geo_tools_db.FlatDB file if there is none
  300. try:
  301. f = open(self.data_path + '/geo_tools_db.FlatDB')
  302. f.close()
  303. except IOError:
  304. App.log.debug('Creating empty geo_tool_db.FlatDB')
  305. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  306. json.dump({}, f)
  307. f.close()
  308. # create current_defaults.FlatConfig file if there is none
  309. try:
  310. f = open(self.data_path + '/current_defaults.FlatConfig')
  311. f.close()
  312. except IOError:
  313. App.log.debug('Creating empty current_defaults.FlatConfig')
  314. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  315. json.dump({}, f)
  316. f.close()
  317. # create factory_defaults.FlatConfig file if there is none
  318. try:
  319. f = open(self.data_path + '/factory_defaults.FlatConfig')
  320. f.close()
  321. except IOError:
  322. App.log.debug('Creating empty factory_defaults.FlatConfig')
  323. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  324. json.dump({}, f)
  325. f.close()
  326. # create a recent files json file if there is none
  327. try:
  328. f = open(self.data_path + '/recent.json')
  329. f.close()
  330. except IOError:
  331. App.log.debug('Creating empty recent.json')
  332. f = open(self.data_path + '/recent.json', 'w')
  333. json.dump([], f)
  334. f.close()
  335. # create a recent projects json file if there is none
  336. try:
  337. fp = open(self.data_path + '/recent_projects.json')
  338. fp.close()
  339. except IOError:
  340. App.log.debug('Creating empty recent_projects.json')
  341. fp = open(self.data_path + '/recent_projects.json', 'w')
  342. json.dump([], fp)
  343. fp.close()
  344. # Application directory. CHDIR to it. Otherwise, trying to load
  345. # GUI icons will fail as their path is relative.
  346. # This will fail under cx_freeze ...
  347. self.app_home = os.path.dirname(os.path.realpath(__file__))
  348. App.log.debug("Application path is " + self.app_home)
  349. App.log.debug("Started in " + os.getcwd())
  350. # cx_freeze workaround
  351. if os.path.isfile(self.app_home):
  352. self.app_home = os.path.dirname(self.app_home)
  353. os.chdir(self.app_home)
  354. # ############################################################################################################
  355. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  356. # ############################################################################################################
  357. self.defaults = LoudDict()
  358. self.defaults.update({
  359. # Global APP Preferences
  360. "decimals_inch": 4,
  361. "decimals_metric": 4,
  362. "version": self.version,
  363. "first_run": True,
  364. "units": "MM",
  365. "global_serial": 0,
  366. "global_stats": dict(),
  367. "global_tabs_detachable": True,
  368. "global_jump_ref": 'abs',
  369. "global_locate_pt": 'bl',
  370. "global_tpdf_tmargin": 15.0,
  371. "global_tpdf_bmargin": 10.0,
  372. "global_tpdf_lmargin": 20.0,
  373. "global_tpdf_rmargin": 20.0,
  374. "global_autosave": False,
  375. "global_autosave_timeout": 300000,
  376. "global_tcl_path": '',
  377. # General
  378. "global_graphic_engine": '3D',
  379. "global_app_level": 'b',
  380. "global_portable": False,
  381. "global_language": 'English',
  382. "global_version_check": True,
  383. "global_send_stats": True,
  384. "global_pan_button": '2',
  385. "global_mselect_key": 'Control',
  386. "global_project_at_startup": False,
  387. "global_systray_icon": True,
  388. "global_project_autohide": True,
  389. "global_toggle_tooltips": True,
  390. "global_worker_number": 2,
  391. "global_tolerance": 0.005,
  392. "global_open_style": True,
  393. "global_delete_confirmation": True,
  394. "global_compression_level": 3,
  395. "global_save_compressed": True,
  396. "global_machinist_setting": False,
  397. # Global GUI Preferences
  398. "global_gridx": 1.0,
  399. "global_gridy": 1.0,
  400. "global_snap_max": 0.05,
  401. "global_workspace": False,
  402. "global_workspaceT": "A4",
  403. "global_workspace_orientation": 'p',
  404. "global_grid_context_menu": {
  405. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  406. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  407. },
  408. "global_sel_fill": '#a5a5ffbf',
  409. "global_sel_line": '#0000ffbf',
  410. "global_alt_sel_fill": '#BBF268BF',
  411. "global_alt_sel_line": '#006E20BF',
  412. "global_draw_color": '#FF0000',
  413. "global_sel_draw_color": '#0000FF',
  414. "global_proj_item_color": '#000000',
  415. "global_proj_item_dis_color": '#b7b7cb',
  416. "global_activity_icon": 'Ball green',
  417. "global_toolbar_view": 511,
  418. "global_background_timeout": 300000, # Default value is 5 minutes
  419. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  420. # (python trace only for unknown errors),
  421. # 1 = show trace(show trace always),
  422. # 2 = (For the future).
  423. # Persistence
  424. "global_last_folder": None,
  425. "global_last_save_folder": None,
  426. # Default window geometry
  427. "global_def_win_x": 100,
  428. "global_def_win_y": 100,
  429. "global_def_win_w": 1024,
  430. "global_def_win_h": 650,
  431. "global_def_notebook_width": 1,
  432. # Constants...
  433. "global_defaults_save_period_ms": 20000, # Time between default saves.
  434. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  435. "global_shell_at_startup": False, # Show the shell at startup.
  436. "global_recent_limit": 10, # Max. items in recent list.
  437. "global_bookmarks": dict(),
  438. "global_bookmarks_limit": 10,
  439. "fit_key": 'V',
  440. "zoom_out_key": '-',
  441. "zoom_in_key": '=',
  442. "grid_toggle_key": 'G',
  443. "global_zoom_ratio": 1.5,
  444. "global_point_clipboard_format": "(%.*f, %.*f)",
  445. "global_zdownrate": None,
  446. # General GUI Settings
  447. "global_theme": 'white',
  448. "global_gray_icons": False,
  449. "global_hover": False,
  450. "global_selection_shape": True,
  451. "global_layout": "compact",
  452. "global_cursor_type": "small",
  453. "global_cursor_size": 20,
  454. "global_cursor_width": 2,
  455. "global_cursor_color": '#FF0000',
  456. "global_cursor_color_enabled": True,
  457. # Gerber General
  458. "gerber_plot": True,
  459. "gerber_solid": True,
  460. "gerber_multicolored": False,
  461. "gerber_circle_steps": 64,
  462. "gerber_use_buffer_for_union": True,
  463. "gerber_clean_apertures": True,
  464. "gerber_extra_buffering": True,
  465. "gerber_plot_fill": '#BBF268BF',
  466. "gerber_plot_line": '#006E20BF',
  467. "gerber_def_units": 'IN',
  468. "gerber_def_zeros": 'L',
  469. "gerber_save_filters": "Gerber File .gbr (*.gbr);;Gerber File .bot (*.bot);;Gerber File .bsm (*.bsm);;"
  470. "Gerber File .cmp (*.cmp);;Gerber File .crc (*.crc);;Gerber File .crs (*.crs);;"
  471. "Gerber File .gb0 (*.gb0);;Gerber File .gb1 (*.gb1);;Gerber File .gb2 (*.gb2);;"
  472. "Gerber File .gb3 (*.gb3);;Gerber File .gb4 (*.gb4);;Gerber File .gb5 (*.gb5);;"
  473. "Gerber File .gb6 (*.gb6);;Gerber File .gb7 (*.gb7);;Gerber File .gb8 (*.gb8);;"
  474. "Gerber File .gb9 (*.gb9);;Gerber File .gbd (*.gbd);;Gerber File .gbl (*.gbl);;"
  475. "Gerber File .gbo (*.gbo);;Gerber File .gbp (*.gbp);;Gerber File .gbs (*.gbs);;"
  476. "Gerber File .gdo (*.gdo);;Gerber File .ger (*.ger);;Gerber File .gko (*.gko);;"
  477. "Gerber File .gm1 (*.gm1);;Gerber File .gm2 (*.gm2);;Gerber File .gm3 (*.gm3);;"
  478. "Gerber File .grb (*.grb);;Gerber File .gtl (*.gtl);;Gerber File .gto (*.gto);;"
  479. "Gerber File .gtp (*.gtp);;Gerber File .gts (*.gts);;Gerber File .ly15 (*.ly15);;"
  480. "Gerber File .ly2 (*.ly2);;Gerber File .mil (*.mil);;"
  481. "Gerber File .outline (*.outline);;Gerber File .pho (*.pho);;"
  482. "Gerber File .plc (*.plc);;Gerber File .pls (*.pls);;Gerber File .smb (*.smb);;"
  483. "Gerber File .smt (*.smt);;Gerber File .sol (*.sol);;Gerber File .spb (*.spb);;"
  484. "Gerber File .spt (*.spt);;Gerber File .ssb (*.ssb);;Gerber File .sst (*.sst);;"
  485. "Gerber File .stc (*.stc);;Gerber File .sts (*.sts);;Gerber File .top (*.top);;"
  486. "Gerber File .tsm (*.tsm);;Gerber File .art (*.art)"
  487. "All Files (*.*)",
  488. # Gerber Options
  489. "gerber_isotooldia": 0.1,
  490. "gerber_isopasses": 1,
  491. "gerber_isooverlap": 10,
  492. "gerber_milling_type": "cl",
  493. "gerber_combine_passes": False,
  494. "gerber_iso_scope": 'all',
  495. "gerber_noncoppermargin": 0.1,
  496. "gerber_noncopperrounded": False,
  497. "gerber_bboxmargin": 0.1,
  498. "gerber_bboxrounded": False,
  499. # Gerber Advanced Options
  500. "gerber_aperture_display": False,
  501. "gerber_aperture_scale_factor": 1.0,
  502. "gerber_aperture_buffer_factor": 0.0,
  503. "gerber_follow": False,
  504. "gerber_tool_type": 'circular',
  505. "gerber_vtipdia": 0.1,
  506. "gerber_vtipangle": 30,
  507. "gerber_vcutz": -0.05,
  508. "gerber_iso_type": "full",
  509. "gerber_buffering": "full",
  510. "gerber_simplification": False,
  511. "gerber_simp_tolerance": 0.0005,
  512. # Gerber Export
  513. "gerber_exp_units": 'IN',
  514. "gerber_exp_integer": 2,
  515. "gerber_exp_decimals": 4,
  516. "gerber_exp_zeros": 'L',
  517. # Gerber Editor
  518. "gerber_editor_sel_limit": 30,
  519. "gerber_editor_newcode": 10,
  520. "gerber_editor_newsize": 0.8,
  521. "gerber_editor_newtype": 'C',
  522. "gerber_editor_newdim": "0.5, 0.5",
  523. "gerber_editor_array_size": 5,
  524. "gerber_editor_lin_axis": 'X',
  525. "gerber_editor_lin_pitch": 0.1,
  526. "gerber_editor_lin_angle": 0.0,
  527. "gerber_editor_circ_dir": 'CW',
  528. "gerber_editor_circ_angle": 0.0,
  529. "gerber_editor_scale_f": 1.0,
  530. "gerber_editor_buff_f": 0.1,
  531. "gerber_editor_ma_low": 0.0,
  532. "gerber_editor_ma_high": 1.0,
  533. # Excellon General
  534. "excellon_plot": True,
  535. "excellon_solid": True,
  536. "excellon_format_upper_in": 2,
  537. "excellon_format_lower_in": 4,
  538. "excellon_format_upper_mm": 3,
  539. "excellon_format_lower_mm": 3,
  540. "excellon_zeros": "L",
  541. "excellon_units": "INCH",
  542. "excellon_update": True,
  543. "excellon_optimization_type": 'B',
  544. "excellon_search_time": 3,
  545. "excellon_save_filters": "Excellon File .txt (*.txt);;Excellon File .drd (*.drd);;"
  546. "Excellon File .drill (*.drill);;"
  547. "Excellon File .drl (*.drl);;Excellon File .exc (*.exc);;"
  548. "Excellon File .ncd (*.ncd);;Excellon File .tap (*.tap);;"
  549. "Excellon File .xln (*.xln);;All Files (*.*)",
  550. "excellon_plot_fill": '#C40000BF',
  551. "excellon_plot_line": '#750000BF',
  552. # Excellon Options
  553. "excellon_operation": "drill",
  554. "excellon_milling_type": "drills",
  555. "excellon_milling_dia": 0.8,
  556. "excellon_cutz": -1.7,
  557. "excellon_multidepth": False,
  558. "excellon_depthperpass": 0.7,
  559. "excellon_travelz": 2,
  560. "excellon_endz": 0.5,
  561. "excellon_endxy": None,
  562. "excellon_feedrate_z": 300,
  563. "excellon_spindlespeed": 0,
  564. "excellon_dwell": False,
  565. "excellon_dwelltime": 1,
  566. "excellon_toolchange": False,
  567. "excellon_toolchangez": 15,
  568. "excellon_ppname_e": 'default',
  569. "excellon_tooldia": 0.8,
  570. "excellon_slot_tooldia": 1.8,
  571. "excellon_gcode_type": "drills",
  572. # Excellon Advanced Options
  573. "excellon_offset": 0.0,
  574. "excellon_toolchangexy": "0.0, 0.0",
  575. "excellon_startz": None,
  576. "excellon_feedrate_rapid": 1500,
  577. "excellon_z_pdepth": -0.02,
  578. "excellon_feedrate_probe": 75,
  579. "excellon_spindledir": 'CW',
  580. "excellon_f_plunge": False,
  581. "excellon_f_retract": False,
  582. # Excellon Export
  583. "excellon_exp_units": 'INCH',
  584. "excellon_exp_format": 'ndec',
  585. "excellon_exp_integer": 2,
  586. "excellon_exp_decimals": 4,
  587. "excellon_exp_zeros": 'LZ',
  588. "excellon_exp_slot_type": 'routing',
  589. # Excellon Editor
  590. "excellon_editor_sel_limit": 30,
  591. "excellon_editor_newdia": 1.0,
  592. "excellon_editor_array_size": 5,
  593. "excellon_editor_lin_dir": 'X',
  594. "excellon_editor_lin_pitch": 2.54,
  595. "excellon_editor_lin_angle": 0.0,
  596. "excellon_editor_circ_dir": 'CW',
  597. "excellon_editor_circ_angle": 12,
  598. # Excellon Slots
  599. "excellon_editor_slot_direction": 'X',
  600. "excellon_editor_slot_angle": 0.0,
  601. "excellon_editor_slot_length": 5.0,
  602. # Excellon Slot Array
  603. "excellon_editor_slot_array_size": 5,
  604. "excellon_editor_slot_lin_dir": 'X',
  605. "excellon_editor_slot_lin_pitch": 2.54,
  606. "excellon_editor_slot_lin_angle": 0.0,
  607. "excellon_editor_slot_circ_dir": 'CW',
  608. "excellon_editor_slot_circ_angle": 0.0,
  609. # Geometry General
  610. "geometry_plot": True,
  611. "geometry_circle_steps": 64,
  612. "geometry_cnctooldia": "2.4",
  613. "geometry_plot_line": "#FF0000",
  614. # Geometry Options
  615. "geometry_cutz": -2.4,
  616. "geometry_vtipdia": 0.1,
  617. "geometry_vtipangle": 30,
  618. "geometry_multidepth": False,
  619. "geometry_depthperpass": 0.8,
  620. "geometry_travelz": 2,
  621. "geometry_toolchange": False,
  622. "geometry_toolchangez": 15.0,
  623. "geometry_endz": 15.0,
  624. "geometry_endxy": None,
  625. "geometry_feedrate": 120,
  626. "geometry_feedrate_z": 60,
  627. "geometry_spindlespeed": 0,
  628. "geometry_dwell": False,
  629. "geometry_dwelltime": 1,
  630. "geometry_ppname_g": 'default',
  631. # Geometry Advanced Options
  632. "geometry_toolchangexy": "0.0, 0.0",
  633. "geometry_startz": None,
  634. "geometry_feedrate_rapid": 1500,
  635. "geometry_extracut": False,
  636. "geometry_extracut_length": 0.1,
  637. "geometry_z_pdepth": -0.02,
  638. "geometry_f_plunge": False,
  639. "geometry_spindledir": 'CW',
  640. "geometry_feedrate_probe": 75,
  641. "geometry_segx": 0.0,
  642. "geometry_segy": 0.0,
  643. # Geometry Editor
  644. "geometry_editor_sel_limit": 30,
  645. "geometry_editor_milling_type": "cl",
  646. # CNC Job General
  647. "cncjob_plot": True,
  648. "cncjob_plot_kind": 'all',
  649. "cncjob_annotation": True,
  650. "cncjob_tooldia": 1.0,
  651. "cncjob_coords_type": "G90",
  652. "cncjob_coords_decimals": 4,
  653. "cncjob_fr_decimals": 2,
  654. "cncjob_steps_per_circle": 64,
  655. "cncjob_footer": False,
  656. "cncjob_line_ending": False,
  657. "cncjob_save_filters": "G-Code Files .nc (*.nc);;G-Code Files .din (*.din);;G-Code Files .dnc (*.dnc);;"
  658. "G-Code Files .ecs (*.ecs);;G-Code Files .eia (*.eia);;G-Code Files .fan (*.fan);;"
  659. "G-Code Files .fgc (*.fgc);;G-Code Files .fnc (*.fnc);;G-Code Files . gc (*.gc);;"
  660. "G-Code Files .gcd (*.gcd);;G-Code Files .gcode (*.gcode);;G-Code Files .h (*.h);;"
  661. "G-Code Files .hnc (*.hnc);;G-Code Files .i (*.i);;G-Code Files .min (*.min);;"
  662. "G-Code Files .mpf (*.mpf);;G-Code Files .mpr (*.mpr);;G-Code Files .cnc (*.cnc);;"
  663. "G-Code Files .ncc (*.ncc);;G-Code Files .ncg (*.ncg);;G-Code Files .ncp (*.ncp);;"
  664. "G-Code Files .ngc (*.ngc);;G-Code Files .out (*.out);;G-Code Files .ply (*.ply);;"
  665. "G-Code Files .sbp (*.sbp);;G-Code Files .tap (*.tap);;G-Code Files .xpi (*.xpi);;"
  666. "All Files (*.*)",
  667. "cncjob_plot_line": '#4650BDFF',
  668. "cncjob_plot_fill": '#5E6CFFFF',
  669. "cncjob_travel_line": '#B5AB3A4C',
  670. "cncjob_travel_fill": '#F0E24D4C',
  671. # CNC Job Options
  672. "cncjob_prepend": "",
  673. "cncjob_append": "",
  674. # CNC Job Advanced Options
  675. "cncjob_toolchange_macro": "",
  676. "cncjob_toolchange_macro_enable": False,
  677. "cncjob_annotation_fontsize": 9,
  678. "cncjob_annotation_fontcolor": '#990000',
  679. # NCC Tool
  680. "tools_ncctools": "1.0, 0.5",
  681. "tools_nccorder": 'rev',
  682. "tools_nccoperation": 'clear',
  683. "tools_nccoverlap": 40,
  684. "tools_nccmargin": 1.0,
  685. "tools_nccmethod": _("Seed"),
  686. "tools_nccconnect": True,
  687. "tools_ncccontour": True,
  688. "tools_nccrest": False,
  689. "tools_ncc_offset_choice": False,
  690. "tools_ncc_offset_value": 0.0000,
  691. "tools_nccref": _('Itself'),
  692. "tools_ncc_area_shape": "square",
  693. "tools_ncc_plotting": 'normal',
  694. "tools_nccmilling_type": 'cl',
  695. "tools_ncctool_type": 'C1',
  696. "tools_ncccutz": -0.05,
  697. "tools_ncctipdia": 0.1,
  698. "tools_ncctipangle": 30,
  699. "tools_nccnewdia": 0.1,
  700. # Cutout Tool
  701. "tools_cutouttooldia": 2.4,
  702. "tools_cutoutkind": "single",
  703. "tools_cutoutmargin": 0.1,
  704. "tools_cutout_z": -1.8,
  705. "tools_cutout_depthperpass": 0.6,
  706. "tools_cutout_mdepth": True,
  707. "tools_cutoutgapsize": 4,
  708. "tools_gaps_ff": "4",
  709. "tools_cutout_convexshape": False,
  710. # Paint Tool
  711. "tools_painttooldia": 0.3,
  712. "tools_paintorder": 'rev',
  713. "tools_paintoverlap": 20,
  714. "tools_paintmargin": 0.0,
  715. "tools_paintmethod": _("Seed"),
  716. "tools_selectmethod": _("All Polygons"),
  717. "tools_paint_area_shape": "square",
  718. "tools_pathconnect": True,
  719. "tools_paintcontour": True,
  720. "tools_paint_plotting": 'normal',
  721. "tools_paintrest": False,
  722. "tools_painttool_type": 'C1',
  723. "tools_paintcutz": -0.05,
  724. "tools_painttipdia": 0.1,
  725. "tools_painttipangle": 30,
  726. "tools_paintnewdia": 0.1,
  727. # 2-Sided Tool
  728. "tools_2sided_mirror_axis": "X",
  729. "tools_2sided_axis_loc": "point",
  730. "tools_2sided_drilldia": 3.125,
  731. "tools_2sided_allign_axis": "X",
  732. # Film Tool
  733. "tools_film_type": 'neg',
  734. "tools_film_boundary": 1.0,
  735. "tools_film_scale_stroke": 0,
  736. "tools_film_color": '#000000',
  737. "tools_film_scale_cb": False,
  738. "tools_film_scale_x_entry": 1.0,
  739. "tools_film_scale_y_entry": 1.0,
  740. "tools_film_skew_cb": False,
  741. "tools_film_skew_x_entry": 0.0,
  742. "tools_film_skew_y_entry": 0.0,
  743. "tools_film_skew_ref_radio": 'bottomleft',
  744. "tools_film_mirror_cb": False,
  745. "tools_film_mirror_axis_radio": 'none',
  746. "tools_film_file_type_radio": 'svg',
  747. "tools_film_orientation": 'p',
  748. "tools_film_pagesize": 'A4',
  749. # Panel Tool
  750. "tools_panelize_spacing_columns": 0,
  751. "tools_panelize_spacing_rows": 0,
  752. "tools_panelize_columns": 1,
  753. "tools_panelize_rows": 1,
  754. "tools_panelize_constrain": False,
  755. "tools_panelize_constrainx": 200.0,
  756. "tools_panelize_constrainy": 290.0,
  757. "tools_panelize_panel_type": 'gerber',
  758. # Calculators Tool
  759. "tools_calc_vshape_tip_dia": 0.2,
  760. "tools_calc_vshape_tip_angle": 30,
  761. "tools_calc_vshape_cut_z": 0.05,
  762. "tools_calc_electro_length": 10.0,
  763. "tools_calc_electro_width": 10.0,
  764. "tools_calc_electro_cdensity": 13.0,
  765. "tools_calc_electro_growth": 10.0,
  766. # Transform Tool
  767. "tools_transform_rotate": 90,
  768. "tools_transform_skew_x": 0.0,
  769. "tools_transform_skew_y": 0.0,
  770. "tools_transform_scale_x": 1.0,
  771. "tools_transform_scale_y": 1.0,
  772. "tools_transform_scale_link": True,
  773. "tools_transform_scale_reference": True,
  774. "tools_transform_offset_x": 0.0,
  775. "tools_transform_offset_y": 0.0,
  776. "tools_transform_mirror_reference": False,
  777. "tools_transform_mirror_point": (0, 0),
  778. "tools_transform_buffer_dis": 0.0,
  779. "tools_transform_buffer_factor": 100.0,
  780. "tools_transform_buffer_corner": True,
  781. # SolderPaste Tool
  782. "tools_solderpaste_tools": "1.0, 0.3",
  783. "tools_solderpaste_new": 0.3,
  784. "tools_solderpaste_z_start": 0.05,
  785. "tools_solderpaste_z_dispense": 0.1,
  786. "tools_solderpaste_z_stop": 0.05,
  787. "tools_solderpaste_z_travel": 0.1,
  788. "tools_solderpaste_z_toolchange": 1.0,
  789. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  790. "tools_solderpaste_frxy": 150,
  791. "tools_solderpaste_frz": 150,
  792. "tools_solderpaste_frz_dispense": 1.0,
  793. "tools_solderpaste_speedfwd": 300,
  794. "tools_solderpaste_dwellfwd": 1,
  795. "tools_solderpaste_speedrev": 200,
  796. "tools_solderpaste_dwellrev": 1,
  797. "tools_solderpaste_pp": 'Paste_1',
  798. # Subtract Tool
  799. "tools_sub_close_paths": True,
  800. # Distance Tool
  801. "tools_dist_snap_center": False,
  802. # ########################################################################################################
  803. # ################################ TOOLS 2 ###############################################################
  804. # ########################################################################################################
  805. # Optimal Tool
  806. "tools_opt_precision": 4,
  807. # Check Rules Tool
  808. "tools_cr_trace_size": True,
  809. "tools_cr_trace_size_val": 0.25,
  810. "tools_cr_c2c": True,
  811. "tools_cr_c2c_val": 0.25,
  812. "tools_cr_c2o": True,
  813. "tools_cr_c2o_val": 1.0,
  814. "tools_cr_s2s": True,
  815. "tools_cr_s2s_val": 0.25,
  816. "tools_cr_s2sm": True,
  817. "tools_cr_s2sm_val": 0.25,
  818. "tools_cr_s2o": True,
  819. "tools_cr_s2o_val": 1.0,
  820. "tools_cr_sm2sm": True,
  821. "tools_cr_sm2sm_val": 0.25,
  822. "tools_cr_ri": True,
  823. "tools_cr_ri_val": 0.3,
  824. "tools_cr_h2h": True,
  825. "tools_cr_h2h_val": 0.3,
  826. "tools_cr_dh": True,
  827. "tools_cr_dh_val": 0.3,
  828. # QRCode Tool
  829. "tools_qrcode_version": 1,
  830. "tools_qrcode_error": 'L',
  831. "tools_qrcode_box_size": 3,
  832. "tools_qrcode_border_size": 4,
  833. "tools_qrcode_qrdata": '',
  834. "tools_qrcode_polarity": 'pos',
  835. "tools_qrcode_rounded": 's',
  836. "tools_qrcode_fill_color": '#000000',
  837. "tools_qrcode_back_color": '#FFFFFF',
  838. "tools_qrcode_sel_limit": 330,
  839. # Copper Thieving Tool
  840. "tools_copper_thieving_clearance": 0.25,
  841. "tools_copper_thieving_margin": 1.0,
  842. "tools_copper_thieving_reference": 'itself',
  843. "tools_copper_thieving_box_type": 'rect',
  844. "tools_copper_thieving_circle_steps": 64,
  845. "tools_copper_thieving_fill_type": 'solid',
  846. "tools_copper_thieving_dots_dia": 1.0,
  847. "tools_copper_thieving_dots_spacing": 2.0,
  848. "tools_copper_thieving_squares_size": 1.0,
  849. "tools_copper_thieving_squares_spacing": 2.0,
  850. "tools_copper_thieving_lines_size": 0.25,
  851. "tools_copper_thieving_lines_spacing": 2.0,
  852. "tools_copper_thieving_rb_margin": 1.0,
  853. "tools_copper_thieving_rb_thickness": 1.0,
  854. "tools_copper_thieving_mask_clearance": 0.0,
  855. # Fiducials Tool
  856. "tools_fiducials_dia": 1.0,
  857. "tools_fiducials_margin": 1.0,
  858. "tools_fiducials_mode": 'auto',
  859. "tools_fiducials_second_pos": 'up',
  860. "tools_fiducials_type": 'circular',
  861. "tools_fiducials_line_thickness": 0.25,
  862. # Calibration Tool
  863. "tools_cal_calsource": 'object',
  864. "tools_cal_travelz": 2.0,
  865. "tools_cal_verz": 0.1,
  866. "tools_cal_zeroz": False,
  867. "tools_cal_toolchangez": 15,
  868. "tools_cal_toolchange_xy": '',
  869. "tools_cal_sec_point": 'tl',
  870. # Drills Extraction Tool
  871. "tools_edrills_hole_type": 'fixed',
  872. "tools_edrills_hole_fixed_dia": 0.5,
  873. "tools_edrills_hole_prop_factor": 80.0,
  874. "tools_edrills_circular_ring": 0.2,
  875. "tools_edrills_oblong_ring": 0.2,
  876. "tools_edrills_square_ring": 0.2,
  877. "tools_edrills_rectangular_ring": 0.2,
  878. "tools_edrills_others_ring": 0.2,
  879. "tools_edrills_circular": True,
  880. "tools_edrills_oblong": False,
  881. "tools_edrills_square": False,
  882. "tools_edrills_rectangular": False,
  883. "tools_edrills_others": False,
  884. # Punch Gerber Tool
  885. "tools_punch_hole_type": 'exc',
  886. "tools_punch_hole_fixed_dia": 0.5,
  887. "tools_punch_hole_prop_factor": 80.0,
  888. "tools_punch_circular_ring": 0.2,
  889. "tools_punch_oblong_ring": 0.2,
  890. "tools_punch_square_ring": 0.2,
  891. "tools_punch_rectangular_ring": 0.2,
  892. "tools_punch_others_ring": 0.2,
  893. "tools_punch_circular": True,
  894. "tools_punch_oblong": False,
  895. "tools_punch_square": True,
  896. "tools_punch_rectangular": False,
  897. "tools_punch_others": False,
  898. # Align Objects Tool
  899. "tools_align_objects_align_type": 'sp',
  900. # Invert Gerber Tool
  901. "tools_invert_margin": 0.1,
  902. "tools_invert_join_style": 's',
  903. # Utilities
  904. # file associations
  905. "fa_excellon": 'drd, drill, drl, exc, ncd, tap, xln',
  906. "fa_gcode": 'cnc, din, dnc, ecs, eia, fan, fgc, fnc, gc, gcd, gcode, h, hnc, i, min, mpf, mpr, nc, ncc, '
  907. 'ncg, ncp, ngc, out, ply, rol, sbp, tap, xpi',
  908. "fa_gerber": 'art, bot, bsm, cmp, crc, crs, dim, gb0, gb1, gb2, gb3, gb4, gb5, gb6, gb7, gb8, gb9, gbd, '
  909. 'gbl, gbo, gbp, gbr, gbs, gdo, ger, gko, gm1, gm2, gm3, grb, gtl, gto, gtp, gts, ly15, ly2, '
  910. 'mil, outline, pho, plc, pls, smb, smt, sol, spb, spt, ssb, sst, stc, sts, top, tsm',
  911. # Keyword list
  912. "util_autocomplete_keywords": 'Desktop, Documents, FlatConfig, FlatPrj, False, '
  913. 'Marius, My Documents, Paste_1, '
  914. 'Repetier, Roland_MDX_20, True, Users, Toolchange_Custom, '
  915. 'Toolchange_Probe_MACH3, '
  916. 'Toolchange_manual, Users, all, axis, auto, axisoffset, '
  917. 'box, center_x, center_y, columns, combine, connect, contour, default, '
  918. 'depthperpass, dia, diatol, dist, drilled_dias, drillz, dpp, dwelltime, '
  919. 'endxy, endz, extracut_length, f, feedrate, '
  920. 'feedrate_z, grbl_11, GRBL_laser, gridoffsety, gridx, gridy, has_offset, '
  921. 'holes, hpgl, iso_type, line_xyz, margin, marlin, method, milled_dias, '
  922. 'minoffset, name, offset, opt_type, order, outname, overlap, '
  923. 'passes, postamble, pp, ppname_e, ppname_g, preamble, radius, ref, rest, '
  924. 'rows, shellvar_, scale_factor, spacing_columns, spacing_rows, spindlespeed, '
  925. 'startz, startxy, toolchange_xy, toolchangez, '
  926. 'tooldia, travelz, use_threads, value, x, x0, x1, y, y0, y1, z_cut, '
  927. 'z_move',
  928. "script_autocompleter": True,
  929. "script_text": "",
  930. "script_plot": True,
  931. "script_source_file": "",
  932. "document_autocompleter": False,
  933. "document_text": "",
  934. "document_plot": True,
  935. "document_source_file": "",
  936. "document_font_color": '#000000',
  937. "document_sel_color": '#0055ff',
  938. "document_font_size": 6,
  939. "document_tab_size": 80,
  940. })
  941. # ###########################################################################################################
  942. # ################################# Load defaults from file #################################################
  943. # ###########################################################################################################
  944. self.old_defaults_found = False
  945. if user_defaults:
  946. self.load_defaults(filename='current_defaults')
  947. if self.defaults['units'] == 'MM':
  948. self.decimals = int(self.defaults['decimals_metric'])
  949. else:
  950. self.decimals = int(self.defaults['decimals_inch'])
  951. if self.defaults["global_gray_icons"] is False:
  952. self.resource_location = 'share'
  953. else:
  954. self.resource_location = 'share/dark_resources'
  955. self.current_units = self.defaults['units']
  956. # store here the current self.defaults so it can be restored if Preferences changes are cancelled
  957. self.current_defaults = {}
  958. self.current_defaults.update(self.defaults)
  959. # ###########################################################################################################
  960. # #################################### SETUP OBJECT CLASSES #################################################
  961. # ###########################################################################################################
  962. self.setup_obj_classes()
  963. # ###########################################################################################################
  964. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  965. # ###########################################################################################################
  966. self.pool = Pool()
  967. # ###########################################################################################################
  968. # ###################################### Setting the Splash Screen ##########################################
  969. # ###########################################################################################################
  970. splash_settings = QSettings("Open Source", "FlatCAM")
  971. if splash_settings.contains("splash_screen"):
  972. show_splash = splash_settings.value("splash_screen")
  973. else:
  974. splash_settings.setValue('splash_screen', 1)
  975. # This will write the setting to the platform specific storage.
  976. del splash_settings
  977. show_splash = 1
  978. if show_splash and self.cmd_line_headless != 1:
  979. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  980. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  981. # self.splash.setMask(splash_pix.mask())
  982. # move splashscreen to the current monitor
  983. desktop = QtWidgets.QApplication.desktop()
  984. screen = desktop.screenNumber(QtGui.QCursor.pos())
  985. current_screen_center = desktop.availableGeometry(screen).center()
  986. self.splash.move(current_screen_center - self.splash.rect().center())
  987. self.splash.show()
  988. self.splash.showMessage(_("FlatCAM is initializing ..."),
  989. alignment=Qt.AlignBottom | Qt.AlignLeft,
  990. color=QtGui.QColor("gray"))
  991. else:
  992. show_splash = 0
  993. # ###########################################################################################################
  994. # ######################################### Initialize GUI ##################################################
  995. # ###########################################################################################################
  996. # FlatCAM colors used in plotting
  997. self.FC_light_green = '#BBF268BF'
  998. self.FC_dark_green = '#006E20BF'
  999. self.FC_light_blue = '#a5a5ffbf'
  1000. self.FC_dark_blue = '#0000ffbf'
  1001. QtCore.QObject.__init__(self)
  1002. self.ui = FlatCAMGUI(self)
  1003. self.on_grid_snap_triggered(state=True)
  1004. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  1005. if theme_settings.contains("theme"):
  1006. theme = theme_settings.value('theme', type=str)
  1007. else:
  1008. theme = 'white'
  1009. if self.defaults["global_cursor_color_enabled"]:
  1010. self.cursor_color_3D = self.defaults["global_cursor_color"]
  1011. else:
  1012. if theme == 'white':
  1013. self.cursor_color_3D = 'black'
  1014. else:
  1015. self.cursor_color_3D = 'gray'
  1016. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  1017. self.ui.final_save.connect(self.final_save)
  1018. # restore the toolbar view
  1019. self.restore_toolbar_view()
  1020. # restore the GUI geometry
  1021. self.restore_main_win_geom()
  1022. # set FlatCAM units in the Status bar
  1023. self.set_screen_units(self.defaults['units'])
  1024. # ###########################################################################################################
  1025. # ########################################### AUTOSAVE SETUP ################################################
  1026. # ###########################################################################################################
  1027. self.block_autosave = False
  1028. self.autosave_timer = QtCore.QTimer(self)
  1029. self.save_project_auto_update()
  1030. self.autosave_timer.timeout.connect(self.save_project_auto)
  1031. # ###########################################################################################################
  1032. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  1033. # ###########################################################################################################
  1034. # when adding entries here read the comments in the method found bellow named:
  1035. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  1036. self.defaults_form_fields = {
  1037. # General App
  1038. "decimals_inch": self.ui.general_defaults_form.general_app_group.precision_inch_entry,
  1039. "decimals_metric": self.ui.general_defaults_form.general_app_group.precision_metric_entry,
  1040. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  1041. "global_graphic_engine": self.ui.general_defaults_form.general_app_group.ge_radio,
  1042. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  1043. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  1044. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  1045. "global_systray_icon": self.ui.general_defaults_form.general_app_group.systray_cb,
  1046. "global_shell_at_startup": self.ui.general_defaults_form.general_app_group.shell_startup_cb,
  1047. "global_project_at_startup": self.ui.general_defaults_form.general_app_group.project_startup_cb,
  1048. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  1049. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  1050. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  1051. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  1052. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_spinner,
  1053. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  1054. "global_autosave": self.ui.general_defaults_form.general_app_group.autosave_cb,
  1055. "global_autosave_timeout": self.ui.general_defaults_form.general_app_group.autosave_entry,
  1056. "global_tpdf_tmargin": self.ui.general_defaults_form.general_app_group.tmargin_entry,
  1057. "global_tpdf_bmargin": self.ui.general_defaults_form.general_app_group.bmargin_entry,
  1058. "global_tpdf_lmargin": self.ui.general_defaults_form.general_app_group.lmargin_entry,
  1059. "global_tpdf_rmargin": self.ui.general_defaults_form.general_app_group.rmargin_entry,
  1060. # General GUI Preferences
  1061. "global_theme": self.ui.general_defaults_form.general_gui_group.theme_radio,
  1062. "global_gray_icons": self.ui.general_defaults_form.general_gui_group.gray_icons_cb,
  1063. "global_layout": self.ui.general_defaults_form.general_gui_group.layout_combo,
  1064. "global_hover": self.ui.general_defaults_form.general_gui_group.hover_cb,
  1065. "global_selection_shape": self.ui.general_defaults_form.general_gui_group.selection_cb,
  1066. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  1067. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  1068. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  1069. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  1070. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  1071. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  1072. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  1073. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  1074. "global_project_autohide": self.ui.general_defaults_form.general_gui_group.project_autohide_cb,
  1075. # General GUI Settings
  1076. "global_gridx": self.ui.general_defaults_form.general_app_set_group.gridx_entry,
  1077. "global_gridy": self.ui.general_defaults_form.general_app_set_group.gridy_entry,
  1078. "global_snap_max": self.ui.general_defaults_form.general_app_set_group.snap_max_dist_entry,
  1079. "global_workspace": self.ui.general_defaults_form.general_app_set_group.workspace_cb,
  1080. "global_workspaceT": self.ui.general_defaults_form.general_app_set_group.wk_cb,
  1081. "global_workspace_orientation": self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio,
  1082. "global_cursor_type": self.ui.general_defaults_form.general_app_set_group.cursor_radio,
  1083. "global_cursor_size": self.ui.general_defaults_form.general_app_set_group.cursor_size_entry,
  1084. "global_cursor_width": self.ui.general_defaults_form.general_app_set_group.cursor_width_entry,
  1085. "global_cursor_color_enabled": self.ui.general_defaults_form.general_app_set_group.mouse_cursor_color_cb,
  1086. "global_cursor_color": self.ui.general_defaults_form.general_app_set_group.mouse_cursor_entry,
  1087. "global_pan_button": self.ui.general_defaults_form.general_app_set_group.pan_button_radio,
  1088. "global_mselect_key": self.ui.general_defaults_form.general_app_set_group.mselect_radio,
  1089. "global_delete_confirmation": self.ui.general_defaults_form.general_app_set_group.delete_conf_cb,
  1090. "global_open_style": self.ui.general_defaults_form.general_app_set_group.open_style_cb,
  1091. "global_toggle_tooltips": self.ui.general_defaults_form.general_app_set_group.toggle_tooltips_cb,
  1092. "global_machinist_setting": self.ui.general_defaults_form.general_app_set_group.machinist_cb,
  1093. "global_bookmarks_limit": self.ui.general_defaults_form.general_app_set_group.bm_limit_spinner,
  1094. "global_activity_icon": self.ui.general_defaults_form.general_app_set_group.activity_combo,
  1095. # Gerber General
  1096. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  1097. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  1098. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  1099. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  1100. "gerber_def_units": self.ui.gerber_defaults_form.gerber_gen_group.gerber_units_radio,
  1101. "gerber_def_zeros": self.ui.gerber_defaults_form.gerber_gen_group.gerber_zeros_radio,
  1102. "gerber_clean_apertures": self.ui.gerber_defaults_form.gerber_gen_group.gerber_clean_cb,
  1103. "gerber_extra_buffering": self.ui.gerber_defaults_form.gerber_gen_group.gerber_extra_buffering,
  1104. "gerber_plot_fill": self.ui.gerber_defaults_form.gerber_gen_group.pf_color_entry,
  1105. "gerber_plot_line": self.ui.gerber_defaults_form.gerber_gen_group.pl_color_entry,
  1106. # Gerber Options
  1107. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  1108. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  1109. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  1110. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  1111. "gerber_iso_scope": self.ui.gerber_defaults_form.gerber_opt_group.iso_scope_radio,
  1112. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  1113. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  1114. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  1115. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  1116. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  1117. # Gerber Advanced Options
  1118. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  1119. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  1120. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  1121. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  1122. "gerber_tool_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.tool_type_radio,
  1123. "gerber_vtipdia": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipdia_spinner,
  1124. "gerber_vtipangle": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipangle_spinner,
  1125. "gerber_vcutz": self.ui.gerber_defaults_form.gerber_adv_opt_group.cutz_spinner,
  1126. "gerber_iso_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.iso_type_radio,
  1127. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  1128. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  1129. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  1130. # Gerber Export
  1131. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  1132. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  1133. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  1134. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  1135. # Gerber Editor
  1136. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  1137. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  1138. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  1139. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  1140. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  1141. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  1142. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  1143. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  1144. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  1145. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  1146. "gerber_editor_circ_angle":
  1147. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  1148. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  1149. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  1150. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  1151. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  1152. # Excellon General
  1153. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  1154. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  1155. "excellon_format_upper_in":
  1156. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  1157. "excellon_format_lower_in":
  1158. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  1159. "excellon_format_upper_mm":
  1160. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  1161. "excellon_format_lower_mm":
  1162. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  1163. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  1164. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  1165. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  1166. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  1167. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  1168. "excellon_plot_fill": self.ui.excellon_defaults_form.excellon_gen_group.fill_color_entry,
  1169. "excellon_plot_line": self.ui.excellon_defaults_form.excellon_gen_group.line_color_entry,
  1170. # Excellon Options
  1171. "excellon_operation": self.ui.excellon_defaults_form.excellon_opt_group.operation_radio,
  1172. "excellon_milling_type": self.ui.excellon_defaults_form.excellon_opt_group.milling_type_radio,
  1173. "excellon_milling_dia": self.ui.excellon_defaults_form.excellon_opt_group.mill_dia_entry,
  1174. "excellon_cutz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  1175. "excellon_multidepth": self.ui.excellon_defaults_form.excellon_opt_group.mpass_cb,
  1176. "excellon_depthperpass": self.ui.excellon_defaults_form.excellon_opt_group.maxdepth_entry,
  1177. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  1178. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.endz_entry,
  1179. "excellon_endxy": self.ui.excellon_defaults_form.excellon_opt_group.endxy_entry,
  1180. "excellon_feedrate_z": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_z_entry,
  1181. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  1182. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  1183. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  1184. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  1185. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  1186. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  1187. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  1188. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  1189. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  1190. # Excellon Advanced Options
  1191. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  1192. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  1193. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  1194. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1195. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  1196. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  1197. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  1198. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  1199. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  1200. # Excellon Export
  1201. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  1202. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  1203. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  1204. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  1205. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  1206. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  1207. # Excellon Editor
  1208. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  1209. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  1210. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  1211. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  1212. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  1213. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  1214. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  1215. "excellon_editor_circ_angle":
  1216. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  1217. # Excellon Slots
  1218. "excellon_editor_slot_direction":
  1219. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  1220. "excellon_editor_slot_angle":
  1221. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  1222. "excellon_editor_slot_length":
  1223. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  1224. # Excellon Slots
  1225. "excellon_editor_slot_array_size":
  1226. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  1227. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  1228. "excellon_editor_slot_lin_pitch":
  1229. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  1230. "excellon_editor_slot_lin_angle":
  1231. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  1232. "excellon_editor_slot_circ_dir":
  1233. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  1234. "excellon_editor_slot_circ_angle":
  1235. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  1236. # Geometry General
  1237. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  1238. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  1239. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  1240. "geometry_plot_line": self.ui.geometry_defaults_form.geometry_gen_group.line_color_entry,
  1241. # Geometry Options
  1242. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  1243. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  1244. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  1245. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.feedrate_z_entry,
  1246. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  1247. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  1248. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  1249. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  1250. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  1251. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  1252. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.endz_entry,
  1253. "geometry_endxy": self.ui.geometry_defaults_form.geometry_opt_group.endxy_entry,
  1254. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  1255. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  1256. # Geometry Advanced Options
  1257. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  1258. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  1259. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_rapid_entry,
  1260. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  1261. "geometry_extracut_length": self.ui.geometry_defaults_form.geometry_adv_opt_group.e_cut_entry,
  1262. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  1263. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  1264. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  1265. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  1266. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  1267. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  1268. # Geometry Editor
  1269. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  1270. "geometry_editor_milling_type": self.ui.geometry_defaults_form.geometry_editor_group.milling_type_radio,
  1271. # CNCJob General
  1272. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  1273. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  1274. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  1275. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  1276. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  1277. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  1278. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  1279. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  1280. "cncjob_line_ending": self.ui.cncjob_defaults_form.cncjob_gen_group.line_ending_cb,
  1281. "cncjob_plot_line": self.ui.cncjob_defaults_form.cncjob_gen_group.line_color_entry,
  1282. "cncjob_plot_fill": self.ui.cncjob_defaults_form.cncjob_gen_group.fill_color_entry,
  1283. "cncjob_travel_line": self.ui.cncjob_defaults_form.cncjob_gen_group.tline_color_entry,
  1284. "cncjob_travel_fill": self.ui.cncjob_defaults_form.cncjob_gen_group.tfill_color_entry,
  1285. # CNC Job Options
  1286. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  1287. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  1288. # CNC Job Advanced Options
  1289. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  1290. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  1291. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  1292. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  1293. # NCC Tool
  1294. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  1295. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  1296. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  1297. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  1298. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_combo,
  1299. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  1300. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  1301. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  1302. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  1303. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  1304. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.select_combo,
  1305. "tools_ncc_area_shape": self.ui.tools_defaults_form.tools_ncc_group.area_shape_radio,
  1306. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  1307. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  1308. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  1309. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  1310. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  1311. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  1312. "tools_nccnewdia": self.ui.tools_defaults_form.tools_ncc_group.newdia_entry,
  1313. # CutOut Tool
  1314. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  1315. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  1316. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  1317. "tools_cutout_z": self.ui.tools_defaults_form.tools_cutout_group.cutz_entry,
  1318. "tools_cutout_depthperpass": self.ui.tools_defaults_form.tools_cutout_group.maxdepth_entry,
  1319. "tools_cutout_mdepth": self.ui.tools_defaults_form.tools_cutout_group.mpass_cb,
  1320. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  1321. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  1322. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  1323. # Paint Area Tool
  1324. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  1325. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  1326. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  1327. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  1328. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  1329. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  1330. "tools_paint_area_shape": self.ui.tools_defaults_form.tools_paint_group.area_shape_radio,
  1331. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  1332. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  1333. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  1334. "tools_paintrest": self.ui.tools_defaults_form.tools_paint_group.rest_cb,
  1335. "tools_painttool_type": self.ui.tools_defaults_form.tools_paint_group.tool_type_radio,
  1336. "tools_paintcutz": self.ui.tools_defaults_form.tools_paint_group.cutz_entry,
  1337. "tools_painttipdia": self.ui.tools_defaults_form.tools_paint_group.tipdia_entry,
  1338. "tools_painttipangle": self.ui.tools_defaults_form.tools_paint_group.tipangle_entry,
  1339. "tools_paintnewdia": self.ui.tools_defaults_form.tools_paint_group.newdia_entry,
  1340. # 2-sided Tool
  1341. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  1342. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  1343. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  1344. "tools_2sided_allign_axis": self.ui.tools_defaults_form.tools_2sided_group.align_axis_radio,
  1345. # Film Tool
  1346. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  1347. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  1348. "tools_film_scale_stroke": self.ui.tools_defaults_form.tools_film_group.film_scale_stroke_entry,
  1349. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  1350. "tools_film_scale_cb": self.ui.tools_defaults_form.tools_film_group.film_scale_cb,
  1351. "tools_film_scale_x_entry": self.ui.tools_defaults_form.tools_film_group.film_scalex_entry,
  1352. "tools_film_scale_y_entry": self.ui.tools_defaults_form.tools_film_group.film_scaley_entry,
  1353. "tools_film_skew_cb": self.ui.tools_defaults_form.tools_film_group.film_skew_cb,
  1354. "tools_film_skew_x_entry": self.ui.tools_defaults_form.tools_film_group.film_skewx_entry,
  1355. "tools_film_skew_y_entry": self.ui.tools_defaults_form.tools_film_group.film_skewy_entry,
  1356. "tools_film_skew_ref_radio": self.ui.tools_defaults_form.tools_film_group.film_skew_reference,
  1357. "tools_film_mirror_cb": self.ui.tools_defaults_form.tools_film_group.film_mirror_cb,
  1358. "tools_film_mirror_axis_radio": self.ui.tools_defaults_form.tools_film_group.film_mirror_axis,
  1359. "tools_film_file_type_radio": self.ui.tools_defaults_form.tools_film_group.file_type_radio,
  1360. "tools_film_orientation": self.ui.tools_defaults_form.tools_film_group.orientation_radio,
  1361. "tools_film_pagesize": self.ui.tools_defaults_form.tools_film_group.pagesize_combo,
  1362. # Panelize Tool
  1363. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  1364. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  1365. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  1366. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  1367. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  1368. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  1369. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  1370. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  1371. # Calculators Tool
  1372. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  1373. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  1374. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  1375. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  1376. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  1377. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  1378. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  1379. # Transformations Tool
  1380. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  1381. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  1382. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  1383. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  1384. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  1385. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  1386. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  1387. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  1388. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  1389. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  1390. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  1391. "tools_transform_buffer_dis": self.ui.tools_defaults_form.tools_transform_group.buffer_entry,
  1392. "tools_transform_buffer_factor": self.ui.tools_defaults_form.tools_transform_group.buffer_factor_entry,
  1393. "tools_transform_buffer_corner": self.ui.tools_defaults_form.tools_transform_group.buffer_rounded_cb,
  1394. # SolderPaste Dispensing Tool
  1395. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  1396. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  1397. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  1398. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  1399. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  1400. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  1401. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  1402. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  1403. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  1404. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  1405. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  1406. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  1407. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  1408. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  1409. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  1410. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  1411. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  1412. # #######################################################################################################
  1413. # ########################################## TOOLS 2 ####################################################
  1414. # #######################################################################################################
  1415. # Optimal Tool
  1416. "tools_opt_precision": self.ui.tools2_defaults_form.tools2_optimal_group.precision_sp,
  1417. # Check Rules Tool
  1418. "tools_cr_trace_size": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_cb,
  1419. "tools_cr_trace_size_val": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_entry,
  1420. "tools_cr_c2c": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_cb,
  1421. "tools_cr_c2c_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_entry,
  1422. "tools_cr_c2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_cb,
  1423. "tools_cr_c2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_entry,
  1424. "tools_cr_s2s": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_cb,
  1425. "tools_cr_s2s_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_entry,
  1426. "tools_cr_s2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_cb,
  1427. "tools_cr_s2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_entry,
  1428. "tools_cr_s2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_cb,
  1429. "tools_cr_s2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_entry,
  1430. "tools_cr_sm2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_cb,
  1431. "tools_cr_sm2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_entry,
  1432. "tools_cr_ri": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_cb,
  1433. "tools_cr_ri_val": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_entry,
  1434. "tools_cr_h2h": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_cb,
  1435. "tools_cr_h2h_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_entry,
  1436. "tools_cr_dh": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_cb,
  1437. "tools_cr_dh_val": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_entry,
  1438. # QRCode Tool
  1439. "tools_qrcode_version": self.ui.tools2_defaults_form.tools2_qrcode_group.version_entry,
  1440. "tools_qrcode_error": self.ui.tools2_defaults_form.tools2_qrcode_group.error_radio,
  1441. "tools_qrcode_box_size": self.ui.tools2_defaults_form.tools2_qrcode_group.bsize_entry,
  1442. "tools_qrcode_border_size": self.ui.tools2_defaults_form.tools2_qrcode_group.border_size_entry,
  1443. "tools_qrcode_qrdata": self.ui.tools2_defaults_form.tools2_qrcode_group.text_data,
  1444. "tools_qrcode_polarity": self.ui.tools2_defaults_form.tools2_qrcode_group.pol_radio,
  1445. "tools_qrcode_rounded": self.ui.tools2_defaults_form.tools2_qrcode_group.bb_radio,
  1446. "tools_qrcode_fill_color": self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry,
  1447. "tools_qrcode_back_color": self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry,
  1448. "tools_qrcode_sel_limit": self.ui.tools2_defaults_form.tools2_qrcode_group.sel_limit_entry,
  1449. # Copper Thieving Tool
  1450. "tools_copper_thieving_clearance": self.ui.tools2_defaults_form.tools2_cfill_group.clearance_entry,
  1451. "tools_copper_thieving_margin": self.ui.tools2_defaults_form.tools2_cfill_group.margin_entry,
  1452. "tools_copper_thieving_reference": self.ui.tools2_defaults_form.tools2_cfill_group.reference_radio,
  1453. "tools_copper_thieving_box_type": self.ui.tools2_defaults_form.tools2_cfill_group.bbox_type_radio,
  1454. "tools_copper_thieving_circle_steps": self.ui.tools2_defaults_form.tools2_cfill_group.circlesteps_entry,
  1455. "tools_copper_thieving_fill_type": self.ui.tools2_defaults_form.tools2_cfill_group.fill_type_radio,
  1456. "tools_copper_thieving_dots_dia": self.ui.tools2_defaults_form.tools2_cfill_group.dot_dia_entry,
  1457. "tools_copper_thieving_dots_spacing": self.ui.tools2_defaults_form.tools2_cfill_group.dot_spacing_entry,
  1458. "tools_copper_thieving_squares_size": self.ui.tools2_defaults_form.tools2_cfill_group.square_size_entry,
  1459. "tools_copper_thieving_squares_spacing":
  1460. self.ui.tools2_defaults_form.tools2_cfill_group.squares_spacing_entry,
  1461. "tools_copper_thieving_lines_size": self.ui.tools2_defaults_form.tools2_cfill_group.line_size_entry,
  1462. "tools_copper_thieving_lines_spacing": self.ui.tools2_defaults_form.tools2_cfill_group.lines_spacing_entry,
  1463. "tools_copper_thieving_rb_margin": self.ui.tools2_defaults_form.tools2_cfill_group.rb_margin_entry,
  1464. "tools_copper_thieving_rb_thickness": self.ui.tools2_defaults_form.tools2_cfill_group.rb_thickness_entry,
  1465. "tools_copper_thieving_mask_clearance": self.ui.tools2_defaults_form.tools2_cfill_group.clearance_ppm_entry,
  1466. # Fiducials Tool
  1467. "tools_fiducials_dia": self.ui.tools2_defaults_form.tools2_fiducials_group.dia_entry,
  1468. "tools_fiducials_margin": self.ui.tools2_defaults_form.tools2_fiducials_group.margin_entry,
  1469. "tools_fiducials_mode": self.ui.tools2_defaults_form.tools2_fiducials_group.mode_radio,
  1470. "tools_fiducials_second_pos": self.ui.tools2_defaults_form.tools2_fiducials_group.pos_radio,
  1471. "tools_fiducials_type": self.ui.tools2_defaults_form.tools2_fiducials_group.fid_type_radio,
  1472. "tools_fiducials_line_thickness": self.ui.tools2_defaults_form.tools2_fiducials_group.line_thickness_entry,
  1473. # Calibration Tool
  1474. "tools_cal_calsource": self.ui.tools2_defaults_form.tools2_cal_group.cal_source_radio,
  1475. "tools_cal_travelz": self.ui.tools2_defaults_form.tools2_cal_group.travelz_entry,
  1476. "tools_cal_verz": self.ui.tools2_defaults_form.tools2_cal_group.verz_entry,
  1477. "tools_cal_zeroz": self.ui.tools2_defaults_form.tools2_cal_group.zeroz_cb,
  1478. "tools_cal_toolchangez": self.ui.tools2_defaults_form.tools2_cal_group.toolchangez_entry,
  1479. "tools_cal_toolchange_xy": self.ui.tools2_defaults_form.tools2_cal_group.toolchange_xy_entry,
  1480. "tools_cal_sec_point": self.ui.tools2_defaults_form.tools2_cal_group.second_point_radio,
  1481. # Extract Drills Tool
  1482. "tools_edrills_hole_type": self.ui.tools2_defaults_form.tools2_edrills_group.hole_size_radio,
  1483. "tools_edrills_hole_fixed_dia": self.ui.tools2_defaults_form.tools2_edrills_group.dia_entry,
  1484. "tools_edrills_hole_prop_factor": self.ui.tools2_defaults_form.tools2_edrills_group.factor_entry,
  1485. "tools_edrills_circular_ring": self.ui.tools2_defaults_form.tools2_edrills_group.circular_ring_entry,
  1486. "tools_edrills_oblong_ring": self.ui.tools2_defaults_form.tools2_edrills_group.oblong_ring_entry,
  1487. "tools_edrills_square_ring": self.ui.tools2_defaults_form.tools2_edrills_group.square_ring_entry,
  1488. "tools_edrills_rectangular_ring": self.ui.tools2_defaults_form.tools2_edrills_group.rectangular_ring_entry,
  1489. "tools_edrills_others_ring": self.ui.tools2_defaults_form.tools2_edrills_group.other_ring_entry,
  1490. "tools_edrills_circular": self.ui.tools2_defaults_form.tools2_edrills_group.circular_cb,
  1491. "tools_edrills_oblong": self.ui.tools2_defaults_form.tools2_edrills_group.oblong_cb,
  1492. "tools_edrills_square": self.ui.tools2_defaults_form.tools2_edrills_group.square_cb,
  1493. "tools_edrills_rectangular": self.ui.tools2_defaults_form.tools2_edrills_group.rectangular_cb,
  1494. "tools_edrills_others": self.ui.tools2_defaults_form.tools2_edrills_group.other_cb,
  1495. # Punch Gerber Tool
  1496. "tools_punch_hole_type": self.ui.tools2_defaults_form.tools2_punch_group.hole_size_radio,
  1497. "tools_punch_hole_fixed_dia": self.ui.tools2_defaults_form.tools2_punch_group.dia_entry,
  1498. "tools_punch_hole_prop_factor": self.ui.tools2_defaults_form.tools2_punch_group.factor_entry,
  1499. "tools_punch_circular_ring": self.ui.tools2_defaults_form.tools2_punch_group.circular_ring_entry,
  1500. "tools_punch_oblong_ring": self.ui.tools2_defaults_form.tools2_punch_group.oblong_ring_entry,
  1501. "tools_punch_square_ring": self.ui.tools2_defaults_form.tools2_punch_group.square_ring_entry,
  1502. "tools_punch_rectangular_ring": self.ui.tools2_defaults_form.tools2_punch_group.rectangular_ring_entry,
  1503. "tools_punch_others_ring": self.ui.tools2_defaults_form.tools2_punch_group.other_ring_entry,
  1504. "tools_punch_circular": self.ui.tools2_defaults_form.tools2_punch_group.circular_cb,
  1505. "tools_punch_oblong": self.ui.tools2_defaults_form.tools2_punch_group.oblong_cb,
  1506. "tools_punch_square": self.ui.tools2_defaults_form.tools2_punch_group.square_cb,
  1507. "tools_punch_rectangular": self.ui.tools2_defaults_form.tools2_punch_group.rectangular_cb,
  1508. "tools_punch_others": self.ui.tools2_defaults_form.tools2_punch_group.other_cb,
  1509. # Invert Gerber Tool
  1510. "tools_invert_margin": self.ui.tools2_defaults_form.tools2_invert_group.margin_entry,
  1511. "tools_invert_join_style": self.ui.tools2_defaults_form.tools2_invert_group.join_radio,
  1512. # Utilities
  1513. # File associations
  1514. "fa_excellon": self.ui.util_defaults_form.fa_excellon_group.exc_list_text,
  1515. "fa_gcode": self.ui.util_defaults_form.fa_gcode_group.gco_list_text,
  1516. # "fa_geometry": self.ui.util_defaults_form.fa_geometry_group.close_paths_cb,
  1517. "fa_gerber": self.ui.util_defaults_form.fa_gerber_group.grb_list_text,
  1518. "util_autocomplete_keywords": self.ui.util_defaults_form.kw_group.kw_list_text,
  1519. }
  1520. # update the Preferences GUI elements with the values in the self.defaults
  1521. self.defaults_write_form()
  1522. # When the self.defaults dictionary changes will update the Preferences GUI forms
  1523. self.defaults.set_change_callback(self.on_defaults_dict_change)
  1524. # ###########################################################################################################
  1525. # ##################################### FIRST RUN SECTION ###################################################
  1526. # ################################ It's done only once after install #####################################
  1527. # ###########################################################################################################
  1528. if self.defaults["first_run"] is True:
  1529. self.save_factory_defaults(silent_message=False)
  1530. # and then make the factory_defaults.FlatConfig file read_only so it can't be modified after creation.
  1531. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1532. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1533. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  1534. initial_lay = 'compact'
  1535. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  1536. # Set the combobox in Preferences to the current layout
  1537. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  1538. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  1539. # after the first run, this object should be False
  1540. self.defaults["first_run"] = False
  1541. self.save_defaults(silent=True)
  1542. # ###########################################################################################################
  1543. # ############################################ Data #########################################################
  1544. # ###########################################################################################################
  1545. self.recent = []
  1546. self.recent_projects = []
  1547. self.clipboard = QtWidgets.QApplication.clipboard()
  1548. self.project_filename = None
  1549. self.toggle_units_ignore = False
  1550. # ###########################################################################################################
  1551. # #################################### LOAD PREPROCESSORS ###################################################
  1552. # ###########################################################################################################
  1553. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  1554. # the preprocessor file
  1555. self.preprocessors = load_preprocessors(self)
  1556. # make sure that always the 'default' preprocessor is the first item in the dictionary
  1557. if 'default' in self.preprocessors.keys():
  1558. new_ppp_dict = {}
  1559. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  1560. default_pp = self.preprocessors.pop('default')
  1561. new_ppp_dict['default'] = default_pp
  1562. # then add the rest of the keys
  1563. for name, val_class in self.preprocessors.items():
  1564. new_ppp_dict[name] = val_class
  1565. # and now put back the ordered dict with 'default' key first
  1566. self.preprocessors = new_ppp_dict
  1567. for name in list(self.preprocessors.keys()):
  1568. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  1569. if name.partition('_')[0] == 'Paste':
  1570. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  1571. continue
  1572. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1573. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  1574. if name == 'hpgl':
  1575. continue
  1576. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1577. # ###########################################################################################################
  1578. # ########################################## LOAD LANGUAGES ################################################
  1579. # ###########################################################################################################
  1580. self.languages = fcTranslate.load_languages()
  1581. for name in sorted(self.languages.values()):
  1582. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  1583. # ###########################################################################################################
  1584. # ####################################### APPLY APP LANGUAGE ################################################
  1585. # ###########################################################################################################
  1586. ret_val = fcTranslate.apply_language('strings')
  1587. if ret_val == "no language":
  1588. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  1589. log.debug("Could not find the Language files. The App strings are missing.")
  1590. else:
  1591. # make the current language the current selection on the language combobox
  1592. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1593. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1594. # ###########################################################################################################
  1595. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  1596. # ###########################################################################################################
  1597. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1598. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1599. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  1600. self.save_defaults(silent=True, first_time=True)
  1601. self.propagate_defaults(silent=True)
  1602. # def auto_save_defaults():
  1603. # try:
  1604. # self.save_defaults(silent=True)
  1605. # self.propagate_defaults(silent=True)
  1606. # finally:
  1607. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1608. # the following lines activates automatic defaults save
  1609. # if user_defaults:
  1610. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1611. # ###########################################################################################################
  1612. # ######################################## UPDATE THE OPTIONS ###############################################
  1613. # ###########################################################################################################
  1614. self.options = LoudDict()
  1615. # -----------------------------------------------------------------------------------------------------------
  1616. # Update the self.options from the self.defaults
  1617. # The self.defaults holds the application defaults while the self.options holds the object defaults
  1618. # -----------------------------------------------------------------------------------------------------------
  1619. # Copy app defaults to project options
  1620. for def_key, def_val in self.defaults.items():
  1621. self.options[def_key] = deepcopy(def_val)
  1622. # self.options.update(self.defaults)
  1623. self.gen_form = None
  1624. self.ger_form = None
  1625. self.exc_form = None
  1626. self.geo_form = None
  1627. self.cnc_form = None
  1628. self.tools_form = None
  1629. self.tools2_form = None
  1630. self.fa_form = None
  1631. # Will show the Preferences GUI
  1632. self.show_preferences_gui()
  1633. # Initialize the color box's color in Preferences -> Global -> Color
  1634. self.init_color_pickers_in_preferences_gui()
  1635. # ### End of Data ####
  1636. # ###########################################################################################################
  1637. # #################################### SETUP OBJECT COLLECTION ##############################################
  1638. # ###########################################################################################################
  1639. self.collection = ObjectCollection(self)
  1640. self.ui.project_tab_layout.addWidget(self.collection.view)
  1641. # ### Adjust tabs width ## ##
  1642. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1643. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1644. self.collection.view.setMinimumWidth(290)
  1645. self.log.debug("Finished creating Object Collection.")
  1646. # ###########################################################################################################
  1647. # ######################################## SETUP Plot Area ##################################################
  1648. # ###########################################################################################################
  1649. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  1650. if self.defaults["global_graphic_engine"] == '3D':
  1651. self.is_legacy = False
  1652. else:
  1653. self.is_legacy = True
  1654. # Event signals disconnect id holders
  1655. self.mp = None
  1656. self.mm = None
  1657. self.mr = None
  1658. self.mdc = None
  1659. self.mp_zc = None
  1660. self.kp = None
  1661. # Matplotlib axis
  1662. self.axes = None
  1663. if show_splash:
  1664. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1665. "Canvas initialization started."),
  1666. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1667. color=QtGui.QColor("gray"))
  1668. start_plot_time = time.time() # debug
  1669. self.plotcanvas = None
  1670. self.app_cursor = None
  1671. self.hover_shapes = None
  1672. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  1673. # setup the PlotCanvas
  1674. self.on_plotcanvas_setup()
  1675. end_plot_time = time.time()
  1676. self.used_time = end_plot_time - start_plot_time
  1677. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1678. if show_splash:
  1679. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1680. "Canvas initialization started.\n"
  1681. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1682. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1683. color=QtGui.QColor("gray"))
  1684. self.ui.splitter.setStretchFactor(1, 2)
  1685. # ###########################################################################################################
  1686. # ############################################### SYS TRAY ##################################################
  1687. # ###########################################################################################################
  1688. if self.defaults["global_systray_icon"]:
  1689. self.parent_w = QtWidgets.QWidget()
  1690. if self.cmd_line_headless == 1:
  1691. self.trayIcon = FlatCAMSystemTray(app=self,
  1692. icon=QtGui.QIcon(self.resource_location +
  1693. '/flatcam_icon32_green.png'),
  1694. headless=True,
  1695. parent=self.parent_w)
  1696. else:
  1697. self.trayIcon = FlatCAMSystemTray(app=self,
  1698. icon=QtGui.QIcon(self.resource_location +
  1699. '/flatcam_icon32_green.png'),
  1700. parent=self.parent_w)
  1701. # ###########################################################################################################
  1702. # ############################################### Worker SETUP ##############################################
  1703. # ###########################################################################################################
  1704. if self.defaults["global_worker_number"]:
  1705. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1706. else:
  1707. self.workers = WorkerStack(workers_number=2)
  1708. self.worker_task.connect(self.workers.add_task)
  1709. self.log.debug("Finished creating Workers crew.")
  1710. # ###########################################################################################################
  1711. # ############################################# Activity Monitor ###########################################
  1712. # ###########################################################################################################
  1713. self.activity_view = FlatCAMActivityView(app=self)
  1714. self.ui.infobar.addWidget(self.activity_view)
  1715. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  1716. # ###########################################################################################################
  1717. # ############################################# Signal handling #############################################
  1718. # ###########################################################################################################
  1719. # ########################################## Custom signals ################################################
  1720. # signal for displaying messages in status bar
  1721. self.inform.connect(self.info)
  1722. # signal to be called when the app is quiting
  1723. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  1724. self.message.connect(self.message_dialog)
  1725. # self.progress.connect(self.set_progress_bar)
  1726. # signals that are emitted when object state changes
  1727. self.object_created.connect(self.on_object_created)
  1728. self.object_changed.connect(self.on_object_changed)
  1729. self.object_plotted.connect(self.on_object_plotted)
  1730. self.plots_updated.connect(self.on_plots_updated)
  1731. # signals emitted when file state change
  1732. self.file_opened.connect(self.register_recent)
  1733. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1734. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1735. # ########################################## Standard signals ###############################################
  1736. # ### Menu
  1737. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1738. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1739. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1740. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1741. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  1742. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1743. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1744. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1745. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1746. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1747. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1748. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1749. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  1750. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1751. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1752. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1753. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1754. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1755. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  1756. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1757. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1758. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1759. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1760. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1761. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  1762. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1763. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1764. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1765. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1766. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1767. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1768. self.ui.menufile_exit.triggered.connect(self.final_save)
  1769. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1770. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1771. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1772. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1773. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1774. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1775. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1776. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1777. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  1778. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1779. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1780. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1781. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  1782. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1783. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1784. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1785. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1786. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1787. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1788. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1789. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1790. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1791. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1792. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1793. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1794. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1795. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1796. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1797. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1798. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1799. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  1800. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1801. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1802. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1803. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1804. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1805. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1806. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1807. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1808. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1809. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1810. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1811. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  1812. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1813. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  1814. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1815. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  1816. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  1817. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1818. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1819. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1820. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1821. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1822. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1823. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1824. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1825. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1826. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1827. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1828. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  1829. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1830. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1831. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1832. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1833. # ToolBar signals
  1834. self.connect_toolbar_signals()
  1835. # Notebook and Plot Tab Area signals
  1836. # make the right click on the notebook tab and plot tab area tab raise a menu
  1837. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1838. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1839. self.on_tab_setup_context_menu()
  1840. # activate initial state
  1841. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1842. # Context Menu
  1843. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1844. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1845. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1846. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1847. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1848. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1849. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1850. self.ui.clearplot.triggered.connect(self.clear_plots)
  1851. self.ui.replot.triggered.connect(self.plot_all)
  1852. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  1853. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1854. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1855. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1856. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1857. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1858. # Project Context Menu -> Color Setting
  1859. for act in self.ui.menuprojectcolor.actions():
  1860. act.triggered.connect(self.on_set_color_action_triggered)
  1861. # Preferences Plot Area TAB
  1862. self.ui.pref_save_button.clicked.connect(lambda: self.on_save_button(save_to_file=True))
  1863. self.ui.pref_apply_button.clicked.connect(lambda: self.on_save_button(save_to_file=False))
  1864. self.ui.pref_close_button.clicked.connect(self.on_pref_close_button)
  1865. self.ui.pref_defaults_button.clicked.connect(self.on_restore_defaults_preferences)
  1866. # ###########################################################################################################
  1867. # #################################### GUI PREFERENCES SIGNALS ##############################################
  1868. # ###########################################################################################################
  1869. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1870. lambda: self.on_toggle_units(no_pref=False))
  1871. # ##################################### Workspace Setting Signals ###########################################
  1872. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  1873. self.on_workspace_modified)
  1874. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  1875. self.on_workspace_modified
  1876. )
  1877. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1878. # ###########################################################################################################
  1879. # ######################################## GUI SETTINGS SIGNALS #############################################
  1880. # ###########################################################################################################
  1881. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  1882. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  1883. # ######################################## Tools related signals ############################################
  1884. # Film Tool
  1885. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1886. self.on_film_color_entry)
  1887. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1888. self.on_film_color_button)
  1889. # QRCode Tool
  1890. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  1891. self.on_qrcode_fill_color_entry)
  1892. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  1893. self.on_qrcode_fill_color_button)
  1894. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  1895. self.on_qrcode_back_color_entry)
  1896. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  1897. self.on_qrcode_back_color_button)
  1898. # portability changed signal
  1899. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1900. # Object list
  1901. self.collection.view.activated.connect(self.on_row_activated)
  1902. self.collection.item_selected.connect(self.on_row_selected)
  1903. self.object_status_changed.connect(self.on_collection_updated)
  1904. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1905. # Export Excellon parameters.
  1906. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1907. self.on_update_exc_export
  1908. )
  1909. # call it once to make sure it is updated at startup
  1910. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1911. # when there are arguments at application startup this get launched
  1912. self.args_at_startup[list].connect(self.on_startup_args)
  1913. # ###########################################################################################################
  1914. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  1915. # ###########################################################################################################
  1916. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1917. lambda: self.restore_extensions(ext_type='excellon'))
  1918. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1919. lambda: self.restore_extensions(ext_type='gcode'))
  1920. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1921. lambda: self.restore_extensions(ext_type='gerber'))
  1922. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1923. lambda: self.delete_all_extensions(ext_type='excellon'))
  1924. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1925. lambda: self.delete_all_extensions(ext_type='gcode'))
  1926. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1927. lambda: self.delete_all_extensions(ext_type='gerber'))
  1928. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1929. lambda: self.add_extension(ext_type='excellon'))
  1930. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1931. lambda: self.add_extension(ext_type='gcode'))
  1932. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1933. lambda: self.add_extension(ext_type='gerber'))
  1934. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1935. lambda: self.del_extension(ext_type='excellon'))
  1936. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1937. lambda: self.del_extension(ext_type='gcode'))
  1938. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1939. lambda: self.del_extension(ext_type='gerber'))
  1940. # connect the 'Apply' buttons from the Preferences/File Associations
  1941. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1942. lambda: self.on_register_files(obj_type='excellon'))
  1943. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1944. lambda: self.on_register_files(obj_type='gcode'))
  1945. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1946. lambda: self.on_register_files(obj_type='gerber'))
  1947. # ###########################################################################################################
  1948. # ########################################### KEYWORDS SIGNALS ##############################################
  1949. # ###########################################################################################################
  1950. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1951. lambda: self.restore_extensions(ext_type='keyword'))
  1952. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1953. lambda: self.delete_all_extensions(ext_type='keyword'))
  1954. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1955. lambda: self.add_extension(ext_type='keyword'))
  1956. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1957. lambda: self.del_extension(ext_type='keyword'))
  1958. # connect the abort_all_tasks related slots to the related signals
  1959. self.proc_container.idle_flag.connect(self.app_is_idle)
  1960. # signal emitted when a tab is closed in the Plot Area
  1961. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  1962. self.ui.grid_snap_btn.triggered.connect(self.on_grid_snap_triggered)
  1963. self.ui.snap_infobar_label.clicked.connect(self.on_grid_icon_snap_clicked)
  1964. # signal to close the application
  1965. self.close_app_signal.connect(self.kill_app)
  1966. # ################################# FINISHED CONNECTING SIGNALS #############################################
  1967. # ###########################################################################################################
  1968. # ###########################################################################################################
  1969. # ###########################################################################################################
  1970. self.log.debug("Finished connecting Signals.")
  1971. # ###########################################################################################################
  1972. # ########################################## Other setups ###################################################
  1973. # ###########################################################################################################
  1974. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  1975. # depending on from where those tools are called different actions can be done
  1976. self.call_source = 'app'
  1977. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1978. self.tool_tab_locked = False
  1979. # decide if to show or hide the Notebook side of the screen at startup
  1980. if self.defaults["global_project_at_startup"] is True:
  1981. self.ui.splitter.setSizes([1, 1])
  1982. else:
  1983. self.ui.splitter.setSizes([0, 1])
  1984. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1985. self.setup_component_editor()
  1986. # ###########################################################################################################
  1987. # ####################################### Auto-complete KEYWORDS ############################################
  1988. # ###########################################################################################################
  1989. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1990. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  1991. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  1992. 'export_exc',
  1993. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  1994. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  1995. 'interiors', 'isolate', 'join_excellon',
  1996. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  1997. 'mirror', 'ncc',
  1998. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1999. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  2000. 'options', 'origin',
  2001. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  2002. 'save', 'save_project',
  2003. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  2004. 'skew', 'subtract_poly', 'subtract_rectangle',
  2005. 'version', 'write_gcode'
  2006. ]
  2007. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  2008. 'Paste_1',
  2009. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  2010. 'Toolchange_manual', 'True', 'Users',
  2011. 'all', 'auto', 'axis',
  2012. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  2013. 'contour', 'default',
  2014. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  2015. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  2016. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  2017. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  2018. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  2019. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  2020. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  2021. 'spacing_columns',
  2022. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  2023. 'toolchange_xy', 'toolchangez', 'travelz',
  2024. 'tooldia', 'use_threads', 'value',
  2025. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  2026. ]
  2027. self.tcl_keywords = [
  2028. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  2029. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  2030. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  2031. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  2032. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  2033. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  2034. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  2035. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  2036. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  2037. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  2038. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  2039. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  2040. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  2041. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  2042. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  2043. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  2044. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  2045. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  2046. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  2047. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  2048. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  2049. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  2050. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  2051. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  2052. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  2053. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  2054. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  2055. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  2056. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  2057. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  2058. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  2059. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  2060. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  2061. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  2062. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  2063. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  2064. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  2065. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  2066. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  2067. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  2068. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  2069. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  2070. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  2071. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  2072. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  2073. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  2074. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  2075. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  2076. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  2077. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  2078. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  2079. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  2080. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  2081. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  2082. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  2083. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  2084. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  2085. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  2086. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  2087. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  2088. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  2089. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  2090. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  2091. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  2092. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  2093. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  2094. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  2095. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  2096. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  2097. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  2098. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  2099. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  2100. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  2101. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  2102. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  2103. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  2104. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  2105. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  2106. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  2107. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  2108. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  2109. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  2110. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  2111. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  2112. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  2113. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  2114. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  2115. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  2116. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  2117. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  2118. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  2119. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  2120. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  2121. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  2122. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  2123. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  2124. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  2125. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  2126. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  2127. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  2128. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  2129. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  2130. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  2131. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  2132. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  2133. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  2134. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  2135. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  2136. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  2137. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  2138. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  2139. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  2140. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  2141. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  2142. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  2143. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  2144. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  2145. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  2146. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  2147. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  2148. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  2149. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  2150. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  2151. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  2152. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  2153. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  2154. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  2155. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  2156. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  2157. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  2158. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  2159. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  2160. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  2161. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  2162. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  2163. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  2164. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  2165. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  2166. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  2167. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  2168. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  2169. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  2170. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  2171. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  2172. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  2173. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  2174. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  2175. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  2176. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  2177. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  2178. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  2179. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  2180. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  2181. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  2182. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  2183. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  2184. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  2185. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  2186. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  2187. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  2188. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  2189. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  2190. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  2191. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  2192. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  2193. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  2194. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  2195. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  2196. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  2197. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  2198. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  2199. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  2200. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  2201. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  2202. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  2203. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  2204. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  2205. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  2206. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  2207. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  2208. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  2209. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  2210. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  2211. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  2212. ]
  2213. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  2214. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2215. # ###########################################################################################################
  2216. # ############################################## Shell SETUP ################################################
  2217. # ###########################################################################################################
  2218. self.shell = FCShell(app=self, version=self.version)
  2219. self.ui.shell_dock.setWidget(self.shell)
  2220. self.log.debug("TCL Shell has been initialized.")
  2221. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  2222. if self.defaults["global_shell_at_startup"]:
  2223. self.ui.shell_dock.show()
  2224. else:
  2225. self.ui.shell_dock.hide()
  2226. # ###########################################################################################################
  2227. # ########################################## Tools and Plugins ##############################################
  2228. # ###########################################################################################################
  2229. self.dblsidedtool = None
  2230. self.distance_tool = None
  2231. self.distance_min_tool = None
  2232. self.panelize_tool = None
  2233. self.film_tool = None
  2234. self.paste_tool = None
  2235. self.calculator_tool = None
  2236. self.rules_tool = None
  2237. self.sub_tool = None
  2238. self.move_tool = None
  2239. self.cutout_tool = None
  2240. self.ncclear_tool = None
  2241. self.optimal_tool = None
  2242. self.paint_tool = None
  2243. self.transform_tool = None
  2244. self.properties_tool = None
  2245. self.pdf_tool = None
  2246. self.image_tool = None
  2247. self.pcb_wizard_tool = None
  2248. self.cal_exc_tool = None
  2249. self.qrcode_tool = None
  2250. self.copper_thieving_tool = None
  2251. self.fiducial_tool = None
  2252. self.edrills_tool = None
  2253. self.align_objects_tool = None
  2254. self.punch_tool = None
  2255. self.invert_tool = None
  2256. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  2257. try:
  2258. self.install_tools()
  2259. except AttributeError as e:
  2260. log.debug("App.__init__() install tools() --> %s" % str(e))
  2261. # ###########################################################################################################
  2262. # ############################################ SETUP RECENT ITEMS ###########################################
  2263. # ###########################################################################################################
  2264. self.setup_recent_items()
  2265. # ###########################################################################################################
  2266. # ######################################### BookMarks Manager ###############################################
  2267. # ###########################################################################################################
  2268. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  2269. self.install_bookmarks()
  2270. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  2271. # ###########################################################################################################
  2272. # ########################################### Tools Database ################################################
  2273. # ###########################################################################################################
  2274. self.tools_db_tab = None
  2275. # ### System Font Parsing ###
  2276. # self.f_parse = ParseFont(self)
  2277. # self.parse_system_fonts()
  2278. # ###########################################################################################################
  2279. # ######################################### Check for updates ###############################################
  2280. # ###########################################################################################################
  2281. # Separate thread (Not worker)
  2282. # Check for updates on startup but only if the user consent and the app is not in Beta version
  2283. if (self.beta is False or self.beta is None) and \
  2284. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  2285. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  2286. self.thr2 = QtCore.QThread()
  2287. self.worker_task.emit({'fcn': self.version_check,
  2288. 'params': []})
  2289. self.thr2.start(QtCore.QThread.LowPriority)
  2290. # ###########################################################################################################
  2291. # ##################################### Register files with FlatCAM; #######################################
  2292. # ################################### It works only for Windows for now ####################################
  2293. # ###########################################################################################################
  2294. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  2295. self.on_register_files()
  2296. # ###########################################################################################################
  2297. # ######################################## Variables for global usage #######################################
  2298. # ###########################################################################################################
  2299. # hold the App units
  2300. self.units = 'MM'
  2301. # coordinates for relative position display
  2302. self.rel_point1 = (0, 0)
  2303. self.rel_point2 = (0, 0)
  2304. # variable to store coordinates
  2305. self.pos = (0, 0)
  2306. self.pos_canvas = (0, 0)
  2307. self.pos_jump = (0, 0)
  2308. # variable to store mouse coordinates
  2309. self.mouse = [0, 0]
  2310. # variable to store the delta positions on cavnas
  2311. self.dx = 0
  2312. self.dy = 0
  2313. # decide if we have a double click or single click
  2314. self.doubleclick = False
  2315. # store here the is_dragging value
  2316. self.event_is_dragging = False
  2317. # variable to store if a command is active (then the var is not None) and which one it is
  2318. self.command_active = None
  2319. # variable to store the status of moving selection action
  2320. # None value means that it's not an selection action
  2321. # True value = a selection from left to right
  2322. # False value = a selection from right to left
  2323. self.selection_type = None
  2324. # List to store the objects that are currently loaded in FlatCAM
  2325. # This list is updated on each object creation or object delete
  2326. self.all_objects_list = []
  2327. self.objects_under_the_click_list = []
  2328. # List to store the objects that are selected
  2329. self.sel_objects_list = []
  2330. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  2331. self.key_modifiers = None
  2332. # Variable to hold the status of the axis
  2333. self.toggle_axis = True
  2334. # Variable to hold the status of the grid lines
  2335. self.toggle_grid_lines = True
  2336. # Variable to store the status of the fullscreen event
  2337. self.toggle_fscreen = False
  2338. # Variable to store the status of the code editor
  2339. self.toggle_codeeditor = False
  2340. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  2341. self.click_noproject = False
  2342. self.cursor = None
  2343. # Variable to store the GCODE that was edited
  2344. self.gcode_edited = ""
  2345. self.text_editor_tab = None
  2346. # reference for the self.ui.code_editor
  2347. self.reference_code_editor = None
  2348. self.script_code = ''
  2349. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  2350. self.preferences_changed_flag = False
  2351. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  2352. self.tools_db_changed_flag = False
  2353. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  2354. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  2355. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  2356. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  2357. 'tsm']
  2358. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  2359. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  2360. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  2361. 'sbp', 'tap', 'xpi']
  2362. self.svg_list = ['svg']
  2363. self.dxf_list = ['dxf']
  2364. self.pdf_list = ['pdf']
  2365. self.prj_list = ['flatprj']
  2366. self.conf_list = ['flatconfig']
  2367. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  2368. # flag for polygons not cleared
  2369. self.poly_not_cleared = False
  2370. # VisPy visuals
  2371. self.isHovering = False
  2372. self.notHovering = True
  2373. # Window geometry
  2374. self.x_pos = None
  2375. self.y_pos = None
  2376. self.width = None
  2377. self.height = None
  2378. # when True, the app has to return from any thread
  2379. self.abort_flag = False
  2380. # set the value used in the Windows Title
  2381. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  2382. # this holds a widget that is installed in the Plot Area when View Source option is used
  2383. self.source_editor_tab = None
  2384. self.pagesize = {}
  2385. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  2386. # VisPy visuals
  2387. if self.is_legacy is False:
  2388. try:
  2389. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  2390. except AttributeError:
  2391. self.tool_shapes = None
  2392. else:
  2393. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  2394. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  2395. # used in the delayed shutdown self.start_delayed_quit() method
  2396. self.save_timer = None
  2397. # ###########################################################################################################
  2398. # ################################## ADDING FlatCAM EDITORS section #########################################
  2399. # ###########################################################################################################
  2400. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2401. # at the first launch of the App , the editors will not be functional.
  2402. try:
  2403. self.geo_editor = FlatCAMGeoEditor(self)
  2404. except AttributeError:
  2405. pass
  2406. try:
  2407. self.exc_editor = FlatCAMExcEditor(self)
  2408. except AttributeError:
  2409. pass
  2410. try:
  2411. self.grb_editor = FlatCAMGrbEditor(self)
  2412. except AttributeError:
  2413. pass
  2414. self.log.debug("Finished adding FlatCAM Editor's.")
  2415. self.set_ui_title(name=_("New Project - Not saved"))
  2416. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2417. current_platform = platform.architecture()[0]
  2418. if current_platform != '64bit':
  2419. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2420. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2421. # ###########################################################################################################
  2422. # ##################################### Finished the CONSTRUCTOR ############################################
  2423. # ###########################################################################################################
  2424. App.log.debug("END of constructor. Releasing control.")
  2425. # ###########################################################################################################
  2426. # ########################################## SHOW GUI #######################################################
  2427. # ###########################################################################################################
  2428. # if the app is not started as headless, show it
  2429. if self.cmd_line_headless != 1:
  2430. if show_splash:
  2431. # finish the splash
  2432. self.splash.finish(self.ui)
  2433. mgui_settings = QSettings("Open Source", "FlatCAM")
  2434. if mgui_settings.contains("maximized_gui"):
  2435. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  2436. if maximized_ui is True:
  2437. self.ui.showMaximized()
  2438. else:
  2439. self.ui.show()
  2440. else:
  2441. self.ui.show()
  2442. if self.defaults["global_systray_icon"]:
  2443. self.trayIcon.show()
  2444. else:
  2445. log.warning("******************* RUNNING HEADLESS *******************")
  2446. # ###########################################################################################################
  2447. # ######################################## START-UP ARGUMENTS ###############################################
  2448. # ###########################################################################################################
  2449. # test if the program was started with a script as parameter
  2450. if self.cmd_line_shellvar:
  2451. try:
  2452. cnt = 0
  2453. command_tcl = 0
  2454. for i in self.cmd_line_shellvar.split(','):
  2455. if i is not None:
  2456. # noinspection PyBroadException
  2457. try:
  2458. command_tcl = eval(i)
  2459. except Exception:
  2460. command_tcl = i
  2461. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  2462. cnt += 1
  2463. # if there are Windows paths then replace the path separator with a Unix like one
  2464. if sys.platform == 'win32':
  2465. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  2466. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  2467. except Exception as ext:
  2468. print("ERROR: ", ext)
  2469. sys.exit(2)
  2470. if self.cmd_line_shellfile:
  2471. if self.cmd_line_headless != 1:
  2472. if self.ui.shell_dock.isHidden():
  2473. self.ui.shell_dock.show()
  2474. try:
  2475. with open(self.cmd_line_shellfile, "r") as myfile:
  2476. # if show_splash:
  2477. # self.splash.showMessage('%s: %ssec\n%s' % (
  2478. # _("Canvas initialization started.\n"
  2479. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  2480. # _("Executing Tcl Script ...")),
  2481. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  2482. # color=QtGui.QColor("gray"))
  2483. cmd_line_shellfile_text = myfile.read()
  2484. if self.cmd_line_headless != 1:
  2485. self.shell.exec_command(cmd_line_shellfile_text)
  2486. else:
  2487. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  2488. except Exception as ext:
  2489. print("ERROR: ", ext)
  2490. sys.exit(2)
  2491. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2492. # the path/file_name must be enclosed in quotes if it contain spaces
  2493. if App.args:
  2494. self.args_at_startup.emit(App.args)
  2495. if self.old_defaults_found is True:
  2496. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  2497. "Please reboot the application to update."))
  2498. self.old_defaults_found = False
  2499. # ######################################### INIT FINISHED #######################################################
  2500. # #################################################################################################################
  2501. # #################################################################################################################
  2502. # #################################################################################################################
  2503. # #################################################################################################################
  2504. # #################################################################################################################
  2505. @staticmethod
  2506. def copy_and_overwrite(from_path, to_path):
  2507. """
  2508. From here:
  2509. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2510. :param from_path: source path
  2511. :param to_path: destination path
  2512. :return: None
  2513. """
  2514. if os.path.exists(to_path):
  2515. shutil.rmtree(to_path)
  2516. try:
  2517. shutil.copytree(from_path, to_path)
  2518. except FileNotFoundError:
  2519. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2520. shutil.copytree(from_new_path, to_path)
  2521. def on_startup_args(self, args, silent=False):
  2522. """
  2523. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2524. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  2525. :param args: a list containing the application args at startup
  2526. :return: None
  2527. """
  2528. if args is not None:
  2529. args_to_process = args
  2530. else:
  2531. args_to_process = App.args
  2532. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2533. for argument in args_to_process:
  2534. if '.FlatPrj'.lower() in argument.lower():
  2535. try:
  2536. project_name = str(argument)
  2537. if project_name == "":
  2538. if silent is False:
  2539. self.inform.emit(_("Cancelled."))
  2540. else:
  2541. # self.open_project(project_name)
  2542. run_from_arg = True
  2543. # self.worker_task.emit({'fcn': self.open_project,
  2544. # 'params': [project_name, run_from_arg]})
  2545. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2546. except Exception as e:
  2547. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2548. elif '.FlatConfig'.lower() in argument.lower():
  2549. try:
  2550. file_name = str(argument)
  2551. if file_name == "":
  2552. if silent is False:
  2553. self.inform.emit(_("Open Config file failed."))
  2554. else:
  2555. run_from_arg = True
  2556. # self.worker_task.emit({'fcn': self.open_config_file,
  2557. # 'params': [file_name, run_from_arg]})
  2558. self.open_config_file(file_name, run_from_arg=run_from_arg)
  2559. except Exception as e:
  2560. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2561. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  2562. try:
  2563. file_name = str(argument)
  2564. if file_name == "":
  2565. if silent is False:
  2566. self.inform.emit(_("Open Script file failed."))
  2567. else:
  2568. if silent is False:
  2569. self.on_fileopenscript(name=file_name)
  2570. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  2571. self.on_filerunscript(name=file_name)
  2572. except Exception as e:
  2573. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2574. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  2575. log.debug("App.on_startup_args() --> Quit event.")
  2576. sys.exit()
  2577. elif 'save'.lower() in argument.lower():
  2578. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  2579. self.save_defaults()
  2580. else:
  2581. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2582. proc_arg = argument.lower()
  2583. for ext in exc_list:
  2584. proc_ext = ext.replace(' ', '')
  2585. proc_ext = '.%s' % proc_ext
  2586. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2587. file_name = str(argument)
  2588. if file_name == "":
  2589. if silent is False:
  2590. self.inform.emit(_("Open Excellon file failed."))
  2591. else:
  2592. self.on_fileopenexcellon(name=file_name)
  2593. return
  2594. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2595. for ext in gco_list:
  2596. proc_ext = ext.replace(' ', '')
  2597. proc_ext = '.%s' % proc_ext
  2598. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2599. file_name = str(argument)
  2600. if file_name == "":
  2601. if silent is False:
  2602. self.inform.emit(_("Open GCode file failed."))
  2603. else:
  2604. self.on_fileopengcode(name=file_name)
  2605. return
  2606. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2607. for ext in grb_list:
  2608. proc_ext = ext.replace(' ', '')
  2609. proc_ext = '.%s' % proc_ext
  2610. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2611. file_name = str(argument)
  2612. if file_name == "":
  2613. if silent is False:
  2614. self.inform.emit(_("Open Gerber file failed."))
  2615. else:
  2616. self.on_fileopengerber(name=file_name)
  2617. return
  2618. # if it reached here without already returning then the app was registered with a file that it does not
  2619. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  2620. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  2621. # for arg in args_to_process:
  2622. # if 'FlatCAM.exe' in arg:
  2623. # continue
  2624. # else:
  2625. # sys.exit(2)
  2626. def set_ui_title(self, name):
  2627. """
  2628. Sets the title of the main window.
  2629. :param name: String that store the project path and project name
  2630. :return: None
  2631. """
  2632. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  2633. (self.version,
  2634. ('BETA' if self.beta else ''),
  2635. platform.architecture()[0],
  2636. self.engine,
  2637. name)
  2638. )
  2639. def on_app_restart(self):
  2640. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  2641. # be left in the SySTray
  2642. try:
  2643. self.trayIcon.hide()
  2644. except Exception:
  2645. pass
  2646. fcTranslate.restart_program(app=self)
  2647. def defaults_read_form(self):
  2648. """
  2649. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2650. :return: None
  2651. """
  2652. for option in self.defaults_form_fields:
  2653. try:
  2654. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2655. except Exception as e:
  2656. log.debug("App.defaults_read_form() --> %s" % str(e))
  2657. def defaults_write_form(self, factor=None, fl_units=None, source_dict=None):
  2658. """
  2659. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2660. self.defaults dictionary.
  2661. :param factor: will apply a factor to the values that written in the GUI elements
  2662. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2663. :param source_dict: the repository of options, usually is the self.defaults
  2664. :return: None
  2665. """
  2666. options_storage = self.defaults if source_dict is None else source_dict
  2667. for option in options_storage:
  2668. if source_dict:
  2669. self.defaults_write_form_field(option, factor=factor, units=fl_units, defaults_dict=source_dict)
  2670. else:
  2671. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2672. # try:
  2673. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2674. # except KeyError:
  2675. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2676. # pass
  2677. def defaults_write_form_field(self, field, factor=None, units=None, defaults_dict=None):
  2678. """
  2679. Basically it is the worker in the self.defaults_write_form()
  2680. :param field: the GUI element in Preferences GUI to be updated
  2681. :param factor: factor to be applied to the field parameter
  2682. :param units: current FLatCAM measuring units
  2683. :param defaults_dict: the defaults storage
  2684. :return: None, it updates GUI elements
  2685. """
  2686. def_dict = self.defaults if defaults_dict is None else defaults_dict
  2687. try:
  2688. if factor is None:
  2689. if units is None:
  2690. self.defaults_form_fields[field].set_value(def_dict[field])
  2691. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2692. self.defaults_form_fields[field].set_value(def_dict[field])
  2693. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2694. self.defaults_form_fields[field].set_value(def_dict[field])
  2695. else:
  2696. if units is None:
  2697. self.defaults_form_fields[field].set_value(def_dict[field] * factor)
  2698. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2699. self.defaults_form_fields[field].set_value((def_dict[field] * factor))
  2700. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2701. self.defaults_form_fields[field].set_value((def_dict[field] * factor))
  2702. except KeyError:
  2703. pass
  2704. except AttributeError:
  2705. log.debug(field)
  2706. def clear_pool(self):
  2707. """
  2708. Clear the multiprocessing pool and calls garbage collector.
  2709. :return: None
  2710. """
  2711. self.pool.close()
  2712. self.pool = Pool()
  2713. self.pool_recreated.emit(self.pool)
  2714. gc.collect()
  2715. def install_tools(self):
  2716. """
  2717. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2718. Instantiation of the Tools classes.
  2719. The order that the tools are installed is important as they can depend on each other install position.
  2720. :return: None
  2721. """
  2722. self.distance_tool = Distance(self)
  2723. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  2724. before=self.ui.menueditorigin,
  2725. separator=False)
  2726. self.distance_min_tool = DistanceMin(self)
  2727. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  2728. pos=self.ui.menuedit,
  2729. before=self.ui.menueditorigin,
  2730. separator=True)
  2731. self.dblsidedtool = DblSidedTool(self)
  2732. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  2733. self.cal_exc_tool = ToolCalibration(self)
  2734. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  2735. before=self.dblsidedtool.menuAction,
  2736. separator=False)
  2737. self.align_objects_tool = AlignObjects(self)
  2738. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  2739. self.edrills_tool = ToolExtractDrills(self)
  2740. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  2741. self.panelize_tool = Panelize(self)
  2742. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  2743. self.film_tool = Film(self)
  2744. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  2745. self.paste_tool = SolderPaste(self)
  2746. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  2747. self.calculator_tool = ToolCalculator(self)
  2748. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  2749. self.sub_tool = ToolSub(self)
  2750. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  2751. pos=self.ui.menutool, separator=True)
  2752. self.rules_tool = RulesCheck(self)
  2753. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  2754. pos=self.ui.menutool, separator=False)
  2755. self.optimal_tool = ToolOptimal(self)
  2756. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  2757. pos=self.ui.menutool, separator=True)
  2758. self.move_tool = ToolMove(self)
  2759. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  2760. before=self.ui.menueditorigin, separator=True)
  2761. self.cutout_tool = CutOut(self)
  2762. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  2763. before=self.sub_tool.menuAction)
  2764. self.ncclear_tool = NonCopperClear(self)
  2765. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  2766. before=self.sub_tool.menuAction, separator=True)
  2767. self.paint_tool = ToolPaint(self)
  2768. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  2769. before=self.sub_tool.menuAction, separator=True)
  2770. self.copper_thieving_tool = ToolCopperThieving(self)
  2771. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  2772. pos=self.ui.menutool)
  2773. self.fiducial_tool = ToolFiducials(self)
  2774. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  2775. pos=self.ui.menutool)
  2776. self.qrcode_tool = QRCode(self)
  2777. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  2778. pos=self.ui.menutool)
  2779. self.punch_tool = ToolPunchGerber(self)
  2780. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  2781. self.invert_tool = ToolInvertGerber(self)
  2782. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  2783. self.transform_tool = ToolTransform(self)
  2784. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  2785. pos=self.ui.menuoptions, separator=True)
  2786. self.properties_tool = Properties(self)
  2787. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  2788. pos=self.ui.menuoptions)
  2789. self.pdf_tool = ToolPDF(self)
  2790. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  2791. pos=self.ui.menufileimport,
  2792. separator=True)
  2793. self.image_tool = ToolImage(self)
  2794. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  2795. pos=self.ui.menufileimport,
  2796. separator=True)
  2797. self.pcb_wizard_tool = PcbWizard(self)
  2798. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  2799. pos=self.ui.menufileimport)
  2800. self.log.debug("Tools are installed.")
  2801. def remove_tools(self):
  2802. """
  2803. Will remove all the actions in the Tool menu.
  2804. :return: None
  2805. """
  2806. for act in self.ui.menutool.actions():
  2807. self.ui.menutool.removeAction(act)
  2808. def init_tools(self):
  2809. """
  2810. Initialize the Tool tab in the notebook side of the central widget.
  2811. Remove the actions in the Tools menu.
  2812. Instantiate again the FlatCAM tools (plugins).
  2813. All this is required when changing the layout: standard, compact etc.
  2814. :return: None
  2815. """
  2816. log.debug("init_tools()")
  2817. # delete the data currently in the Tools Tab and the Tab itself
  2818. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2819. if widget is not None:
  2820. widget.deleteLater()
  2821. self.ui.notebook.removeTab(2)
  2822. # rebuild the Tools Tab
  2823. self.ui.tool_tab = QtWidgets.QWidget()
  2824. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2825. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2826. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2827. self.ui.tool_scroll_area = VerticalScrollArea()
  2828. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2829. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2830. # first remove all of them
  2831. self.remove_tools()
  2832. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2833. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  2834. '&Command Line\tS')
  2835. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  2836. # third install all of them
  2837. try:
  2838. self.install_tools()
  2839. except AttributeError:
  2840. pass
  2841. self.log.debug("Tools are initialized.")
  2842. # def parse_system_fonts(self):
  2843. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2844. # 'params': []})
  2845. def connect_toolbar_signals(self):
  2846. """
  2847. Reconnect the signals to the actions in the toolbar.
  2848. This has to be done each time after the FlatCAM tools are removed/installed.
  2849. :return: None
  2850. """
  2851. # Toolbar
  2852. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2853. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2854. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2855. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2856. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2857. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2858. self.ui.replot_btn.triggered.connect(self.plot_all)
  2859. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2860. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2861. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2862. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2863. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2864. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2865. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2866. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2867. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  2868. self.ui.delete_btn.triggered.connect(self.on_delete)
  2869. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  2870. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  2871. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  2872. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  2873. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  2874. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  2875. self.ui.shell_btn.triggered.connect(self.toggle_shell)
  2876. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2877. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2878. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2879. # Tools Toolbar Signals
  2880. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2881. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  2882. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  2883. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  2884. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2885. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2886. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2887. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2888. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2889. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2890. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2891. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  2892. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  2893. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2894. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2895. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  2896. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  2897. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  2898. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  2899. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  2900. def object2editor(self):
  2901. """
  2902. Send the current Geometry or Excellon object (if any) into the it's editor.
  2903. :return: None
  2904. """
  2905. self.report_usage("object2editor()")
  2906. # disable the objects menu as it may interfere with the Editors
  2907. self.ui.menuobjects.setDisabled(True)
  2908. edited_object = self.collection.get_active()
  2909. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  2910. isinstance(edited_object, ExcellonObject):
  2911. pass
  2912. else:
  2913. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber or Excellon Object to edit."))
  2914. return
  2915. if isinstance(edited_object, GeometryObject):
  2916. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2917. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2918. # we set the notebook to hidden
  2919. # self.ui.splitter.setSizes([0, 1])
  2920. if edited_object.multigeo is True:
  2921. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  2922. if len(sel_rows) > 1:
  2923. self.inform.emit('[WARNING_NOTCL] %s' %
  2924. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  2925. "is not possible.\n"
  2926. "Edit only one geometry at a time."))
  2927. # determine the tool dia of the selected tool
  2928. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  2929. # now find the key in the edited_object.tools that has this tooldia
  2930. multi_tool = 1
  2931. for tool in edited_object.tools:
  2932. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2933. multi_tool = tool
  2934. break
  2935. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2936. else:
  2937. self.geo_editor.edit_fcgeometry(edited_object)
  2938. # set call source to the Editor we go into
  2939. self.call_source = 'geo_editor'
  2940. elif isinstance(edited_object, ExcellonObject):
  2941. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2942. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2943. if self.ui.splitter.sizes()[0] == 0:
  2944. self.ui.splitter.setSizes([1, 1])
  2945. self.exc_editor.edit_fcexcellon(edited_object)
  2946. # set call source to the Editor we go into
  2947. self.call_source = 'exc_editor'
  2948. elif isinstance(edited_object, GerberObject):
  2949. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2950. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2951. if self.ui.splitter.sizes()[0] == 0:
  2952. self.ui.splitter.setSizes([1, 1])
  2953. self.grb_editor.edit_fcgerber(edited_object)
  2954. # set call source to the Editor we go into
  2955. self.call_source = 'grb_editor'
  2956. # reset the following variables so the UI is built again after edit
  2957. edited_object.ui_build = False
  2958. edited_object.build_aperture_storage = False
  2959. # make sure that we can't select another object while in Editor Mode:
  2960. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2961. self.ui.project_frame.setDisabled(True)
  2962. # delete any selection shape that might be active as they are not relevant in Editor
  2963. self.delete_selection_shape()
  2964. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2965. self.ui.plot_tab_area.protectTab(0)
  2966. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  2967. self.should_we_save = True
  2968. def editor2object(self, cleanup=None):
  2969. """
  2970. Transfers the Geometry or Excellon from it's editor to the current object.
  2971. :return: None
  2972. """
  2973. self.report_usage("editor2object()")
  2974. # re-enable the objects menu that was disabled on entry in Editor mode
  2975. self.ui.menuobjects.setDisabled(False)
  2976. # do not update a geometry or excellon object unless it comes out of an editor
  2977. if self.call_source != 'app':
  2978. edited_obj = self.collection.get_active()
  2979. if cleanup is None:
  2980. msgbox = QtWidgets.QMessageBox()
  2981. msgbox.setText(_("Do you want to save the edited object?"))
  2982. msgbox.setWindowTitle(_("Close Editor"))
  2983. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2984. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2985. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2986. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2987. msgbox.setDefaultButton(bt_yes)
  2988. msgbox.exec_()
  2989. response = msgbox.clickedButton()
  2990. if response == bt_yes:
  2991. # clean the Tools Tab
  2992. self.ui.tool_scroll_area.takeWidget()
  2993. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2994. self.ui.notebook.setTabText(2, "Tool")
  2995. if isinstance(edited_obj, GeometryObject):
  2996. obj_type = "Geometry"
  2997. if cleanup is None:
  2998. self.geo_editor.update_fcgeometry(edited_obj)
  2999. # self.geo_editor.update_options(edited_obj)
  3000. self.geo_editor.deactivate()
  3001. # restore GUI to the Selected TAB
  3002. # Remove anything else in the GUI
  3003. self.ui.tool_scroll_area.takeWidget()
  3004. # update the geo object options so it is including the bounding box values
  3005. try:
  3006. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  3007. edited_obj.options['xmin'] = xmin
  3008. edited_obj.options['ymin'] = ymin
  3009. edited_obj.options['xmax'] = xmax
  3010. edited_obj.options['ymax'] = ymax
  3011. except AttributeError as e:
  3012. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  3013. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  3014. edited_obj.build_ui()
  3015. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  3016. elif isinstance(edited_obj, GerberObject):
  3017. obj_type = "Gerber"
  3018. if cleanup is None:
  3019. self.grb_editor.update_fcgerber()
  3020. self.grb_editor.update_options(edited_obj)
  3021. self.grb_editor.deactivate_grb_editor()
  3022. # delete the old object (the source object) if it was an empty one
  3023. try:
  3024. if len(edited_obj.solid_geometry) == 0:
  3025. old_name = edited_obj.options['name']
  3026. self.collection.set_active(old_name)
  3027. self.collection.delete_active()
  3028. except TypeError:
  3029. # if the solid_geometry is a single Polygon the len() will not work
  3030. # in any case, falling here means that we have something in the solid_geometry, even if only
  3031. # a single Polygon, therefore we pass this
  3032. pass
  3033. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  3034. # restore GUI to the Selected TAB
  3035. # Remove anything else in the GUI
  3036. self.ui.selected_scroll_area.takeWidget()
  3037. elif isinstance(edited_obj, ExcellonObject):
  3038. obj_type = "Excellon"
  3039. if cleanup is None:
  3040. self.exc_editor.update_fcexcellon(edited_obj)
  3041. # self.exc_editor.update_options(edited_obj)
  3042. self.exc_editor.deactivate()
  3043. # restore GUI to the Selected TAB
  3044. # Remove anything else in the GUI
  3045. self.ui.tool_scroll_area.takeWidget()
  3046. # delete the old object (the source object) if it was an empty one
  3047. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  3048. old_name = edited_obj.options['name']
  3049. self.collection.delete_by_name(name=old_name)
  3050. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  3051. else:
  3052. self.inform.emit('[WARNING_NOTCL] %s' %
  3053. _("Select a Gerber, Geometry or Excellon Object to update."))
  3054. return
  3055. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  3056. elif response == bt_no:
  3057. # clean the Tools Tab
  3058. self.ui.tool_scroll_area.takeWidget()
  3059. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  3060. self.ui.notebook.setTabText(2, "Tool")
  3061. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  3062. if isinstance(edited_obj, GeometryObject):
  3063. self.geo_editor.deactivate()
  3064. edited_obj.build_ui()
  3065. elif isinstance(edited_obj, GerberObject):
  3066. self.grb_editor.deactivate_grb_editor()
  3067. edited_obj.build_ui()
  3068. elif isinstance(edited_obj, ExcellonObject):
  3069. self.exc_editor.deactivate()
  3070. edited_obj.build_ui()
  3071. else:
  3072. self.inform.emit('[WARNING_NOTCL] %s' %
  3073. _("Select a Gerber, Geometry or Excellon Object to update."))
  3074. return
  3075. elif response == bt_cancel:
  3076. return
  3077. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  3078. # edited_obj.build_ui()
  3079. # Switch notebook to Selected page
  3080. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3081. else:
  3082. if isinstance(edited_obj, GeometryObject):
  3083. self.geo_editor.deactivate()
  3084. elif isinstance(edited_obj, GerberObject):
  3085. self.grb_editor.deactivate_grb_editor()
  3086. elif isinstance(edited_obj, ExcellonObject):
  3087. self.exc_editor.deactivate()
  3088. else:
  3089. self.inform.emit('[WARNING_NOTCL] %s' %
  3090. _("Select a Gerber, Geometry or Excellon Object to update."))
  3091. return
  3092. # if notebook is hidden we show it
  3093. if self.ui.splitter.sizes()[0] == 0:
  3094. self.ui.splitter.setSizes([1, 1])
  3095. # restore the call_source to app
  3096. self.call_source = 'app'
  3097. edited_obj.plot()
  3098. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  3099. self.ui.plot_tab_area.protectTab(0)
  3100. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  3101. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  3102. self.ui.project_frame.setDisabled(False)
  3103. def get_last_folder(self):
  3104. """
  3105. Get the folder path from where the last file was opened.
  3106. :return: String, last opened folder path
  3107. """
  3108. return self.defaults["global_last_folder"]
  3109. def get_last_save_folder(self):
  3110. """
  3111. Get the folder path from where the last file was saved.
  3112. :return: String, last saved folder path
  3113. """
  3114. loc = self.defaults["global_last_save_folder"]
  3115. if loc is None:
  3116. loc = self.defaults["global_last_folder"]
  3117. if loc is None:
  3118. loc = os.path.dirname(__file__)
  3119. return loc
  3120. def report_usage(self, resource):
  3121. """
  3122. Increments usage counter for the given resource
  3123. in self.defaults['global_stats'].
  3124. :param resource: Name of the resource.
  3125. :return: None
  3126. """
  3127. if resource in self.defaults['global_stats']:
  3128. self.defaults['global_stats'][resource] += 1
  3129. else:
  3130. self.defaults['global_stats'][resource] = 1
  3131. def info(self, msg):
  3132. """
  3133. Informs the user. Normally on the status bar, optionally
  3134. also on the shell.
  3135. :param msg: Text to write.
  3136. :return: None
  3137. """
  3138. # Type of message in brackets at the beginning of the message.
  3139. match = re.search(r"\[(.*)\](.*)", msg)
  3140. if match:
  3141. level = match.group(1)
  3142. msg_ = match.group(2)
  3143. self.ui.fcinfo.set_status(str(msg_), level=level)
  3144. if level.lower() == "error":
  3145. self.shell_message(msg, error=True, show=True)
  3146. elif level.lower() == "warning":
  3147. self.shell_message(msg, warning=True, show=True)
  3148. elif level.lower() == "error_notcl":
  3149. self.shell_message(msg, error=True, show=False)
  3150. elif level.lower() == "warning_notcl":
  3151. self.shell_message(msg, warning=True, show=False)
  3152. elif level.lower() == "success":
  3153. self.shell_message(msg, success=True, show=False)
  3154. elif level.lower() == "selected":
  3155. self.shell_message(msg, selected=True, show=False)
  3156. else:
  3157. self.shell_message(msg, show=False)
  3158. else:
  3159. self.ui.fcinfo.set_status(str(msg), level="info")
  3160. # make sure that if the message is to clear the infobar with a space
  3161. # is not printed over and over on the shell
  3162. if msg != '':
  3163. self.shell_message(msg)
  3164. def restore_toolbar_view(self):
  3165. """
  3166. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  3167. was saved in the defaults dictionary.
  3168. :return: None
  3169. """
  3170. tb = self.defaults["global_toolbar_view"]
  3171. if tb & 1:
  3172. self.ui.toolbarfile.setVisible(True)
  3173. else:
  3174. self.ui.toolbarfile.setVisible(False)
  3175. if tb & 2:
  3176. self.ui.toolbargeo.setVisible(True)
  3177. else:
  3178. self.ui.toolbargeo.setVisible(False)
  3179. if tb & 4:
  3180. self.ui.toolbarview.setVisible(True)
  3181. else:
  3182. self.ui.toolbarview.setVisible(False)
  3183. if tb & 8:
  3184. self.ui.toolbartools.setVisible(True)
  3185. else:
  3186. self.ui.toolbartools.setVisible(False)
  3187. if tb & 16:
  3188. self.ui.exc_edit_toolbar.setVisible(True)
  3189. else:
  3190. self.ui.exc_edit_toolbar.setVisible(False)
  3191. if tb & 32:
  3192. self.ui.geo_edit_toolbar.setVisible(True)
  3193. else:
  3194. self.ui.geo_edit_toolbar.setVisible(False)
  3195. if tb & 64:
  3196. self.ui.grb_edit_toolbar.setVisible(True)
  3197. else:
  3198. self.ui.grb_edit_toolbar.setVisible(False)
  3199. if tb & 128:
  3200. self.ui.snap_toolbar.setVisible(True)
  3201. else:
  3202. self.ui.snap_toolbar.setVisible(False)
  3203. if tb & 256:
  3204. self.ui.toolbarshell.setVisible(True)
  3205. else:
  3206. self.ui.toolbarshell.setVisible(False)
  3207. def load_defaults(self, filename):
  3208. """
  3209. Loads the aplication's default settings from current_defaults.FlatConfig into
  3210. ``self.defaults``.
  3211. :return: None
  3212. """
  3213. try:
  3214. f = open(self.data_path + "/" + filename + ".FlatConfig")
  3215. options = f.read()
  3216. f.close()
  3217. except IOError:
  3218. self.log.error("Could not load defaults file.")
  3219. self.inform.emit('[ERROR] %s' % _("Could not load defaults file."))
  3220. # in case the defaults file can't be loaded, show all toolbars
  3221. self.defaults["global_toolbar_view"] = 511
  3222. return
  3223. try:
  3224. defaults = json.loads(options)
  3225. except Exception:
  3226. # in case the defaults file can't be loaded, show all toolbars
  3227. self.defaults["global_toolbar_view"] = 511
  3228. e = sys.exc_info()[0]
  3229. App.log.error(str(e))
  3230. self.inform.emit('[ERROR] %s' % _("Failed to parse defaults file."))
  3231. return
  3232. if defaults:
  3233. if 'version' not in defaults or defaults['version'] != self.defaults['version']:
  3234. for k, v in defaults.items():
  3235. if k in self.defaults and k != 'version':
  3236. # check if the types are the same. Because some types (tuple, float, int etc)
  3237. # may be stored as strings we check their types.
  3238. try:
  3239. target = eval(self.defaults[k])
  3240. except (NameError, TypeError):
  3241. # it's an unknown string leave it as it is
  3242. target = deepcopy(self.defaults[k])
  3243. try:
  3244. source = eval(v)
  3245. except NameError:
  3246. # it's an unknown string leave it as it is
  3247. source = deepcopy(v)
  3248. if type(target) == type(source):
  3249. self.defaults[k] = v
  3250. # delete old factory defaults
  3251. try:
  3252. fact_def_file_path = os.path.join(self.data_path, 'factory_defaults.FlatConfig')
  3253. os.chmod(fact_def_file_path, stat.S_IRWXO | stat.S_IWRITE | stat.S_IWGRP)
  3254. os.remove(fact_def_file_path)
  3255. # recreate a new factory defaults file and save the factory defaults data into it
  3256. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  3257. json.dump(self.defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3258. f_f_def_s.close()
  3259. # and then make the factory_defaults.FlatConfig file read_only
  3260. # so it can't be modified after creation.
  3261. os.chmod(fact_def_file_path, S_IREAD | S_IRGRP | S_IROTH)
  3262. except Exception as e:
  3263. log.debug("App.load_defaults() -> deleting old factory defaults file -> %s" % str(e))
  3264. self.old_defaults_found = True
  3265. else:
  3266. self.old_defaults_found = False
  3267. self.defaults.update(defaults)
  3268. log.debug("FlatCAM defaults loaded from: %s" % filename)
  3269. def on_restore_defaults_preferences(self):
  3270. """
  3271. Loads the application's factory default settings from factory_defaults.FlatConfig into
  3272. ``self.defaults``.
  3273. :return: None
  3274. """
  3275. App.log.debug("App.on_restore_defaults_preferences()")
  3276. filename = self.data_path + '/factory_defaults.FlatConfig'
  3277. if filename == "":
  3278. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  3279. else:
  3280. try:
  3281. f = open(filename)
  3282. options = f.read()
  3283. f.close()
  3284. except IOError:
  3285. self.log.error("Could not load factory defaults file.")
  3286. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load factory defaults file."))
  3287. return
  3288. try:
  3289. defaults_from_file = json.loads(options)
  3290. except Exception:
  3291. e = sys.exc_info()[0]
  3292. App.log.error(str(e))
  3293. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse factory defaults file."))
  3294. return
  3295. self.defaults.update(defaults_from_file)
  3296. # update the dict that is used to restore the values in the defaults form if Cancel is clicked in the
  3297. # Preferences window
  3298. self.current_defaults.update(defaults_from_file)
  3299. self.on_preferences_edited()
  3300. self.inform.emit('[success] %s' % _("Preferences default values are restored."))
  3301. def on_import_preferences(self):
  3302. """
  3303. Loads the application default settings from a saved file into
  3304. ``self.defaults`` dictionary.
  3305. :return: None
  3306. """
  3307. self.report_usage("on_import_preferences")
  3308. App.log.debug("App.on_import_preferences()")
  3309. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  3310. try:
  3311. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3312. directory=self.data_path,
  3313. filter=filter_)
  3314. except TypeError:
  3315. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3316. filter=filter_)
  3317. filename = str(filename)
  3318. if filename == "":
  3319. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  3320. else:
  3321. try:
  3322. f = open(filename)
  3323. options = f.read()
  3324. f.close()
  3325. except IOError:
  3326. self.log.error("Could not load defaults file.")
  3327. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load defaults file."))
  3328. return
  3329. try:
  3330. defaults_from_file = json.loads(options)
  3331. except Exception:
  3332. e = sys.exc_info()[0]
  3333. App.log.error(str(e))
  3334. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse defaults file."))
  3335. return
  3336. self.defaults.update(defaults_from_file)
  3337. # update the dict that is used to restore the values in the defaults form if Cancel is clicked in the
  3338. # Preferences window
  3339. self.current_defaults.update(defaults_from_file)
  3340. self.on_preferences_edited()
  3341. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  3342. def on_export_preferences(self):
  3343. """
  3344. Save the defaults dictionary to a file.
  3345. :return: None
  3346. """
  3347. self.report_usage("on_export_preferences")
  3348. App.log.debug("on_export_preferences()")
  3349. defaults_file_content = None
  3350. self.date = str(datetime.today()).rpartition('.')[0]
  3351. self.date = ''.join(c for c in self.date if c not in ':-')
  3352. self.date = self.date.replace(' ', '_')
  3353. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  3354. try:
  3355. filename, _f = FCFileSaveDialog.get_saved_filename(
  3356. caption=_("Export FlatCAM Preferences"),
  3357. directory=self.data_path + '/preferences_' + self.date,
  3358. filter=filter__
  3359. )
  3360. except TypeError:
  3361. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  3362. filename = str(filename)
  3363. defaults_from_file = {}
  3364. if filename == "":
  3365. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  3366. return
  3367. else:
  3368. try:
  3369. f = open(filename, 'w')
  3370. defaults_file_content = f.read()
  3371. f.close()
  3372. except PermissionError:
  3373. self.inform.emit('[WARNING] %s' %
  3374. _("Permission denied, saving not possible.\n"
  3375. "Most likely another app is holding the file open and not accessible."))
  3376. return
  3377. except IOError:
  3378. App.log.debug('Creating a new preferences file ...')
  3379. f = open(filename, 'w')
  3380. json.dump({}, f)
  3381. f.close()
  3382. except Exception:
  3383. e = sys.exc_info()[0]
  3384. App.log.error("Could not load defaults file.")
  3385. App.log.error(str(e))
  3386. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load preferences file."))
  3387. return
  3388. try:
  3389. defaults_from_file = json.loads(defaults_file_content)
  3390. except Exception:
  3391. App.log.warning("Trying to read an empty Preferences file. Continue.")
  3392. # Update options
  3393. self.defaults_read_form()
  3394. defaults_from_file.update(self.defaults)
  3395. self.propagate_defaults(silent=True)
  3396. # Save update options
  3397. try:
  3398. f = open(filename, "w")
  3399. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  3400. f.close()
  3401. except Exception:
  3402. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  3403. return
  3404. if self.defaults["global_open_style"] is False:
  3405. self.file_opened.emit("preferences", filename)
  3406. self.file_saved.emit("preferences", filename)
  3407. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  3408. def save_to_file(self, content_to_save, txt_content):
  3409. """
  3410. Save something to a file.
  3411. :return: None
  3412. """
  3413. self.report_usage("save_to_file")
  3414. App.log.debug("save_to_file()")
  3415. self.date = str(datetime.today()).rpartition('.')[0]
  3416. self.date = ''.join(c for c in self.date if c not in ':-')
  3417. self.date = self.date.replace(' ', '_')
  3418. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  3419. path_to_save = self.defaults["global_last_save_folder"] if\
  3420. self.defaults["global_last_save_folder"] is not None else self.data_path
  3421. try:
  3422. filename, _f = FCFileSaveDialog.get_saved_filename(
  3423. caption=_("Save to file"),
  3424. directory=path_to_save + '/file_' + self.date,
  3425. filter=filter__
  3426. )
  3427. except TypeError:
  3428. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  3429. filename = str(filename)
  3430. if filename == "":
  3431. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  3432. return
  3433. else:
  3434. try:
  3435. with open(filename, 'w') as f:
  3436. ___ = f.read()
  3437. except PermissionError:
  3438. self.inform.emit('[WARNING] %s' %
  3439. _("Permission denied, saving not possible.\n"
  3440. "Most likely another app is holding the file open and not accessible."))
  3441. return
  3442. except IOError:
  3443. App.log.debug('Creating a new file ...')
  3444. f = open(filename, 'w')
  3445. f.close()
  3446. except Exception:
  3447. e = sys.exc_info()[0]
  3448. App.log.error("Could not load the file.")
  3449. App.log.error(str(e))
  3450. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  3451. return
  3452. # Save content
  3453. if filename.rpartition('.')[2].lower() == 'html':
  3454. file_content = content_to_save
  3455. else:
  3456. file_content = txt_content
  3457. try:
  3458. with open(filename, "w") as f:
  3459. f.write(file_content)
  3460. except Exception:
  3461. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  3462. return
  3463. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  3464. def save_geometry(self, x, y, width, height, notebook_width):
  3465. """
  3466. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  3467. launch of the application.
  3468. :param x: X position of the main window
  3469. :param y: Y position of the main window
  3470. :param width: width of the main window
  3471. :param height: height of the main window
  3472. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  3473. :return: None
  3474. """
  3475. self.defaults["global_def_win_x"] = x
  3476. self.defaults["global_def_win_y"] = y
  3477. self.defaults["global_def_win_w"] = width
  3478. self.defaults["global_def_win_h"] = height
  3479. self.defaults["global_def_notebook_width"] = notebook_width
  3480. self.save_defaults()
  3481. def restore_main_win_geom(self):
  3482. try:
  3483. self.ui.setGeometry(self.defaults["global_def_win_x"],
  3484. self.defaults["global_def_win_y"],
  3485. self.defaults["global_def_win_w"],
  3486. self.defaults["global_def_win_h"])
  3487. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  3488. except KeyError as e:
  3489. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  3490. def message_dialog(self, title, message, kind="info"):
  3491. """
  3492. Builds and show a custom QMessageBox to be used in FlatCAM.
  3493. :param title: title of the QMessageBox
  3494. :param message: message to be displayed
  3495. :param kind: type of QMessageBox; will display a specific icon.
  3496. :return:
  3497. """
  3498. icon = {"info": QtWidgets.QMessageBox.Information,
  3499. "warning": QtWidgets.QMessageBox.Warning,
  3500. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3501. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  3502. dlg.setText(message)
  3503. dlg.exec_()
  3504. def register_recent(self, kind, filename):
  3505. """
  3506. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  3507. dictionary.
  3508. :param kind: type of file that was opened
  3509. :param filename: the path and file name for the file that was opened
  3510. :return:
  3511. """
  3512. self.log.debug("register_recent()")
  3513. self.log.debug(" %s" % kind)
  3514. self.log.debug(" %s" % filename)
  3515. record = {'kind': str(kind), 'filename': str(filename)}
  3516. if record in self.recent:
  3517. return
  3518. if record in self.recent_projects:
  3519. return
  3520. if record['kind'] == 'project':
  3521. self.recent_projects.insert(0, record)
  3522. else:
  3523. self.recent.insert(0, record)
  3524. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3525. self.recent.pop()
  3526. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3527. self.recent_projects.pop()
  3528. try:
  3529. f = open(self.data_path + '/recent.json', 'w')
  3530. except IOError:
  3531. App.log.error("Failed to open recent items file for writing.")
  3532. self.inform.emit('[ERROR_NOTCL] %s' %
  3533. _('Failed to open recent files file for writing.'))
  3534. return
  3535. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3536. f.close()
  3537. try:
  3538. fp = open(self.data_path + '/recent_projects.json', 'w')
  3539. except IOError:
  3540. App.log.error("Failed to open recent items file for writing.")
  3541. self.inform.emit('[ERROR_NOTCL] %s' %
  3542. _('Failed to open recent projects file for writing.'))
  3543. return
  3544. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3545. fp.close()
  3546. # Re-build the recent items menu
  3547. self.setup_recent_items()
  3548. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3549. """
  3550. Creates a new specialized FlatCAMObj and attaches it to the application,
  3551. this is, updates the GUI accordingly, any other records and plots it.
  3552. This method is thread-safe.
  3553. Notes:
  3554. * If the name is in use, the self.collection will modify it
  3555. when appending it to the collection. There is no need to handle
  3556. name conflicts here.
  3557. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3558. :type kind: str
  3559. :param name: Name for the object.
  3560. :type name: str
  3561. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3562. The function is called with 2 parameters: the new object and the App instance.
  3563. :type initialize: function
  3564. :param active:
  3565. :param fit:
  3566. :param plot: If to plot the resulting object
  3567. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3568. self.collection
  3569. :return: None
  3570. :rtype: None
  3571. """
  3572. App.log.debug("new_object()")
  3573. obj_plot = plot
  3574. obj_autoselected = autoselected
  3575. t0 = time.time() # Debug
  3576. # ## Create object
  3577. classdict = {
  3578. "gerber": GerberObject,
  3579. "excellon": ExcellonObject,
  3580. "cncjob": CNCJobObject,
  3581. "geometry": GeometryObject,
  3582. "script": ScriptObject,
  3583. "document": DocumentObject
  3584. }
  3585. App.log.debug("Calling object constructor...")
  3586. # Object creation/instantiation
  3587. obj = classdict[kind](name)
  3588. obj.units = self.options["units"]
  3589. # IMPORTANT
  3590. # The key names in defaults and options dictionary's are not random:
  3591. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3592. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  3593. # copied to self.options. After that, below, depending on the type of
  3594. # object that is created, it will strip the name of the object and the underline (if the original key was
  3595. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3596. # "toolchange"
  3597. for option in self.options:
  3598. if option.find(kind + "_") == 0:
  3599. oname = option[len(kind) + 1:]
  3600. obj.options[oname] = self.options[option]
  3601. obj.isHovering = False
  3602. obj.notHovering = True
  3603. # Initialize as per user request
  3604. # User must take care to implement initialize
  3605. # in a thread-safe way as is is likely that we
  3606. # have been invoked in a separate thread.
  3607. t1 = time.time()
  3608. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3609. try:
  3610. return_value = initialize(obj, self)
  3611. except Exception as e:
  3612. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  3613. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3614. msg += traceback.format_exc()
  3615. self.inform.emit(msg)
  3616. return "fail"
  3617. t2 = time.time()
  3618. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3619. if return_value == 'fail':
  3620. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3621. return "fail"
  3622. # Check units and convert if necessary
  3623. # This condition CAN be true because initialize() can change obj.units
  3624. if self.options["units"].upper() != obj.units.upper():
  3625. self.inform.emit('%s: %s' % (_("Converting units to "), self.options["units"]))
  3626. obj.convert_units(self.options["units"])
  3627. t3 = time.time()
  3628. self.log.debug("%f seconds converting units." % (t3 - t2))
  3629. # Create the bounding box for the object and then add the results to the obj.options
  3630. # But not for Scripts or for Documents
  3631. if kind != 'document' and kind != 'script':
  3632. try:
  3633. xmin, ymin, xmax, ymax = obj.bounds()
  3634. obj.options['xmin'] = xmin
  3635. obj.options['ymin'] = ymin
  3636. obj.options['xmax'] = xmax
  3637. obj.options['ymax'] = ymax
  3638. except Exception as e:
  3639. log.warning("App.new_object() -> The object has no bounds properties. %s" % str(e))
  3640. return "fail"
  3641. try:
  3642. if kind == 'excellon':
  3643. obj.fill_color = self.defaults["excellon_plot_fill"]
  3644. obj.outline_color = self.defaults["excellon_plot_line"]
  3645. if kind == 'gerber':
  3646. obj.fill_color = self.defaults["gerber_plot_fill"]
  3647. obj.outline_color = self.defaults["gerber_plot_line"]
  3648. except Exception as e:
  3649. log.warning("App.new_object() -> setting colors error. %s" % str(e))
  3650. # update the KeyWords list with the name of the file
  3651. self.myKeywords.append(obj.options['name'])
  3652. log.debug("Moving new object back to main thread.")
  3653. # Move the object to the main thread and let the app know that it is available.
  3654. obj.moveToThread(self.main_thread)
  3655. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3656. return obj
  3657. def new_excellon_object(self):
  3658. """
  3659. Creates a new, blank Excellon object.
  3660. :return: None
  3661. """
  3662. self.report_usage("new_excellon_object()")
  3663. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3664. def new_geometry_object(self):
  3665. """
  3666. Creates a new, blank and single-tool Geometry object.
  3667. :return: None
  3668. """
  3669. self.report_usage("new_geometry_object()")
  3670. def initialize(obj, app):
  3671. obj.multitool = False
  3672. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3673. def new_gerber_object(self):
  3674. """
  3675. Creates a new, blank Gerber object.
  3676. :return: None
  3677. """
  3678. self.report_usage("new_gerber_object()")
  3679. def initialize(grb_obj, app):
  3680. grb_obj.multitool = False
  3681. grb_obj.source_file = []
  3682. grb_obj.multigeo = False
  3683. grb_obj.follow = False
  3684. grb_obj.apertures = {}
  3685. grb_obj.solid_geometry = []
  3686. try:
  3687. grb_obj.options['xmin'] = 0
  3688. grb_obj.options['ymin'] = 0
  3689. grb_obj.options['xmax'] = 0
  3690. grb_obj.options['ymax'] = 0
  3691. except KeyError:
  3692. pass
  3693. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3694. def new_script_object(self, name=None, text=None):
  3695. """
  3696. Creates a new, blank TCL Script object.
  3697. :param name: a name for the new object
  3698. :param text: pass a source file to the newly created script to be loaded in it
  3699. :return: None
  3700. """
  3701. self.report_usage("new_script_object()")
  3702. if text is not None:
  3703. new_source_file = text
  3704. else:
  3705. # commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  3706. # "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n" \
  3707. # "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  3708. # "# ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n" \
  3709. # "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  3710. # "ListSys, MillDrills,\n" \
  3711. # "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  3712. # "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n" \
  3713. # "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  3714. # "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  3715. # "# SubtractRectangle, Version, WriteGCode\n"
  3716. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  3717. '# %s:\n' % _('TCL Tutorial is here') + \
  3718. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  3719. '# %s:\n' % _("FlatCAM commands list")
  3720. new_source_file += '# %s\n\n' % _("Type >help< followed by Run Code for a list of FlatCAM Tcl Commands "
  3721. "(displayed in Tcl Shell).")
  3722. def initialize(obj, app):
  3723. obj.source_file = deepcopy(new_source_file)
  3724. if name is None:
  3725. outname = 'new_script'
  3726. else:
  3727. outname = name
  3728. self.new_object('script', outname, initialize, plot=False)
  3729. def new_document_object(self):
  3730. """
  3731. Creates a new, blank Document object.
  3732. :return: None
  3733. """
  3734. self.report_usage("new_document_object()")
  3735. def initialize(obj, app):
  3736. obj.source_file = ""
  3737. self.new_object('document', 'new_document', initialize, plot=False)
  3738. def on_object_created(self, obj, plot, auto_select):
  3739. """
  3740. Event callback for object creation.
  3741. It will add the new object to the collection. After that it will plot the object in a threaded way
  3742. :param obj: The newly created FlatCAM object.
  3743. :param plot: if the newly create object t obe plotted
  3744. :param auto_select: if the newly created object to be autoselected after creation
  3745. :return: None
  3746. """
  3747. t0 = time.time() # DEBUG
  3748. self.log.debug("on_object_created()")
  3749. # The Collection might change the name if there is a collision
  3750. self.collection.append(obj)
  3751. # after adding the object to the collection always update the list of objects that are in the collection
  3752. self.all_objects_list = self.collection.get_list()
  3753. # self.inform.emit('[selected] %s created & selected: %s' %
  3754. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3755. if obj.kind == 'gerber':
  3756. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3757. kind=obj.kind.capitalize(),
  3758. color='green',
  3759. name=str(obj.options['name']), tx=_("created/selected"))
  3760. )
  3761. elif obj.kind == 'excellon':
  3762. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3763. kind=obj.kind.capitalize(),
  3764. color='brown',
  3765. name=str(obj.options['name']), tx=_("created/selected"))
  3766. )
  3767. elif obj.kind == 'cncjob':
  3768. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3769. kind=obj.kind.capitalize(),
  3770. color='blue',
  3771. name=str(obj.options['name']), tx=_("created/selected"))
  3772. )
  3773. elif obj.kind == 'geometry':
  3774. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3775. kind=obj.kind.capitalize(),
  3776. color='red',
  3777. name=str(obj.options['name']), tx=_("created/selected"))
  3778. )
  3779. elif obj.kind == 'script':
  3780. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3781. kind=obj.kind.capitalize(),
  3782. color='orange',
  3783. name=str(obj.options['name']), tx=_("created/selected"))
  3784. )
  3785. elif obj.kind == 'document':
  3786. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3787. kind=obj.kind.capitalize(),
  3788. color='darkCyan',
  3789. name=str(obj.options['name']), tx=_("created/selected"))
  3790. )
  3791. # update the SHELL auto-completer model with the name of the new object
  3792. self.shell._edit.set_model_data(self.myKeywords)
  3793. if auto_select:
  3794. # select the just opened object but deselect the previous ones
  3795. self.collection.set_all_inactive()
  3796. self.collection.set_active(obj.options["name"])
  3797. else:
  3798. self.collection.set_all_inactive()
  3799. # here it is done the object plotting
  3800. def worker_task(t_obj):
  3801. with self.proc_container.new(_("Plotting")):
  3802. if isinstance(t_obj, CNCJobObject):
  3803. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3804. else:
  3805. t_obj.plot()
  3806. t1 = time.time() # DEBUG
  3807. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3808. self.object_plotted.emit(t_obj)
  3809. # Send to worker
  3810. # self.worker.add_task(worker_task, [self])
  3811. if plot is True:
  3812. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3813. def on_object_changed(self, obj):
  3814. """
  3815. Called whenever the geometry of the object was changed in some way.
  3816. This require the update of it's bounding values so it can be the selected on canvas.
  3817. Update the bounding box data from obj.options
  3818. :param obj: the object that was changed
  3819. :return: None
  3820. """
  3821. xmin, ymin, xmax, ymax = obj.bounds()
  3822. obj.options['xmin'] = xmin
  3823. obj.options['ymin'] = ymin
  3824. obj.options['xmax'] = xmax
  3825. obj.options['ymax'] = ymax
  3826. log.debug("Object changed, updating the bounding box data on self.options")
  3827. # delete the old selection shape
  3828. self.delete_selection_shape()
  3829. self.should_we_save = True
  3830. def on_object_plotted(self):
  3831. """
  3832. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3833. :return: None
  3834. """
  3835. self.on_zoom_fit(None)
  3836. def on_about(self):
  3837. """
  3838. Displays the "about" dialog found in the Menu --> Help.
  3839. :return: None
  3840. """
  3841. self.report_usage("on_about")
  3842. version = self.version
  3843. version_date = self.version_date
  3844. beta = self.beta
  3845. class AboutDialog(QtWidgets.QDialog):
  3846. def __init__(self, app, parent=None):
  3847. QtWidgets.QDialog.__init__(self, parent)
  3848. self.app = app
  3849. # Icon and title
  3850. self.setWindowIcon(parent.app_icon)
  3851. self.setWindowTitle(_("About FlatCAM"))
  3852. self.resize(600, 200)
  3853. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3854. # self.setStyleSheet(
  3855. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3856. # "background-attachment: fixed"
  3857. # )
  3858. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  3859. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3860. # palette = QtGui.QPalette()
  3861. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3862. # self.setPalette(palette)
  3863. logo = QtWidgets.QLabel()
  3864. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  3865. title = QtWidgets.QLabel(
  3866. "<font size=8><B>FlatCAM</B></font><BR>"
  3867. "{title}<BR>"
  3868. "<BR>"
  3869. "<BR>"
  3870. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3871. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3872. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3873. "<B>{issue}</B></a><BR>".format(
  3874. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3875. devel=_("Development"),
  3876. down=_("DOWNLOAD"),
  3877. issue=_("Issue tracker"))
  3878. )
  3879. title.setOpenExternalLinks(True)
  3880. closebtn = QtWidgets.QPushButton(_("Close"))
  3881. tab_widget = QtWidgets.QTabWidget()
  3882. description_label = QtWidgets.QLabel(
  3883. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3884. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3885. version=version,
  3886. beta=('BETA' if beta else ''),
  3887. date=version_date,
  3888. arch=platform.architecture()[0])
  3889. )
  3890. description_label.setOpenExternalLinks(True)
  3891. lic_lbl_header = QtWidgets.QLabel(
  3892. '%s:<br>%s<br>' % (
  3893. _('Licensed under the MIT license'),
  3894. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  3895. "http://www.opensource.org/licenses/mit-license.php</a>"
  3896. )
  3897. )
  3898. lic_lbl_header.setOpenExternalLinks(True)
  3899. lic_lbl_body = QtWidgets.QLabel(
  3900. _(
  3901. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3902. 'of this software and associated documentation files (the "Software"), to deal\n'
  3903. 'in the Software without restriction, including without limitation the rights\n'
  3904. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3905. 'copies of the Software, and to permit persons to whom the Software is\n'
  3906. 'furnished to do so, subject to the following conditions:\n\n'
  3907. 'The above copyright notice and this permission notice shall be included in\n'
  3908. 'all copies or substantial portions of the Software.\n\n'
  3909. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3910. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3911. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3912. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3913. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3914. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3915. 'THE SOFTWARE.'
  3916. )
  3917. )
  3918. attributions_label = QtWidgets.QLabel(
  3919. _(
  3920. 'Some of the icons used are from the following sources:<br>'
  3921. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  3922. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  3923. 'title="Flaticon">www.flaticon.com</a></div>'
  3924. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  3925. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  3926. )
  3927. )
  3928. attributions_label.setOpenExternalLinks(True)
  3929. # layouts
  3930. layout1 = QtWidgets.QVBoxLayout()
  3931. layout1_1 = QtWidgets.QHBoxLayout()
  3932. layout1_2 = QtWidgets.QHBoxLayout()
  3933. layout2 = QtWidgets.QHBoxLayout()
  3934. layout3 = QtWidgets.QHBoxLayout()
  3935. self.setLayout(layout1)
  3936. layout1.addLayout(layout1_1)
  3937. layout1.addLayout(layout1_2)
  3938. layout1.addLayout(layout2)
  3939. layout1.addLayout(layout3)
  3940. layout1_1.addStretch()
  3941. layout1_1.addWidget(description_label)
  3942. layout1_2.addWidget(tab_widget)
  3943. self.splash_tab = QtWidgets.QWidget()
  3944. self.splash_tab.setObjectName("splash_about")
  3945. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3946. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3947. tab_widget.addTab(self.splash_tab, _("Splash"))
  3948. self.programmmers_tab = QtWidgets.QWidget()
  3949. self.programmmers_tab.setObjectName("programmers_about")
  3950. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3951. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3952. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3953. self.translators_tab = QtWidgets.QWidget()
  3954. self.translators_tab.setObjectName("translators_about")
  3955. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3956. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3957. tab_widget.addTab(self.translators_tab, _("Translators"))
  3958. self.license_tab = QtWidgets.QWidget()
  3959. self.license_tab.setObjectName("license_about")
  3960. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3961. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3962. tab_widget.addTab(self.license_tab, _("License"))
  3963. self.attributions_tab = QtWidgets.QWidget()
  3964. self.attributions_tab.setObjectName("attributions_about")
  3965. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  3966. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  3967. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  3968. self.splash_tab_layout.addWidget(logo, stretch=0)
  3969. self.splash_tab_layout.addWidget(title, stretch=1)
  3970. pal = QtGui.QPalette()
  3971. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3972. self.prog_grid_lay = QtWidgets.QGridLayout()
  3973. self.prog_grid_lay.setHorizontalSpacing(20)
  3974. self.prog_grid_lay.setColumnStretch(0, 0)
  3975. self.prog_grid_lay.setColumnStretch(2, 1)
  3976. prog_widget = QtWidgets.QWidget()
  3977. prog_widget.setLayout(self.prog_grid_lay)
  3978. prog_scroll = QtWidgets.QScrollArea()
  3979. prog_scroll.setWidget(prog_widget)
  3980. prog_scroll.setWidgetResizable(True)
  3981. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3982. prog_scroll.setPalette(pal)
  3983. self.programmmers_tab_layout.addWidget(prog_scroll)
  3984. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  3985. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  3986. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3987. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  3988. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Program Author"), 1, 1)
  3989. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  3990. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  3991. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  3992. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  3993. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  3994. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  3995. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  3996. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 6, 0)
  3997. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  3998. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  3999. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  4000. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  4001. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  4002. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  4003. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  4004. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  4005. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  4006. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  4007. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  4008. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  4009. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  4010. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  4011. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  4012. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  4013. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  4014. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  4015. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  4016. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  4017. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  4018. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  4019. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  4020. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  4021. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  4022. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  4023. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  4024. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  4025. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  4026. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  4027. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  4028. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  4029. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  4030. self.translator_grid_lay = QtWidgets.QGridLayout()
  4031. self.translator_grid_lay.setColumnStretch(0, 0)
  4032. self.translator_grid_lay.setColumnStretch(1, 0)
  4033. self.translator_grid_lay.setColumnStretch(2, 1)
  4034. self.translator_grid_lay.setColumnStretch(3, 0)
  4035. # trans_widget = QtWidgets.QWidget()
  4036. # trans_widget.setLayout(self.translator_grid_lay)
  4037. # self.translators_tab_layout.addWidget(trans_widget)
  4038. # self.translators_tab_layout.addStretch()
  4039. trans_widget = QtWidgets.QWidget()
  4040. trans_widget.setLayout(self.translator_grid_lay)
  4041. trans_scroll = QtWidgets.QScrollArea()
  4042. trans_scroll.setWidget(trans_widget)
  4043. trans_scroll.setWidgetResizable(True)
  4044. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  4045. trans_scroll.setPalette(pal)
  4046. self.translators_tab_layout.addWidget(trans_scroll)
  4047. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  4048. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  4049. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  4050. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  4051. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  4052. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  4053. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  4054. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  4055. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  4056. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  4057. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  4058. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  4059. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 3, 1)
  4060. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 3, 2)
  4061. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  4062. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  4063. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  4064. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 3)
  4065. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  4066. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  4067. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 3)
  4068. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  4069. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 6, 1)
  4070. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 6, 2)
  4071. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 3)
  4072. self.translator_grid_lay.setColumnStretch(0, 0)
  4073. self.translators_tab_layout.addStretch()
  4074. self.license_tab_layout.addWidget(lic_lbl_header)
  4075. self.license_tab_layout.addWidget(lic_lbl_body)
  4076. self.license_tab_layout.addStretch()
  4077. self.attributions_tab_layout.addWidget(attributions_label)
  4078. self.attributions_tab_layout.addStretch()
  4079. layout3.addStretch()
  4080. layout3.addWidget(closebtn)
  4081. closebtn.clicked.connect(self.accept)
  4082. AboutDialog(app=self, parent=self.ui).exec_()
  4083. def install_bookmarks(self, book_dict=None):
  4084. """
  4085. Install the bookmarks actions in the Help menu -> Bookmarks
  4086. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  4087. :return: None
  4088. """
  4089. if book_dict is None:
  4090. self.defaults["global_bookmarks"].update(
  4091. {
  4092. '1': ['FlatCAM', "http://flatcam.org"],
  4093. '2': ['Backup Site', ""]
  4094. }
  4095. )
  4096. else:
  4097. self.defaults["global_bookmarks"].clear()
  4098. self.defaults["global_bookmarks"].update(book_dict)
  4099. # first try to disconnect if somehow they get connected from elsewhere
  4100. for act in self.ui.menuhelp_bookmarks.actions():
  4101. try:
  4102. act.triggered.disconnect()
  4103. except TypeError:
  4104. pass
  4105. # clear all actions except the last one who is the Bookmark manager
  4106. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  4107. pass
  4108. else:
  4109. self.ui.menuhelp_bookmarks.removeAction(act)
  4110. bm_limit = int(self.defaults["global_bookmarks_limit"])
  4111. if self.defaults["global_bookmarks"]:
  4112. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  4113. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  4114. # the JSON is first making the keys as strings (therefore I have to use strings too
  4115. # or do the conversion :(
  4116. # )
  4117. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  4118. # the '10' entry jsut after '1' therefore ordering as strings
  4119. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  4120. key=lambda x: int(x[0]))
  4121. for entry, bookmark in sorted_bookmarks:
  4122. title = bookmark[0]
  4123. weblink = bookmark[1]
  4124. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  4125. act.setText(title)
  4126. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  4127. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  4128. if title == 'Backup Site' and weblink == "":
  4129. act.triggered.connect(self.on_backup_site)
  4130. else:
  4131. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  4132. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  4133. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  4134. def on_bookmarks_manager(self):
  4135. """
  4136. Adds the bookmark manager in a Tab in Plot Area
  4137. :return:
  4138. """
  4139. for idx in range(self.ui.plot_tab_area.count()):
  4140. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  4141. # there can be only one instance of Bookmark Manager at one time
  4142. return
  4143. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  4144. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  4145. # add the tab if it was closed
  4146. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  4147. # delete the absolute and relative position and messages in the infobar
  4148. self.ui.position_label.setText("")
  4149. self.ui.rel_position_label.setText("")
  4150. # Switch plot_area to preferences page
  4151. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  4152. def on_backup_site(self):
  4153. msgbox = QtWidgets.QMessageBox()
  4154. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  4155. "1. FlatCAM.org website is down\n"
  4156. "2. Someone forked FlatCAM project and wants to point\n"
  4157. "to his own website\n\n"
  4158. "If you can't get any informations about FlatCAM beta\n"
  4159. "use the YouTube channel link from the Help menu."))
  4160. msgbox.setWindowTitle(_("Alternative website"))
  4161. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  4162. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  4163. msgbox.setDefaultButton(bt_yes)
  4164. msgbox.exec_()
  4165. # response = msgbox.clickedButton()
  4166. def on_file_savedefaults(self):
  4167. """
  4168. Callback for menu item File->Save Defaults. Saves application default options
  4169. ``self.defaults`` to current_defaults.FlatConfig.
  4170. :return: None
  4171. """
  4172. self.save_defaults()
  4173. # def on_app_exit(self):
  4174. # self.report_usage("on_app_exit()")
  4175. #
  4176. # if self.collection.get_list():
  4177. # msgbox = QtWidgets.QMessageBox()
  4178. # # msgbox.setText("<B>Save changes ...</B>")
  4179. # msgbox.setText("There are files/objects opened in FlatCAM. "
  4180. # "\n"
  4181. # "Do you want to Save the project?")
  4182. # msgbox.setWindowTitle("Save changes")
  4183. # msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4184. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  4185. # QtWidgets.QMessageBox.Cancel)
  4186. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  4187. #
  4188. # response = msgbox.exec_()
  4189. #
  4190. # if response == QtWidgets.QMessageBox.Yes:
  4191. # self.on_file_saveprojectas(thread=False)
  4192. # elif response == QtWidgets.QMessageBox.Cancel:
  4193. # return
  4194. # self.save_defaults()
  4195. # else:
  4196. # self.save_defaults()
  4197. # log.debug("Application defaults saved ... Exit event.")
  4198. # QtWidgets.qApp.quit()
  4199. def save_defaults(self, silent=False, data_path=None, first_time=False):
  4200. """
  4201. Saves application default options
  4202. ``self.defaults`` to current_defaults.FlatConfig file.
  4203. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  4204. used at the next launch of the application.
  4205. :param silent: Whether to display a message in status bar or not; boolean
  4206. :param data_path: The path where to save the preferences file (current_defaults.FlatConfig)
  4207. When the application is portable it should be a mobile location.
  4208. :param first_time: Boolean. If True will execute some code when the app is run first time
  4209. :return: None
  4210. """
  4211. self.report_usage("save_defaults")
  4212. if data_path is None:
  4213. data_path = self.data_path
  4214. # Read options from file
  4215. try:
  4216. f = open(data_path + "/current_defaults.FlatConfig")
  4217. defaults_file_content = f.read()
  4218. f.close()
  4219. except Exception:
  4220. e = sys.exc_info()[0]
  4221. App.log.error("Could not load defaults file.")
  4222. App.log.error(str(e))
  4223. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load defaults file."))
  4224. return
  4225. try:
  4226. defaults = json.loads(defaults_file_content)
  4227. except Exception:
  4228. e = sys.exc_info()[0]
  4229. App.log.error("Failed to parse defaults file.")
  4230. App.log.error(str(e))
  4231. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse defaults file."))
  4232. return
  4233. # Update options
  4234. self.defaults_read_form()
  4235. defaults.update(self.defaults)
  4236. self.propagate_defaults(silent=True)
  4237. if first_time is False:
  4238. self.save_toolbar_view()
  4239. # Save update options
  4240. filename = data_path + "/current_defaults.FlatConfig"
  4241. try:
  4242. f = open(filename, "w")
  4243. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  4244. f.close()
  4245. except Exception as e:
  4246. log.debug("App.save_defaults() --> %s" % str(e))
  4247. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  4248. return
  4249. if not silent:
  4250. self.inform.emit('[success] %s' % _("Preferences saved."))
  4251. # update the autosave timer
  4252. self.save_project_auto_update()
  4253. def save_toolbar_view(self):
  4254. """
  4255. Will save the toolbar view state to the defaults
  4256. :return: None
  4257. """
  4258. # Save the toolbar view
  4259. tb_status = 0
  4260. if self.ui.toolbarfile.isVisible():
  4261. tb_status += 1
  4262. if self.ui.toolbargeo.isVisible():
  4263. tb_status += 2
  4264. if self.ui.toolbarview.isVisible():
  4265. tb_status += 4
  4266. if self.ui.toolbartools.isVisible():
  4267. tb_status += 8
  4268. if self.ui.exc_edit_toolbar.isVisible():
  4269. tb_status += 16
  4270. if self.ui.geo_edit_toolbar.isVisible():
  4271. tb_status += 32
  4272. if self.ui.grb_edit_toolbar.isVisible():
  4273. tb_status += 64
  4274. if self.ui.snap_toolbar.isVisible():
  4275. tb_status += 128
  4276. if self.ui.toolbarshell.isVisible():
  4277. tb_status += 256
  4278. self.defaults["global_toolbar_view"] = tb_status
  4279. def save_factory_defaults(self, silent_message=False, data_path=None):
  4280. """
  4281. Saves application factory default options
  4282. ``self.defaults`` to factory_defaults.FlatConfig.
  4283. It's a one time job done just after the first install.
  4284. :param silent_message: whether to display a message in status bar or not; boolean
  4285. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  4286. When the application is portable it should be a mobile location.
  4287. :return: None
  4288. """
  4289. self.report_usage("save_factory_defaults")
  4290. if data_path is None:
  4291. data_path = self.data_path
  4292. # Read options from file
  4293. try:
  4294. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  4295. factory_defaults_file_content = f_f_def.read()
  4296. f_f_def.close()
  4297. except Exception:
  4298. e = sys.exc_info()[0]
  4299. App.log.error("Could not load factory defaults file.")
  4300. App.log.error(str(e))
  4301. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load factory defaults file."))
  4302. return
  4303. try:
  4304. factory_defaults = json.loads(factory_defaults_file_content)
  4305. except Exception:
  4306. e = sys.exc_info()[0]
  4307. App.log.error("Failed to parse factory defaults file.")
  4308. App.log.error(str(e))
  4309. if silent_message is False:
  4310. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse factory defaults file."))
  4311. return
  4312. # Update options
  4313. self.defaults_read_form()
  4314. factory_defaults.update(self.defaults)
  4315. self.propagate_defaults(silent=True)
  4316. # Save update options
  4317. try:
  4318. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  4319. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  4320. f_f_def_s.close()
  4321. except Exception as e:
  4322. log.debug("App.save_factory_default() save update --> %s" % str(e))
  4323. if silent_message is False:
  4324. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to write factory defaults to file."))
  4325. return
  4326. if silent_message is False:
  4327. self.inform.emit(_("Factory defaults saved."))
  4328. def final_save(self):
  4329. """
  4330. Callback for doing a preferences save to file whenever the application is about to quit.
  4331. If the project has changes, it will ask the user to save the project.
  4332. :return: None
  4333. """
  4334. if self.save_in_progress:
  4335. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  4336. return
  4337. if self.should_we_save and self.collection.get_list():
  4338. msgbox = QtWidgets.QMessageBox()
  4339. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  4340. "\n"
  4341. "Do you want to Save the project?"))
  4342. msgbox.setWindowTitle(_("Save changes"))
  4343. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4344. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4345. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4346. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4347. msgbox.setDefaultButton(bt_yes)
  4348. msgbox.exec_()
  4349. response = msgbox.clickedButton()
  4350. if response == bt_yes:
  4351. try:
  4352. self.trayIcon.hide()
  4353. except Exception:
  4354. pass
  4355. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  4356. elif response == bt_no:
  4357. try:
  4358. self.trayIcon.hide()
  4359. except Exception:
  4360. pass
  4361. self.quit_application()
  4362. elif response == bt_cancel:
  4363. return
  4364. else:
  4365. try:
  4366. self.trayIcon.hide()
  4367. except Exception:
  4368. pass
  4369. self.quit_application()
  4370. def quit_application(self):
  4371. """
  4372. Called (as a pyslot or not) when the application is quit.
  4373. :return: None
  4374. """
  4375. self.save_defaults(silent=True)
  4376. log.debug("App.quit_application() --> App Defaults saved.")
  4377. if self.cmd_line_headless != 1:
  4378. # save app state to file
  4379. stgs = QSettings("Open Source", "FlatCAM")
  4380. stgs.setValue('saved_gui_state', self.ui.saveState())
  4381. stgs.setValue('maximized_gui', self.ui.isMaximized())
  4382. stgs.setValue(
  4383. 'language',
  4384. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  4385. )
  4386. stgs.setValue(
  4387. 'notebook_font_size',
  4388. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  4389. )
  4390. stgs.setValue(
  4391. 'axis_font_size',
  4392. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  4393. )
  4394. stgs.setValue(
  4395. 'textbox_font_size',
  4396. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  4397. )
  4398. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  4399. stgs.setValue(
  4400. 'machinist',
  4401. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  4402. )
  4403. # This will write the setting to the platform specific storage.
  4404. del stgs
  4405. log.debug("App.quit_application() --> App UI state saved.")
  4406. # try to quit the QThread that run ArgsThread class
  4407. try:
  4408. self.th.quit()
  4409. except Exception as e:
  4410. log.debug("App.quit_application() --> %s" % str(e))
  4411. # try to quit the Socket opened by ArgsThread class
  4412. try:
  4413. self.new_launch.listener.close()
  4414. except Exception as err:
  4415. log.debug("App.quit_application() --> %s" % str(err))
  4416. # quit app by signalling for self.kill_app() method
  4417. # self.close_app_signal.emit()
  4418. QtWidgets.qApp.quit()
  4419. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  4420. # we use the following command
  4421. # sys.exit(0)
  4422. os._exit(0) # fix to work with Python 3.8
  4423. @staticmethod
  4424. def kill_app():
  4425. # QtCore.QCoreApplication.quit()
  4426. QtWidgets.qApp.quit()
  4427. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  4428. # we use the following command
  4429. sys.exit(0)
  4430. def on_portable_checked(self, state):
  4431. """
  4432. Callback called when the checkbox in Preferences GUI is checked.
  4433. It will set the application as portable by creating the preferences and recent files in the
  4434. 'config' folder found in the FlatCAM installation folder.
  4435. :param state: boolean, the state of the checkbox when clicked/checked
  4436. :return:
  4437. """
  4438. line_no = 0
  4439. data = None
  4440. if sys.platform != 'win32':
  4441. # this won't work in Linux or MacOS
  4442. return
  4443. # test if the app was frozen and choose the path for the configuration file
  4444. if getattr(sys, "frozen", False) is True:
  4445. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  4446. else:
  4447. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  4448. config_file = current_data_path + '\\configuration.txt'
  4449. try:
  4450. with open(config_file, 'r') as f:
  4451. try:
  4452. data = f.readlines()
  4453. except Exception as e:
  4454. log.debug('App.__init__() -->%s' % str(e))
  4455. return
  4456. except FileNotFoundError:
  4457. pass
  4458. for line in data:
  4459. line = line.strip('\n')
  4460. param = str(line).rpartition('=')
  4461. if param[0] == 'portable':
  4462. break
  4463. line_no += 1
  4464. if state:
  4465. data[line_no] = 'portable=True\n'
  4466. # create the new defauults files
  4467. # create current_defaults.FlatConfig file if there is none
  4468. try:
  4469. f = open(current_data_path + '/current_defaults.FlatConfig')
  4470. f.close()
  4471. except IOError:
  4472. App.log.debug('Creating empty current_defaults.FlatConfig')
  4473. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  4474. json.dump({}, f)
  4475. f.close()
  4476. # create factory_defaults.FlatConfig file if there is none
  4477. try:
  4478. f = open(current_data_path + '/factory_defaults.FlatConfig')
  4479. f.close()
  4480. except IOError:
  4481. App.log.debug('Creating empty factory_defaults.FlatConfig')
  4482. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  4483. json.dump({}, f)
  4484. f.close()
  4485. try:
  4486. f = open(current_data_path + '/recent.json')
  4487. f.close()
  4488. except IOError:
  4489. App.log.debug('Creating empty recent.json')
  4490. f = open(current_data_path + '/recent.json', 'w')
  4491. json.dump([], f)
  4492. f.close()
  4493. try:
  4494. fp = open(current_data_path + '/recent_projects.json')
  4495. fp.close()
  4496. except IOError:
  4497. App.log.debug('Creating empty recent_projects.json')
  4498. fp = open(current_data_path + '/recent_projects.json', 'w')
  4499. json.dump([], fp)
  4500. fp.close()
  4501. # save the current defaults to the new defaults file
  4502. self.save_defaults(silent=True, data_path=current_data_path)
  4503. self.save_factory_defaults(silent_message=True, data_path=current_data_path)
  4504. else:
  4505. data[line_no] = 'portable=False\n'
  4506. with open(config_file, 'w') as f:
  4507. f.writelines(data)
  4508. def on_register_files(self, obj_type=None):
  4509. """
  4510. Called whenever there is a need to register file extensions with FlatCAM.
  4511. Works only in Windows and should be called only when FlatCAM is run in Windows.
  4512. :param obj_type: the type of object to be register for.
  4513. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  4514. :return: None
  4515. """
  4516. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  4517. new_reg_path = 'Software\\Classes\\'
  4518. # find if the current user is admin
  4519. try:
  4520. is_admin = os.getuid() == 0
  4521. except AttributeError:
  4522. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  4523. if is_admin is True:
  4524. root_path = winreg.HKEY_LOCAL_MACHINE
  4525. else:
  4526. root_path = winreg.HKEY_CURRENT_USER
  4527. # create the keys
  4528. def set_reg(name, root_path, new_reg_path, value):
  4529. try:
  4530. winreg.CreateKey(root_path, new_reg_path)
  4531. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  4532. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  4533. return True
  4534. except WindowsError:
  4535. return False
  4536. # delete key in registry
  4537. def delete_reg(root_path, reg_path, key_to_del):
  4538. key_to_del_path = reg_path + key_to_del
  4539. try:
  4540. winreg.DeleteKey(root_path, key_to_del_path)
  4541. return True
  4542. except WindowsError:
  4543. return False
  4544. if obj_type is None or obj_type == 'excellon':
  4545. exc_list = \
  4546. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4547. exc_list = [x for x in exc_list if x != '']
  4548. # register all keys in the Preferences window
  4549. for ext in exc_list:
  4550. new_k = new_reg_path + '.%s' % ext
  4551. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4552. # and unregister those that are no longer in the Preferences windows but are in the file
  4553. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  4554. if ext not in exc_list:
  4555. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4556. # now write the updated extensions to the self.defaults
  4557. # new_ext = ''
  4558. # for ext in exc_list:
  4559. # new_ext = new_ext + ext + ', '
  4560. # self.defaults["fa_excellon"] = new_ext
  4561. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  4562. if obj_type is None or obj_type == 'gcode':
  4563. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4564. gco_list = [x for x in gco_list if x != '']
  4565. # register all keys in the Preferences window
  4566. for ext in gco_list:
  4567. new_k = new_reg_path + '.%s' % ext
  4568. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4569. # and unregister those that are no longer in the Preferences windows but are in the file
  4570. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  4571. if ext not in gco_list:
  4572. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4573. # now write the updated extensions to the self.defaults
  4574. # new_ext = ''
  4575. # for ext in gco_list:
  4576. # new_ext = new_ext + ext + ', '
  4577. # self.defaults["fa_gcode"] = new_ext
  4578. self.inform.emit('[success] %s' %
  4579. _("Selected GCode file extensions registered with FlatCAM."))
  4580. if obj_type is None or obj_type == 'gerber':
  4581. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4582. grb_list = [x for x in grb_list if x != '']
  4583. # register all keys in the Preferences window
  4584. for ext in grb_list:
  4585. new_k = new_reg_path + '.%s' % ext
  4586. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4587. # and unregister those that are no longer in the Preferences windows but are in the file
  4588. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  4589. if ext not in grb_list:
  4590. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4591. # now write the updated extensions to the self.defaults
  4592. # new_ext = ''
  4593. # for ext in grb_list:
  4594. # new_ext = new_ext + ext + ', '
  4595. # self.defaults["fa_gerber"] = new_ext
  4596. self.inform.emit('[success] %s' %
  4597. _("Selected Gerber file extensions registered with FlatCAM."))
  4598. def add_extension(self, ext_type):
  4599. """
  4600. Add a file extension to the list for a specific object
  4601. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4602. :return:
  4603. """
  4604. if ext_type == 'excellon':
  4605. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4606. if new_ext == '':
  4607. return
  4608. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4609. if new_ext in old_val:
  4610. return
  4611. old_val.append(new_ext)
  4612. old_val.sort()
  4613. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4614. if ext_type == 'gcode':
  4615. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4616. if new_ext == '':
  4617. return
  4618. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4619. if new_ext in old_val:
  4620. return
  4621. old_val.append(new_ext)
  4622. old_val.sort()
  4623. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4624. if ext_type == 'gerber':
  4625. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4626. if new_ext == '':
  4627. return
  4628. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4629. if new_ext in old_val:
  4630. return
  4631. old_val.append(new_ext)
  4632. old_val.sort()
  4633. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4634. if ext_type == 'keyword':
  4635. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4636. if new_kw == '':
  4637. return
  4638. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4639. if new_kw in old_val:
  4640. return
  4641. old_val.append(new_kw)
  4642. old_val.sort()
  4643. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4644. # update the self.myKeywords so the model is updated
  4645. self.autocomplete_kw_list = \
  4646. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4647. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4648. self.shell._edit.set_model_data(self.myKeywords)
  4649. def del_extension(self, ext_type):
  4650. """
  4651. Remove a file extension from the list for a specific object
  4652. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4653. :return:
  4654. """
  4655. if ext_type == 'excellon':
  4656. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4657. if new_ext == '':
  4658. return
  4659. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4660. if new_ext not in old_val:
  4661. return
  4662. old_val.remove(new_ext)
  4663. old_val.sort()
  4664. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4665. if ext_type == 'gcode':
  4666. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4667. if new_ext == '':
  4668. return
  4669. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4670. if new_ext not in old_val:
  4671. return
  4672. old_val.remove(new_ext)
  4673. old_val.sort()
  4674. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4675. if ext_type == 'gerber':
  4676. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4677. if new_ext == '':
  4678. return
  4679. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4680. if new_ext not in old_val:
  4681. return
  4682. old_val.remove(new_ext)
  4683. old_val.sort()
  4684. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4685. if ext_type == 'keyword':
  4686. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4687. if new_kw == '':
  4688. return
  4689. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4690. if new_kw not in old_val:
  4691. return
  4692. old_val.remove(new_kw)
  4693. old_val.sort()
  4694. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4695. # update the self.myKeywords so the model is updated
  4696. self.autocomplete_kw_list = \
  4697. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4698. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4699. self.shell._edit.set_model_data(self.myKeywords)
  4700. def restore_extensions(self, ext_type):
  4701. """
  4702. Restore all file extensions associations with FlatCAM, for a specific object
  4703. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4704. :return:
  4705. """
  4706. if ext_type == 'excellon':
  4707. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  4708. # for the ability to open Excellon files with .txt extension
  4709. new_exc_list = deepcopy(self.exc_list)
  4710. try:
  4711. new_exc_list.remove('txt')
  4712. except ValueError:
  4713. pass
  4714. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  4715. if ext_type == 'gcode':
  4716. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  4717. if ext_type == 'gerber':
  4718. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  4719. if ext_type == 'keyword':
  4720. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  4721. # update the self.myKeywords so the model is updated
  4722. self.autocomplete_kw_list = self.default_keywords
  4723. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4724. self.shell._edit.set_model_data(self.myKeywords)
  4725. def delete_all_extensions(self, ext_type):
  4726. """
  4727. Delete all file extensions associations with FlatCAM, for a specific object
  4728. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4729. :return:
  4730. """
  4731. if ext_type == 'excellon':
  4732. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4733. if ext_type == 'gcode':
  4734. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4735. if ext_type == 'gerber':
  4736. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4737. if ext_type == 'keyword':
  4738. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4739. # update the self.myKeywords so the model is updated
  4740. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4741. self.shell._edit.set_model_data(self.myKeywords)
  4742. def on_edit_join(self, name=None):
  4743. """
  4744. Callback for Edit->Join. Joins the selected geometry objects into
  4745. a new one.
  4746. :return: None
  4747. """
  4748. self.report_usage("on_edit_join()")
  4749. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4750. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4751. geo_type_set = set()
  4752. objs = self.collection.get_selected()
  4753. if len(objs) < 2:
  4754. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4755. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4756. return 'fail'
  4757. for obj in objs:
  4758. geo_type_set.add(obj.multigeo)
  4759. # if len(geo_type_list) == 1 means that all list elements are the same
  4760. if len(geo_type_set) != 1:
  4761. self.inform.emit('[ERROR] %s' %
  4762. _("Failed join. The Geometry objects are of different types.\n"
  4763. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4764. "convert from one to another and retry joining \n"
  4765. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4766. "the result may not be what was expected. \n"
  4767. "Check the generated GCODE."))
  4768. return
  4769. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4770. if True in geo_type_set:
  4771. def initialize(geo_obj, app):
  4772. GeometryObject.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=True)
  4773. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  4774. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4775. for v in geo_obj.tools.values():
  4776. v['data']['name'] = obj_name_multi
  4777. self.new_object("geometry", obj_name_multi, initialize)
  4778. else:
  4779. def initialize(geo_obj, app):
  4780. GeometryObject.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=False)
  4781. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  4782. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4783. for v in geo_obj.tools.values():
  4784. v['data']['name'] = obj_name_single
  4785. self.new_object("geometry", obj_name_single, initialize)
  4786. self.should_we_save = True
  4787. def on_edit_join_exc(self):
  4788. """
  4789. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4790. a new Excellon.
  4791. :return: None
  4792. """
  4793. self.report_usage("on_edit_join_exc()")
  4794. objs = self.collection.get_selected()
  4795. for obj in objs:
  4796. if not isinstance(obj, ExcellonObject):
  4797. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  4798. return
  4799. if len(objs) < 2:
  4800. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4801. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4802. return 'fail'
  4803. def initialize(exc_obj, app):
  4804. ExcellonObject.merge(self, exc_list=objs, exc_final=exc_obj)
  4805. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  4806. self.new_object("excellon", 'Combo_Excellon', initialize)
  4807. self.should_we_save = True
  4808. def on_edit_join_grb(self):
  4809. """
  4810. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4811. a new Gerber object.
  4812. :return: None
  4813. """
  4814. self.report_usage("on_edit_join_grb()")
  4815. objs = self.collection.get_selected()
  4816. for obj in objs:
  4817. if not isinstance(obj, GerberObject):
  4818. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  4819. return
  4820. if len(objs) < 2:
  4821. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4822. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4823. return 'fail'
  4824. def initialize(grb_obj, app):
  4825. GerberObject.merge(self, grb_list=objs, grb_final=grb_obj)
  4826. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  4827. self.new_object("gerber", 'Combo_Gerber', initialize)
  4828. self.should_we_save = True
  4829. def on_convert_singlegeo_to_multigeo(self):
  4830. """
  4831. Called for converting a Geometry object from single-geo to multi-geo.
  4832. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4833. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4834. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4835. the solid-geometry of that tool.
  4836. :return: None
  4837. """
  4838. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4839. obj = self.collection.get_active()
  4840. if obj is None:
  4841. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  4842. return
  4843. if not isinstance(obj, GeometryObject):
  4844. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  4845. return
  4846. obj.multigeo = True
  4847. for tooluid, dict_value in obj.tools.items():
  4848. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4849. if not isinstance(obj.solid_geometry, list):
  4850. obj.solid_geometry = [obj.solid_geometry]
  4851. obj.solid_geometry[:] = []
  4852. obj.plot()
  4853. self.should_we_save = True
  4854. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  4855. def on_convert_multigeo_to_singlegeo(self):
  4856. """
  4857. Called for converting a Geometry object from multi-geo to single-geo.
  4858. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4859. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4860. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4861. the solid-geometry of that tool.
  4862. :return: None
  4863. """
  4864. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4865. obj = self.collection.get_active()
  4866. if obj is None:
  4867. self.inform.emit('[ERROR_NOTCL] %s' %
  4868. _("Failed. Select a Geometry Object and try again."))
  4869. return
  4870. if not isinstance(obj, GeometryObject):
  4871. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4872. (_("Expected a GeometryObject, got"), type(obj)))
  4873. return
  4874. obj.multigeo = False
  4875. total_solid_geometry = []
  4876. for tooluid, dict_value in obj.tools.items():
  4877. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4878. # clear the original geometry
  4879. dict_value['solid_geometry'][:] = []
  4880. obj.solid_geometry = deepcopy(total_solid_geometry)
  4881. obj.plot()
  4882. self.should_we_save = True
  4883. self.inform.emit('[success] %s' %
  4884. _("A Geometry object was converted to SingleGeo type."))
  4885. def on_defaults_dict_change(self, field):
  4886. """
  4887. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4888. Edit -> Preferences tab window.
  4889. :param field: the key of the self.defaults dictionary that was changed.
  4890. :return: None
  4891. """
  4892. self.defaults_write_form_field(field)
  4893. if field == "units":
  4894. self.set_screen_units(self.defaults['units'])
  4895. def set_screen_units(self, units):
  4896. """
  4897. Set the FlatCAM units on the status bar.
  4898. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4899. :return: None
  4900. """
  4901. self.ui.units_label.setText("[" + units.lower() + "]")
  4902. def on_toggle_units_click(self):
  4903. try:
  4904. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4905. except (TypeError, AttributeError):
  4906. pass
  4907. if self.defaults["units"] == 'MM':
  4908. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4909. else:
  4910. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4911. self.on_toggle_units(no_pref=True)
  4912. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4913. lambda: self.on_toggle_units(no_pref=False))
  4914. def on_toggle_units(self, no_pref=False):
  4915. """
  4916. Callback for the Units radio-button change in the Preferences tab.
  4917. Changes the application's default units adn for the project too.
  4918. If changing the project's units, the change propagates to all of
  4919. the objects in the project.
  4920. :return: None
  4921. """
  4922. self.report_usage("on_toggle_units")
  4923. if self.toggle_units_ignore:
  4924. return
  4925. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4926. # If option is the same, then ignore
  4927. if new_units == self.defaults["units"].upper():
  4928. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4929. return
  4930. # Options to scale
  4931. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin', "gerber_isooverlap",
  4932. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  4933. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  4934. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4935. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  4936. "excellon_feedrate_probe",
  4937. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  4938. "excellon_editor_slot_lin_pitch",
  4939. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4940. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4941. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  4942. "geometry_z_pdepth",
  4943. "geometry_feedrate_probe", "geometry_startz",
  4944. 'cncjob_tooldia',
  4945. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4946. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  4947. "tools_nccnewdia",
  4948. "tools_2sided_drilldia", "tools_film_boundary",
  4949. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4950. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4951. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4952. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4953. "tools_transform_offset_y",
  4954. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4955. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4956. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4957. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4958. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  4959. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  4960. "tools_cr_h2h_val", "tools_cr_dh_val", "tools_fiducials_dia", "tools_fiducials_margin",
  4961. "tools_fiducials_line_thickness",
  4962. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  4963. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  4964. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  4965. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  4966. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  4967. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  4968. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  4969. def scale_defaults(sfactor):
  4970. for dim in dimensions:
  4971. if dim == 'excellon_toolchangexy':
  4972. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4973. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4974. coords_xy[0] *= sfactor
  4975. coords_xy[1] *= sfactor
  4976. self.defaults['excellon_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  4977. self.decimals, coords_xy[1])
  4978. elif dim == 'geometry_toolchangexy':
  4979. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4980. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4981. coords_xy[0] *= sfactor
  4982. coords_xy[1] *= sfactor
  4983. self.defaults['geometry_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  4984. self.decimals, coords_xy[1])
  4985. elif dim == 'excellon_endxy':
  4986. coordinates = self.defaults["excellon_endxy"].split(",")
  4987. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4988. end_coords_xy[0] *= sfactor
  4989. end_coords_xy[1] *= sfactor
  4990. self.defaults['excellon_endxy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  4991. self.decimals, end_coords_xy[1])
  4992. elif dim == 'geometry_endxy':
  4993. coordinates = self.defaults["geometry_endxy"].split(",")
  4994. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4995. end_coords_xy[0] *= sfactor
  4996. end_coords_xy[1] *= sfactor
  4997. self.defaults['geometry_endxy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  4998. self.decimals, end_coords_xy[1])
  4999. elif dim == 'geometry_cnctooldia':
  5000. if type(self.defaults["geometry_cnctooldia"]) == float:
  5001. tools_diameters = [self.defaults["geometry_cnctooldia"]]
  5002. else:
  5003. try:
  5004. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  5005. tools_diameters = [eval(a) for a in tools_string if a != '']
  5006. except Exception as e:
  5007. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  5008. continue
  5009. self.defaults['geometry_cnctooldia'] = ''
  5010. for t in range(len(tools_diameters)):
  5011. tools_diameters[t] *= sfactor
  5012. self.defaults['geometry_cnctooldia'] += "%.*f," % (self.decimals, tools_diameters[t])
  5013. elif dim == 'tools_ncctools':
  5014. if type(self.defaults["tools_ncctools"]) == float:
  5015. ncctools = [self.defaults["tools_ncctools"]]
  5016. else:
  5017. try:
  5018. tools_string = self.defaults["tools_ncctools"].split(",")
  5019. ncctools = [eval(a) for a in tools_string if a != '']
  5020. except Exception as e:
  5021. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  5022. continue
  5023. self.defaults['tools_ncctools'] = ''
  5024. for t in range(len(ncctools)):
  5025. ncctools[t] *= sfactor
  5026. self.defaults['tools_ncctools'] += "%.*f," % (self.decimals, ncctools[t])
  5027. elif dim == 'tools_solderpaste_tools':
  5028. if type(self.defaults["tools_solderpaste_tools"]) == float:
  5029. sptools = [self.defaults["tools_solderpaste_tools"]]
  5030. else:
  5031. try:
  5032. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  5033. sptools = [eval(a) for a in tools_string if a != '']
  5034. except Exception as e:
  5035. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  5036. continue
  5037. self.defaults['tools_solderpaste_tools'] = ""
  5038. for t in range(len(sptools)):
  5039. sptools[t] *= sfactor
  5040. self.defaults['tools_solderpaste_tools'] += "%.*f," % (self.decimals, sptools[t])
  5041. elif dim == 'tools_solderpaste_xy_toolchange':
  5042. try:
  5043. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  5044. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  5045. sp_coords[0] *= sfactor
  5046. sp_coords[1] *= sfactor
  5047. self.defaults['tools_solderpaste_xy_toolchange'] = "%.*f, %.*f" % (self.decimals, sp_coords[0],
  5048. self.decimals, sp_coords[1])
  5049. except Exception as e:
  5050. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  5051. continue
  5052. elif dim == 'global_gridx' or dim == 'global_gridy':
  5053. if new_units == 'IN':
  5054. try:
  5055. val = float(self.defaults[dim]) * sfactor
  5056. except Exception as e:
  5057. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  5058. continue
  5059. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  5060. else:
  5061. try:
  5062. val = float(self.defaults[dim]) * sfactor
  5063. except Exception as e:
  5064. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  5065. continue
  5066. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  5067. else:
  5068. if self.defaults[dim]:
  5069. try:
  5070. val = float(self.defaults[dim]) * sfactor
  5071. except Exception as e:
  5072. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  5073. continue
  5074. self.defaults[dim] = val
  5075. # The scaling factor depending on choice of units.
  5076. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  5077. # Changing project units. Warn user.
  5078. msgbox = QtWidgets.QMessageBox()
  5079. msgbox.setWindowTitle(_("Toggle Units"))
  5080. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  5081. msgbox.setText(_("Changing the units of the project\n"
  5082. "will scale all objects.\n\n"
  5083. "Do you want to continue?"))
  5084. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5085. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5086. msgbox.setDefaultButton(bt_ok)
  5087. msgbox.exec_()
  5088. response = msgbox.clickedButton()
  5089. if response == bt_ok:
  5090. if no_pref is False:
  5091. self.defaults_read_form()
  5092. scale_defaults(factor)
  5093. self.defaults_write_form(fl_units=new_units)
  5094. self.defaults["units"] = new_units
  5095. # update the defaults from form, some may assume that the conversion is enough and it's not
  5096. self.on_options_app2project()
  5097. # update the objects
  5098. for obj in self.collection.get_list():
  5099. obj.convert_units(new_units)
  5100. # make that the properties stored in the object are also updated
  5101. self.object_changed.emit(obj)
  5102. # rebuild the object UI
  5103. obj.build_ui()
  5104. # change this only if the workspace is active
  5105. if self.defaults['global_workspace'] is True:
  5106. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  5107. # adjust the grid values on the main toolbar
  5108. val_x = float(self.defaults['global_gridx']) * factor
  5109. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  5110. current = self.collection.get_active()
  5111. if current is not None:
  5112. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  5113. if not isinstance(current, GeometryObject):
  5114. current.to_form()
  5115. # replot all objects
  5116. self.plot_all()
  5117. # set the status labels to reflect the current FlatCAM units
  5118. self.set_screen_units(new_units)
  5119. # signal to the app that we changed the object properties and it shoud save the project
  5120. self.should_we_save = True
  5121. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  5122. else:
  5123. # Undo toggling
  5124. self.toggle_units_ignore = True
  5125. if self.defaults['units'].upper() == 'MM':
  5126. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  5127. else:
  5128. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  5129. self.toggle_units_ignore = False
  5130. # store the grid values so they are not changed in the next step
  5131. val_x = float(self.defaults['global_gridx'])
  5132. val_y = float(self.defaults['global_gridy'])
  5133. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  5134. self.defaults_read_form()
  5135. # the self.defaults_read_form() will update all defaults values in self.defaults from the GUI elements but
  5136. # I don't want it for the grid values, so I update them here
  5137. self.defaults['global_gridx'] = val_x
  5138. self.defaults['global_gridy'] = val_y
  5139. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  5140. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  5141. def on_fullscreen(self, disable=False):
  5142. self.report_usage("on_fullscreen()")
  5143. flags = self.ui.windowFlags()
  5144. if self.toggle_fscreen is False and disable is False:
  5145. # self.ui.showFullScreen()
  5146. self.ui.setWindowFlags(flags | Qt.FramelessWindowHint)
  5147. a = self.ui.geometry()
  5148. self.x_pos = a.x()
  5149. self.y_pos = a.y()
  5150. self.width = a.width()
  5151. self.height = a.height()
  5152. # set new geometry to full desktop rect
  5153. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  5154. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  5155. # everything else will not work without this hack. This happen in Windows.
  5156. # https://bugreports.qt.io/browse/QTBUG-41309
  5157. desktop = QtWidgets.QApplication.desktop()
  5158. screen = desktop.screenNumber(QtGui.QCursor.pos())
  5159. rec = desktop.screenGeometry(screen)
  5160. x = rec.x() - 1
  5161. y = rec.y() - 1
  5162. h = rec.height() + 2
  5163. w = rec.width() + 2
  5164. self.ui.setGeometry(x, y, w, h)
  5165. self.ui.show()
  5166. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  5167. tb.setVisible(False)
  5168. self.ui.splitter_left.setVisible(False)
  5169. self.toggle_fscreen = True
  5170. elif self.toggle_fscreen is True or disable is True:
  5171. self.ui.setWindowFlags(flags & ~Qt.FramelessWindowHint)
  5172. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  5173. self.ui.showNormal()
  5174. self.restore_toolbar_view()
  5175. self.ui.splitter_left.setVisible(True)
  5176. self.toggle_fscreen = False
  5177. def on_toggle_plotarea(self):
  5178. self.report_usage("on_toggle_plotarea()")
  5179. try:
  5180. name = self.ui.plot_tab_area.widget(0).objectName()
  5181. except AttributeError:
  5182. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  5183. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  5184. self.ui.plot_tab_area.protectTab(0)
  5185. return
  5186. if name != 'plotarea':
  5187. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5188. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  5189. self.ui.plot_tab_area.protectTab(0)
  5190. else:
  5191. self.ui.plot_tab_area.closeTab(0)
  5192. def on_toggle_notebook(self):
  5193. if self.ui.splitter.sizes()[0] == 0:
  5194. self.ui.splitter.setSizes([1, 1])
  5195. self.ui.menu_toggle_nb.setChecked(True)
  5196. else:
  5197. self.ui.splitter.setSizes([0, 1])
  5198. self.ui.menu_toggle_nb.setChecked(False)
  5199. def on_toggle_axis(self):
  5200. self.report_usage("on_toggle_axis()")
  5201. if self.toggle_axis is False:
  5202. if self.is_legacy is False:
  5203. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  5204. parent=self.plotcanvas.view.scene)
  5205. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  5206. parent=self.plotcanvas.view.scene)
  5207. else:
  5208. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  5209. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  5210. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  5211. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  5212. self.plotcanvas.canvas.draw()
  5213. self.toggle_axis = True
  5214. else:
  5215. if self.is_legacy is False:
  5216. self.plotcanvas.v_line.parent = None
  5217. self.plotcanvas.h_line.parent = None
  5218. else:
  5219. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  5220. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  5221. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  5222. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  5223. self.plotcanvas.canvas.draw()
  5224. self.toggle_axis = False
  5225. def on_toggle_grid(self):
  5226. self.report_usage("on_toggle_grid()")
  5227. self.ui.grid_snap_btn.trigger()
  5228. self.on_grid_snap_triggered(state=True)
  5229. def on_toggle_grid_lines(self):
  5230. self.report_usage("on_toggle_grd_lines()")
  5231. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  5232. if tt_settings.contains("theme"):
  5233. theme = tt_settings.value('theme', type=str)
  5234. else:
  5235. theme = 'white'
  5236. if self.toggle_grid_lines is False:
  5237. if self.is_legacy is False:
  5238. if theme == 'white':
  5239. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  5240. else:
  5241. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  5242. else:
  5243. self.plotcanvas.axes.grid(True)
  5244. try:
  5245. self.plotcanvas.canvas.draw()
  5246. except IndexError:
  5247. pass
  5248. pass
  5249. self.toggle_grid_lines = True
  5250. else:
  5251. if self.is_legacy is False:
  5252. if theme == 'white':
  5253. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  5254. else:
  5255. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  5256. else:
  5257. self.plotcanvas.axes.grid(False)
  5258. try:
  5259. self.plotcanvas.canvas.draw()
  5260. except IndexError:
  5261. pass
  5262. self.toggle_grid_lines = False
  5263. if self.is_legacy is False:
  5264. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  5265. # - perhaps is a bug in VisPy implementation
  5266. if self.grid_status() is True:
  5267. self.app_cursor.enabled = False
  5268. self.app_cursor.enabled = True
  5269. else:
  5270. self.app_cursor.enabled = True
  5271. self.app_cursor.enabled = False
  5272. def show_preferences_gui(self):
  5273. """
  5274. Called to initialize and show the Preferences GUI
  5275. :return: None
  5276. """
  5277. self.gen_form = self.ui.general_defaults_form
  5278. self.ger_form = self.ui.gerber_defaults_form
  5279. self.exc_form = self.ui.excellon_defaults_form
  5280. self.geo_form = self.ui.geometry_defaults_form
  5281. self.cnc_form = self.ui.cncjob_defaults_form
  5282. self.tools_form = self.ui.tools_defaults_form
  5283. self.tools2_form = self.ui.tools2_defaults_form
  5284. self.fa_form = self.ui.util_defaults_form
  5285. try:
  5286. self.ui.general_scroll_area.takeWidget()
  5287. except Exception:
  5288. self.log.debug("Nothing to remove")
  5289. self.ui.general_scroll_area.setWidget(self.gen_form)
  5290. self.gen_form.show()
  5291. try:
  5292. self.ui.gerber_scroll_area.takeWidget()
  5293. except Exception:
  5294. self.log.debug("Nothing to remove")
  5295. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  5296. self.ger_form.show()
  5297. try:
  5298. self.ui.excellon_scroll_area.takeWidget()
  5299. except Exception:
  5300. self.log.debug("Nothing to remove")
  5301. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  5302. self.exc_form.show()
  5303. try:
  5304. self.ui.geometry_scroll_area.takeWidget()
  5305. except Exception:
  5306. self.log.debug("Nothing to remove")
  5307. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  5308. self.geo_form.show()
  5309. try:
  5310. self.ui.cncjob_scroll_area.takeWidget()
  5311. except Exception:
  5312. self.log.debug("Nothing to remove")
  5313. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  5314. self.cnc_form.show()
  5315. try:
  5316. self.ui.tools_scroll_area.takeWidget()
  5317. except Exception:
  5318. self.log.debug("Nothing to remove")
  5319. self.ui.tools_scroll_area.setWidget(self.tools_form)
  5320. self.tools_form.show()
  5321. try:
  5322. self.ui.tools2_scroll_area.takeWidget()
  5323. except Exception:
  5324. self.log.debug("Nothing to remove")
  5325. self.ui.tools2_scroll_area.setWidget(self.tools2_form)
  5326. self.tools2_form.show()
  5327. try:
  5328. self.ui.fa_scroll_area.takeWidget()
  5329. except Exception:
  5330. self.log.debug("Nothing to remove")
  5331. self.ui.fa_scroll_area.setWidget(self.fa_form)
  5332. self.fa_form.show()
  5333. self.log.debug("Finished Preferences GUI form initialization.")
  5334. # self.options2form()
  5335. def init_color_pickers_in_preferences_gui(self):
  5336. # Init Gerber Plot Colors
  5337. self.ui.gerber_defaults_form.gerber_gen_group.pf_color_entry.set_value(self.defaults['gerber_plot_fill'])
  5338. self.ui.gerber_defaults_form.gerber_gen_group.pf_color_button.setStyleSheet(
  5339. "background-color:%s;"
  5340. "border-color: dimgray" % str(self.defaults['gerber_plot_fill'])[:7])
  5341. self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_spinner.set_value(
  5342. int(self.defaults['gerber_plot_fill'][7:9], 16))
  5343. self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.setValue(
  5344. int(self.defaults['gerber_plot_fill'][7:9], 16))
  5345. self.ui.gerber_defaults_form.gerber_gen_group.pl_color_entry.set_value(self.defaults['gerber_plot_line'])
  5346. self.ui.gerber_defaults_form.gerber_gen_group.pl_color_button.setStyleSheet(
  5347. "background-color:%s;"
  5348. "border-color: dimgray" % str(self.defaults['gerber_plot_line'])[:7])
  5349. # Init Excellon Plot Colors
  5350. self.ui.excellon_defaults_form.excellon_gen_group.fill_color_entry.set_value(
  5351. self.defaults['excellon_plot_fill'])
  5352. self.ui.excellon_defaults_form.excellon_gen_group.fill_color_button.setStyleSheet(
  5353. "background-color:%s;"
  5354. "border-color: dimgray" % str(self.defaults['excellon_plot_fill'])[:7])
  5355. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_spinner.set_value(
  5356. int(self.defaults['excellon_plot_fill'][7:9], 16))
  5357. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.setValue(
  5358. int(self.defaults['excellon_plot_fill'][7:9], 16))
  5359. self.ui.excellon_defaults_form.excellon_gen_group.line_color_entry.set_value(
  5360. self.defaults['excellon_plot_line'])
  5361. self.ui.excellon_defaults_form.excellon_gen_group.line_color_button.setStyleSheet(
  5362. "background-color:%s;"
  5363. "border-color: dimgray" % str(self.defaults['excellon_plot_line'])[:7])
  5364. # Init Geometry Plot Colors
  5365. self.ui.geometry_defaults_form.geometry_gen_group.line_color_entry.set_value(
  5366. self.defaults['geometry_plot_line'])
  5367. self.ui.geometry_defaults_form.geometry_gen_group.line_color_button.setStyleSheet(
  5368. "background-color:%s;"
  5369. "border-color: dimgray" % str(self.defaults['geometry_plot_line'])[:7])
  5370. # Init CNCJob Travel Line Colors
  5371. self.ui.cncjob_defaults_form.cncjob_gen_group.tfill_color_entry.set_value(
  5372. self.defaults['cncjob_travel_fill'])
  5373. self.ui.cncjob_defaults_form.cncjob_gen_group.tfill_color_button.setStyleSheet(
  5374. "background-color:%s;"
  5375. "border-color: dimgray" % str(self.defaults['cncjob_travel_fill'])[:7])
  5376. self.ui.cncjob_defaults_form.cncjob_gen_group.tcolor_alpha_spinner.set_value(
  5377. int(self.defaults['cncjob_travel_fill'][7:9], 16))
  5378. self.ui.cncjob_defaults_form.cncjob_gen_group.tcolor_alpha_slider.setValue(
  5379. int(self.defaults['cncjob_travel_fill'][7:9], 16))
  5380. self.ui.cncjob_defaults_form.cncjob_gen_group.tline_color_entry.set_value(
  5381. self.defaults['cncjob_travel_line'])
  5382. self.ui.cncjob_defaults_form.cncjob_gen_group.tline_color_button.setStyleSheet(
  5383. "background-color:%s;"
  5384. "border-color: dimgray" % str(self.defaults['cncjob_travel_line'])[:7])
  5385. # Init CNCJob Plot Colors
  5386. self.ui.cncjob_defaults_form.cncjob_gen_group.fill_color_entry.set_value(
  5387. self.defaults['cncjob_plot_fill'])
  5388. self.ui.cncjob_defaults_form.cncjob_gen_group.fill_color_button.setStyleSheet(
  5389. "background-color:%s;"
  5390. "border-color: dimgray" % str(self.defaults['cncjob_plot_fill'])[:7])
  5391. self.ui.cncjob_defaults_form.cncjob_gen_group.line_color_entry.set_value(
  5392. self.defaults['cncjob_plot_line'])
  5393. self.ui.cncjob_defaults_form.cncjob_gen_group.line_color_button.setStyleSheet(
  5394. "background-color:%s;"
  5395. "border-color: dimgray" % str(self.defaults['cncjob_plot_line'])[:7])
  5396. # Init Left-Right Selection colors
  5397. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  5398. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5399. "background-color:%s;"
  5400. "border-color: dimgray" % str(self.defaults['global_sel_fill'])[:7])
  5401. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  5402. int(self.defaults['global_sel_fill'][7:9], 16))
  5403. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  5404. int(self.defaults['global_sel_fill'][7:9], 16))
  5405. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  5406. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5407. "background-color:%s;"
  5408. "border-color: dimgray" % str(self.defaults['global_sel_line'])[:7])
  5409. # Init Right-Left Selection colors
  5410. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  5411. self.defaults['global_alt_sel_fill'])
  5412. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5413. "background-color:%s;"
  5414. "border-color: dimgray" % str(self.defaults['global_alt_sel_fill'])[:7])
  5415. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  5416. int(self.defaults['global_sel_fill'][7:9], 16))
  5417. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  5418. int(self.defaults['global_sel_fill'][7:9], 16))
  5419. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  5420. self.defaults['global_alt_sel_line'])
  5421. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5422. "background-color:%s;"
  5423. "border-color: dimgray" % str(self.defaults['global_alt_sel_line'])[:7])
  5424. # Init Draw color and Selection Draw Color
  5425. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  5426. self.defaults['global_draw_color'])
  5427. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5428. "background-color:%s;"
  5429. "border-color: dimgray" % str(self.defaults['global_draw_color'])[:7])
  5430. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  5431. self.defaults['global_sel_draw_color'])
  5432. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5433. "background-color:%s;"
  5434. "border-color: dimgray" % str(self.defaults['global_sel_draw_color'])[:7])
  5435. # Init Project Items color
  5436. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  5437. self.defaults['global_proj_item_color'])
  5438. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5439. "background-color:%s;"
  5440. "border-color: dimgray" % str(self.defaults['global_proj_item_color'])[:7])
  5441. # Init Project Disabled Items color
  5442. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  5443. self.defaults['global_proj_item_dis_color'])
  5444. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5445. "background-color:%s;"
  5446. "border-color: dimgray" % str(self.defaults['global_proj_item_dis_color'])[:7])
  5447. # Init Project Disabled Items color
  5448. self.ui.general_defaults_form.general_app_set_group.mouse_cursor_entry.set_value(
  5449. self.defaults['global_cursor_color'])
  5450. self.ui.general_defaults_form.general_app_set_group.mouse_cursor_button.setStyleSheet(
  5451. "background-color:%s;"
  5452. "border-color: dimgray" % str(self.defaults['global_cursor_color'])[:7])
  5453. # Init the Annotation CNC Job color
  5454. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  5455. self.defaults['cncjob_annotation_fontcolor'])
  5456. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5457. "background-color:%s;"
  5458. "border-color: dimgray" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  5459. # Init the Tool Film color
  5460. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  5461. self.defaults['tools_film_color'])
  5462. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5463. "background-color:%s;"
  5464. "border-color: dimgray" % str(self.defaults['tools_film_color'])[:7]
  5465. )
  5466. # Init the Tool QRCode colors
  5467. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(
  5468. self.defaults['tools_qrcode_fill_color'])
  5469. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5470. "background-color:%s;"
  5471. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])[:7])
  5472. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(
  5473. self.defaults['tools_qrcode_back_color'])
  5474. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5475. "background-color:%s;"
  5476. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])[:7])
  5477. def on_update_exc_export(self, state):
  5478. """
  5479. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  5480. if the update_excellon_cb checkbox is checked
  5481. :param state: state of the checkbox whose signals is tied to his slot
  5482. :return:
  5483. """
  5484. if state:
  5485. # first try to disconnect
  5486. try:
  5487. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  5488. disconnect(self.on_excellon_format_changed)
  5489. except TypeError:
  5490. pass
  5491. try:
  5492. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  5493. disconnect(self.on_excellon_format_changed)
  5494. except TypeError:
  5495. pass
  5496. try:
  5497. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  5498. disconnect(self.on_excellon_format_changed)
  5499. except TypeError:
  5500. pass
  5501. try:
  5502. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  5503. disconnect(self.on_excellon_format_changed)
  5504. except TypeError:
  5505. pass
  5506. try:
  5507. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  5508. disconnect(self.on_excellon_zeros_changed)
  5509. except TypeError:
  5510. pass
  5511. try:
  5512. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  5513. disconnect(self.on_excellon_zeros_changed)
  5514. except TypeError:
  5515. pass
  5516. # the connect them
  5517. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  5518. self.on_excellon_format_changed)
  5519. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  5520. self.on_excellon_format_changed)
  5521. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  5522. self.on_excellon_format_changed)
  5523. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  5524. self.on_excellon_format_changed)
  5525. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  5526. self.on_excellon_zeros_changed)
  5527. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  5528. self.on_excellon_units_changed)
  5529. else:
  5530. # disconnect the signals
  5531. try:
  5532. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  5533. disconnect(self.on_excellon_format_changed)
  5534. except TypeError:
  5535. pass
  5536. try:
  5537. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  5538. disconnect(self.on_excellon_format_changed)
  5539. except TypeError:
  5540. pass
  5541. try:
  5542. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  5543. disconnect(self.on_excellon_format_changed)
  5544. except TypeError:
  5545. pass
  5546. try:
  5547. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  5548. disconnect(self.on_excellon_format_changed)
  5549. except TypeError:
  5550. pass
  5551. try:
  5552. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  5553. disconnect(self.on_excellon_zeros_changed)
  5554. except TypeError:
  5555. pass
  5556. try:
  5557. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  5558. disconnect(self.on_excellon_zeros_changed)
  5559. except TypeError:
  5560. pass
  5561. def on_excellon_format_changed(self):
  5562. """
  5563. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  5564. :return: None
  5565. """
  5566. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  5567. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5568. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  5569. )
  5570. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5571. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  5572. )
  5573. else:
  5574. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5575. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  5576. )
  5577. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5578. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  5579. )
  5580. def on_excellon_zeros_changed(self):
  5581. """
  5582. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  5583. :return: None
  5584. """
  5585. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  5586. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  5587. )
  5588. def on_excellon_units_changed(self):
  5589. """
  5590. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  5591. :return: None
  5592. """
  5593. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  5594. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  5595. )
  5596. self.on_excellon_format_changed()
  5597. def on_film_color_entry(self):
  5598. self.defaults['tools_film_color'] = \
  5599. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  5600. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5601. "background-color:%s;"
  5602. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  5603. )
  5604. def on_film_color_button(self):
  5605. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  5606. c_dialog = QtWidgets.QColorDialog()
  5607. film_color = c_dialog.getColor(initial=current_color)
  5608. if film_color.isValid() is False:
  5609. return
  5610. # if new color is different then mark that the Preferences are changed
  5611. if film_color != current_color:
  5612. self.on_preferences_edited()
  5613. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5614. "background-color:%s;"
  5615. "border-color: dimgray" % str(film_color.name())
  5616. )
  5617. new_val_sel = str(film_color.name())
  5618. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  5619. self.defaults['tools_film_color'] = new_val_sel
  5620. def on_qrcode_fill_color_entry(self):
  5621. self.defaults['tools_qrcode_fill_color'] = \
  5622. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  5623. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5624. "background-color:%s;"
  5625. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  5626. )
  5627. def on_qrcode_fill_color_button(self):
  5628. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  5629. c_dialog = QtWidgets.QColorDialog()
  5630. fill_color = c_dialog.getColor(initial=current_color)
  5631. if fill_color.isValid() is False:
  5632. return
  5633. # if new color is different then mark that the Preferences are changed
  5634. if fill_color != current_color:
  5635. self.on_preferences_edited()
  5636. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5637. "background-color:%s;"
  5638. "border-color: dimgray" % str(fill_color.name())
  5639. )
  5640. new_val_sel = str(fill_color.name())
  5641. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  5642. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  5643. def on_qrcode_back_color_entry(self):
  5644. self.defaults['tools_qrcode_back_color'] = \
  5645. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  5646. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5647. "background-color:%s;"
  5648. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  5649. )
  5650. def on_qrcode_back_color_button(self):
  5651. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  5652. c_dialog = QtWidgets.QColorDialog()
  5653. back_color = c_dialog.getColor(initial=current_color)
  5654. if back_color.isValid() is False:
  5655. return
  5656. # if new color is different then mark that the Preferences are changed
  5657. if back_color != current_color:
  5658. self.on_preferences_edited()
  5659. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5660. "background-color:%s;"
  5661. "border-color: dimgray" % str(back_color.name())
  5662. )
  5663. new_val_sel = str(back_color.name())
  5664. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  5665. self.defaults['tools_qrcode_back_color'] = new_val_sel
  5666. def on_tab_rmb_click(self, checked):
  5667. self.ui.notebook.set_detachable(val=checked)
  5668. self.defaults["global_tabs_detachable"] = checked
  5669. self.ui.plot_tab_area.set_detachable(val=checked)
  5670. self.defaults["global_tabs_detachable"] = checked
  5671. def on_tab_setup_context_menu(self):
  5672. initial_checked = self.defaults["global_tabs_detachable"]
  5673. action_name = str(_("Detachable Tabs"))
  5674. action = QtWidgets.QAction(self)
  5675. action.setCheckable(True)
  5676. action.setText(action_name)
  5677. action.setChecked(initial_checked)
  5678. self.ui.notebook.tabBar.addAction(action)
  5679. self.ui.plot_tab_area.tabBar.addAction(action)
  5680. try:
  5681. action.triggered.disconnect()
  5682. except TypeError:
  5683. pass
  5684. action.triggered.connect(self.on_tab_rmb_click)
  5685. def on_deselect_all(self):
  5686. self.collection.set_all_inactive()
  5687. self.delete_selection_shape()
  5688. def on_workspace_modified(self):
  5689. # self.save_defaults(silent=True)
  5690. if self.is_legacy is True:
  5691. self.plotcanvas.delete_workspace()
  5692. self.defaults_read_form()
  5693. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  5694. def on_workspace(self):
  5695. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  5696. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  5697. else:
  5698. self.plotcanvas.delete_workspace()
  5699. self.defaults_read_form()
  5700. # self.save_defaults(silent=True)
  5701. def on_workspace_toggle(self):
  5702. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  5703. try:
  5704. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  5705. except TypeError:
  5706. pass
  5707. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  5708. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  5709. self.on_workspace()
  5710. def on_cursor_type(self, val):
  5711. """
  5712. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  5713. :return: None
  5714. """
  5715. self.app_cursor.enabled = False
  5716. if val == 'small':
  5717. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  5718. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  5719. self.app_cursor = self.plotcanvas.new_cursor()
  5720. else:
  5721. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  5722. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  5723. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  5724. if self.ui.grid_snap_btn.isChecked():
  5725. self.app_cursor.enabled = True
  5726. else:
  5727. self.app_cursor.enabled = False
  5728. def on_save_button(self, save_to_file=True):
  5729. log.debug("App.on_save_button() --> Applying preferences to file.")
  5730. # Preferences saved, update flag
  5731. self.preferences_changed_flag = False
  5732. # Preferences save, update the color of the Preferences Tab text
  5733. for idx in range(self.ui.plot_tab_area.count()):
  5734. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5735. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  5736. # restore the default stylesheet by setting a blank one
  5737. self.ui.pref_apply_button.setStyleSheet("")
  5738. self.inform.emit('%s' % _("Preferences applied."))
  5739. # make sure we update the self.current_defaults dict used to undo changes to self.defaults
  5740. self.current_defaults.update(self.defaults)
  5741. if save_to_file:
  5742. self.save_defaults(silent=False)
  5743. # load the defaults so they are updated into the app
  5744. self.load_defaults(filename='current_defaults')
  5745. # Re-fresh project options
  5746. self.on_options_app2project()
  5747. settgs = QSettings("Open Source", "FlatCAM")
  5748. # save the notebook font size
  5749. fsize = self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  5750. settgs.setValue('notebook_font_size', fsize)
  5751. # save the axis font size
  5752. g_fsize = self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  5753. settgs.setValue('axis_font_size', g_fsize)
  5754. # save the textbox font size
  5755. tb_fsize = self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  5756. settgs.setValue('textbox_font_size', tb_fsize)
  5757. settgs.setValue(
  5758. 'machinist',
  5759. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  5760. )
  5761. # This will write the setting to the platform specific storage.
  5762. del settgs
  5763. if save_to_file:
  5764. # close the tab and delete it
  5765. for idx in range(self.ui.plot_tab_area.count()):
  5766. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5767. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  5768. self.ui.plot_tab_area.closeTab(idx)
  5769. break
  5770. def on_pref_close_button(self):
  5771. # Preferences saved, update flag
  5772. self.preferences_changed_flag = False
  5773. try:
  5774. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_plot_area_tab_closed)
  5775. except TypeError:
  5776. pass
  5777. try:
  5778. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  5779. except (TypeError, AttributeError):
  5780. pass
  5781. self.defaults_write_form(source_dict=self.current_defaults)
  5782. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  5783. lambda: self.on_toggle_units(no_pref=False))
  5784. self.defaults.update(self.current_defaults)
  5785. # shared_items = {k: self.defaults[k] for k in self.defaults if k in self.current_defaults and
  5786. # self.defaults[k] == self.current_defaults[k]}
  5787. # print(len(self.defaults), len(shared_items))
  5788. # Preferences save, update the color of the Preferences Tab text
  5789. for idx in range(self.ui.plot_tab_area.count()):
  5790. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5791. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  5792. self.ui.plot_tab_area.closeTab(idx)
  5793. break
  5794. self.inform.emit('%s' % _("Preferences closed without saving."))
  5795. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  5796. def on_tool_add_keypress(self):
  5797. # ## Current application units in Upper Case
  5798. self.units = self.defaults['units'].upper()
  5799. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5800. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5801. if notebook_widget_name == 'selected_tab':
  5802. if self.collection.get_active().kind == 'geometry':
  5803. # Tool add works for Geometry only if Advanced is True in Preferences
  5804. if self.defaults["global_app_level"] == 'a':
  5805. tool_add_popup = FCInputDialog(title="New Tool ...",
  5806. text='Enter a Tool Diameter:',
  5807. min=0.0000, max=99.9999, decimals=4)
  5808. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  5809. val, ok = tool_add_popup.get_value()
  5810. if ok:
  5811. if float(val) == 0:
  5812. self.inform.emit('[WARNING_NOTCL] %s' %
  5813. _("Please enter a tool diameter with non-zero value, in Float format."))
  5814. return
  5815. self.collection.get_active().on_tool_add(dia=float(val))
  5816. else:
  5817. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  5818. else:
  5819. msgbox = QtWidgets.QMessageBox()
  5820. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5821. "Go to Preferences -> General - Show Advanced Options."))
  5822. msgbox.setWindowTitle("Tool adding ...")
  5823. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  5824. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5825. msgbox.setDefaultButton(bt_ok)
  5826. msgbox.exec_()
  5827. # work only if the notebook tab on focus is the Tools_Tab
  5828. if notebook_widget_name == 'tool_tab':
  5829. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5830. # and only if the tool is NCC Tool
  5831. if tool_widget == self.ncclear_tool.toolName:
  5832. self.ncclear_tool.on_add_tool_by_key()
  5833. # and only if the tool is Paint Area Tool
  5834. elif tool_widget == self.paint_tool.toolName:
  5835. self.paint_tool.on_add_tool_by_key()
  5836. # and only if the tool is Solder Paste Dispensing Tool
  5837. elif tool_widget == self.paste_tool.toolName:
  5838. self.paste_tool.on_add_tool_by_key()
  5839. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5840. # See description bellow.
  5841. def on_delete_keypress(self):
  5842. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5843. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5844. if notebook_widget_name == 'selected_tab':
  5845. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  5846. self.collection.get_active().on_tool_delete()
  5847. # work only if the notebook tab on focus is the Tools_Tab
  5848. elif notebook_widget_name == 'tool_tab':
  5849. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5850. # and only if the tool is NCC Tool
  5851. if tool_widget == self.ncclear_tool.toolName:
  5852. self.ncclear_tool.on_tool_delete()
  5853. # and only if the tool is Paint Tool
  5854. elif tool_widget == self.paint_tool.toolName:
  5855. self.paint_tool.on_tool_delete()
  5856. # and only if the tool is Solder Paste Dispensing Tool
  5857. elif tool_widget == self.paste_tool.toolName:
  5858. self.paste_tool.on_tool_delete()
  5859. else:
  5860. self.on_delete()
  5861. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5862. # some screens you have to be careful where you hover with your mouse.
  5863. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5864. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5865. # Complicated, I know :)
  5866. def on_delete(self, force_deletion=False):
  5867. """
  5868. Delete the currently selected FlatCAMObjs.
  5869. :param force_deletion: used by Tcl command
  5870. :return: None
  5871. """
  5872. self.report_usage("on_delete()")
  5873. response = None
  5874. bt_ok = None
  5875. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5876. # a geometry object before we update it.
  5877. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5878. and self.grb_editor.editor_active is False:
  5879. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  5880. msgbox = QtWidgets.QMessageBox()
  5881. msgbox.setWindowTitle(_("Delete objects"))
  5882. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  5883. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5884. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5885. "the selected objects?"))
  5886. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5887. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5888. msgbox.setDefaultButton(bt_ok)
  5889. msgbox.exec_()
  5890. response = msgbox.clickedButton()
  5891. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  5892. response = bt_ok
  5893. if response == bt_ok:
  5894. if self.collection.get_active():
  5895. self.log.debug("App.on_delete()")
  5896. for obj_active in self.collection.get_selected():
  5897. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  5898. if isinstance(obj_active, GerberObject):
  5899. for el in obj_active.mark_shapes:
  5900. obj_active.mark_shapes[el].clear(update=True)
  5901. obj_active.mark_shapes[el].enabled = False
  5902. # obj_active.mark_shapes[el] = None
  5903. del el
  5904. elif isinstance(obj_active, CNCJobObject):
  5905. try:
  5906. obj_active.text_col.enabled = False
  5907. del obj_active.text_col
  5908. obj_active.annotation.clear(update=True)
  5909. del obj_active.annotation
  5910. except AttributeError as e:
  5911. log.debug(
  5912. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  5913. )
  5914. while self.collection.get_selected():
  5915. self.delete_first_selected()
  5916. self.inform.emit('%s...' % _("Object(s) deleted"))
  5917. # make sure that the selection shape is deleted, too
  5918. self.delete_selection_shape()
  5919. else:
  5920. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  5921. else:
  5922. self.inform.emit(_("Save the work in Editor and try again ..."))
  5923. def delete_first_selected(self):
  5924. # Keep this for later
  5925. try:
  5926. sel_obj = self.collection.get_active()
  5927. name = sel_obj.options["name"]
  5928. isPlotted = sel_obj.options["plot"]
  5929. except AttributeError:
  5930. self.log.debug("Nothing selected for deletion")
  5931. return
  5932. if self.is_legacy is True:
  5933. # Remove plot only if the object was plotted otherwise delaxes will fail
  5934. if isPlotted:
  5935. try:
  5936. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  5937. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  5938. except Exception as e:
  5939. log.debug("App.delete_first_selected() --> %s" % str(e))
  5940. self.plotcanvas.auto_adjust_axes()
  5941. # Remove from dictionary
  5942. self.collection.delete_active()
  5943. # Clear form
  5944. self.setup_component_editor()
  5945. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  5946. def on_set_origin(self):
  5947. """
  5948. Set the origin to the left mouse click position
  5949. :return: None
  5950. """
  5951. # display the message for the user
  5952. # and ask him to click on the desired position
  5953. self.report_usage("on_set_origin()")
  5954. def origin_replot():
  5955. def worker_task():
  5956. with self.proc_container.new('%s...' % _("Plotting")):
  5957. for obj in self.collection.get_list():
  5958. obj.plot()
  5959. self.plotcanvas.fit_view()
  5960. if self.is_legacy:
  5961. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  5962. else:
  5963. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  5964. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5965. self.inform.emit(_('Click to set the origin ...'))
  5966. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  5967. # first disconnect it as it may have been used by something else
  5968. try:
  5969. self.replot_signal.disconnect()
  5970. except TypeError:
  5971. pass
  5972. self.replot_signal[list].connect(origin_replot)
  5973. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  5974. """
  5975. :param event:
  5976. :param location:
  5977. :param noplot:
  5978. :param use_thread:
  5979. :return:
  5980. """
  5981. noplot_sig = noplot
  5982. def worker_task():
  5983. with self.proc_container.new(_("Setting Origin...")):
  5984. obj_list = self.collection.get_list()
  5985. for obj in obj_list:
  5986. obj.offset((x, y))
  5987. self.object_changed.emit(obj)
  5988. # Update the object bounding box options
  5989. a, b, c, d = obj.bounds()
  5990. obj.options['xmin'] = a
  5991. obj.options['ymin'] = b
  5992. obj.options['xmax'] = c
  5993. obj.options['ymax'] = d
  5994. self.inform.emit('[success] %s...' % _('Origin set'))
  5995. for obj in obj_list:
  5996. out_name = obj.options["name"]
  5997. if obj.kind == 'gerber':
  5998. obj.source_file = self.export_gerber(
  5999. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  6000. elif obj.kind == 'excellon':
  6001. obj.source_file = self.export_excellon(
  6002. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  6003. if noplot_sig is False:
  6004. self.replot_signal.emit([])
  6005. if location is not None:
  6006. if len(location) != 2:
  6007. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  6008. return 'fail'
  6009. x, y = location
  6010. if use_thread is True:
  6011. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6012. else:
  6013. worker_task()
  6014. self.should_we_save = True
  6015. return
  6016. if event.button == 1:
  6017. if self.is_legacy is False:
  6018. event_pos = event.pos
  6019. else:
  6020. event_pos = (event.xdata, event.ydata)
  6021. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6022. if self.grid_status():
  6023. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6024. else:
  6025. pos = pos_canvas
  6026. x = 0 - pos[0]
  6027. y = 0 - pos[1]
  6028. if use_thread is True:
  6029. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6030. else:
  6031. worker_task()
  6032. self.should_we_save = True
  6033. def on_move2origin(self, use_thread=True):
  6034. """
  6035. Move selected objects to origin.
  6036. :param use_thread: Control if to use threaded operation. Boolean.
  6037. :return:
  6038. """
  6039. def worker_task():
  6040. with self.proc_container.new(_("Moving to Origin...")):
  6041. obj_list = self.collection.get_selected()
  6042. if not obj_list:
  6043. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  6044. return
  6045. xminlist = []
  6046. yminlist = []
  6047. # first get a bounding box to fit all
  6048. for obj in obj_list:
  6049. xmin, ymin, xmax, ymax = obj.bounds()
  6050. xminlist.append(xmin)
  6051. yminlist.append(ymin)
  6052. # get the minimum x,y for all objects selected
  6053. x = min(xminlist)
  6054. y = min(yminlist)
  6055. for obj in obj_list:
  6056. obj.offset((-x, -y))
  6057. self.object_changed.emit(obj)
  6058. # Update the object bounding box options
  6059. a, b, c, d = obj.bounds()
  6060. obj.options['xmin'] = a
  6061. obj.options['ymin'] = b
  6062. obj.options['xmax'] = c
  6063. obj.options['ymax'] = d
  6064. for obj in obj_list:
  6065. obj.plot()
  6066. for obj in obj_list:
  6067. out_name = obj.options["name"]
  6068. if obj.kind == 'gerber':
  6069. obj.source_file = self.export_gerber(
  6070. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  6071. elif obj.kind == 'excellon':
  6072. obj.source_file = self.export_excellon(
  6073. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  6074. self.inform.emit('[success] %s...' % _('Origin set'))
  6075. if use_thread is True:
  6076. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6077. else:
  6078. worker_task()
  6079. self.should_we_save = True
  6080. def on_jump_to(self, custom_location=None, fit_center=True):
  6081. """
  6082. Jump to a location by setting the mouse cursor location.
  6083. :param custom_location: Jump to a specified point. (x, y) tuple.
  6084. :param fit_center: If to fit view. Boolean.
  6085. :return:
  6086. """
  6087. self.report_usage("on_jump_to()")
  6088. if not custom_location:
  6089. dia_box_location = None
  6090. try:
  6091. dia_box_location = eval(self.clipboard.text())
  6092. except Exception:
  6093. pass
  6094. if type(dia_box_location) == tuple:
  6095. dia_box_location = str(dia_box_location)
  6096. else:
  6097. dia_box_location = None
  6098. # dia_box = Dialog_box(title=_("Jump to ..."),
  6099. # label=_("Enter the coordinates in format X,Y:"),
  6100. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6101. # initial_text=dia_box_location)
  6102. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  6103. label=_("Enter the coordinates in format X,Y:"),
  6104. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6105. initial_text=dia_box_location,
  6106. reference=self.defaults['global_jump_ref'])
  6107. if dia_box.ok is True:
  6108. try:
  6109. location = eval(dia_box.location)
  6110. if not isinstance(location, tuple):
  6111. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  6112. return
  6113. if dia_box.reference == 'rel':
  6114. rel_x = self.mouse[0] + location[0]
  6115. rel_y = self.mouse[1] + location[1]
  6116. location = (rel_x, rel_y)
  6117. self.defaults['global_jump_ref'] = dia_box.reference
  6118. except Exception:
  6119. return
  6120. else:
  6121. return
  6122. else:
  6123. location = custom_location
  6124. self.jump_signal.emit(location)
  6125. if fit_center:
  6126. self.plotcanvas.fit_center(loc=location)
  6127. cursor = QtGui.QCursor()
  6128. if self.is_legacy is False:
  6129. # I don't know where those differences come from but they are constant for the current
  6130. # execution of the application and they are multiples of a value around 0.0263mm.
  6131. # In a random way sometimes they are more sometimes they are less
  6132. # if units == 'MM':
  6133. # cal_factor = 0.0263
  6134. # else:
  6135. # cal_factor = 0.0263 / 25.4
  6136. cal_location = (location[0], location[1])
  6137. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6138. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  6139. j_pos = (
  6140. int(canvas_origin.x() + round(jump_loc[0])),
  6141. int(canvas_origin.y() + round(jump_loc[1]))
  6142. )
  6143. cursor.setPos(j_pos[0], j_pos[1])
  6144. else:
  6145. # find the canvas origin which is in the top left corner
  6146. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6147. # determine the coordinates for the lowest left point of the canvas
  6148. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  6149. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  6150. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  6151. # canvas) and the point (width, height) is in the top-right location
  6152. loc = self.plotcanvas.axes.transData.transform_point(location)
  6153. j_pos = (
  6154. int(x0 + loc[0]),
  6155. int(y0 - loc[1])
  6156. )
  6157. cursor.setPos(j_pos[0], j_pos[1])
  6158. self.plotcanvas.mouse = [location[0], location[1]]
  6159. if self.defaults["global_cursor_color_enabled"] is True:
  6160. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  6161. else:
  6162. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  6163. if self.grid_status():
  6164. # Update cursor
  6165. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  6166. symbol='++', edge_color=self.cursor_color_3D,
  6167. edge_width=self.defaults["global_cursor_width"],
  6168. size=self.defaults["global_cursor_size"])
  6169. # Set the position label
  6170. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6171. "<b>Y</b>: %.4f" % (location[0], location[1]))
  6172. # Set the relative position label
  6173. dx = location[0] - float(self.rel_point1[0])
  6174. dy = location[1] - float(self.rel_point1[1])
  6175. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6176. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6177. self.inform.emit('[success] %s' % _("Done."))
  6178. return location
  6179. def on_locate(self, obj, fit_center=True):
  6180. """
  6181. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  6182. :param obj: The object on which to locate certain points
  6183. :param fit_center: If to fit view. Boolean.
  6184. :return: A point location. (x, y) tuple.
  6185. """
  6186. self.report_usage("on_locate()")
  6187. if obj is None:
  6188. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6189. return 'fail'
  6190. class DialogBoxChoice(QtWidgets.QDialog):
  6191. def __init__(self, title=None, icon=None, choice='bl'):
  6192. """
  6193. :param title: string with the window title
  6194. """
  6195. super(DialogBoxChoice, self).__init__()
  6196. self.ok = False
  6197. self.setWindowIcon(icon)
  6198. self.setWindowTitle(str(title))
  6199. self.form = QtWidgets.QFormLayout(self)
  6200. self.ref_radio = RadioSet([
  6201. {"label": _("Bottom-Left"), "value": "bl"},
  6202. {"label": _("Top-Left"), "value": "tl"},
  6203. {"label": _("Bottom-Right"), "value": "br"},
  6204. {"label": _("Top-Right"), "value": "tr"},
  6205. {"label": _("Center"), "value": "c"}
  6206. ], orientation='vertical', stretch=False)
  6207. self.ref_radio.set_value(choice)
  6208. self.form.addRow(self.ref_radio)
  6209. self.button_box = QtWidgets.QDialogButtonBox(
  6210. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  6211. Qt.Horizontal, parent=self)
  6212. self.form.addRow(self.button_box)
  6213. self.button_box.accepted.connect(self.accept)
  6214. self.button_box.rejected.connect(self.reject)
  6215. if self.exec_() == QtWidgets.QDialog.Accepted:
  6216. self.ok = True
  6217. self.location_point = self.ref_radio.get_value()
  6218. else:
  6219. self.ok = False
  6220. self.location_point = None
  6221. dia_box = DialogBoxChoice(title=_("Locate ..."),
  6222. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  6223. choice=self.defaults['global_locate_pt'])
  6224. if dia_box.ok is True:
  6225. try:
  6226. location_point = dia_box.location_point
  6227. self.defaults['global_locate_pt'] = dia_box.location_point
  6228. except Exception:
  6229. return
  6230. else:
  6231. return
  6232. loc_b = obj.bounds()
  6233. if location_point == 'bl':
  6234. location = (loc_b[0], loc_b[1])
  6235. elif location_point == 'tl':
  6236. location = (loc_b[0], loc_b[3])
  6237. elif location_point == 'br':
  6238. location = (loc_b[2], loc_b[1])
  6239. elif location_point == 'tr':
  6240. location = (loc_b[2], loc_b[3])
  6241. else:
  6242. # center
  6243. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  6244. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  6245. location = (cx, cy)
  6246. self.locate_signal.emit(location, location_point)
  6247. if fit_center:
  6248. self.plotcanvas.fit_center(loc=location)
  6249. cursor = QtGui.QCursor()
  6250. if self.is_legacy is False:
  6251. # I don't know where those differences come from but they are constant for the current
  6252. # execution of the application and they are multiples of a value around 0.0263mm.
  6253. # In a random way sometimes they are more sometimes they are less
  6254. # if units == 'MM':
  6255. # cal_factor = 0.0263
  6256. # else:
  6257. # cal_factor = 0.0263 / 25.4
  6258. cal_location = (location[0], location[1])
  6259. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6260. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  6261. j_pos = (
  6262. int(canvas_origin.x() + round(jump_loc[0])),
  6263. int(canvas_origin.y() + round(jump_loc[1]))
  6264. )
  6265. cursor.setPos(j_pos[0], j_pos[1])
  6266. else:
  6267. # find the canvas origin which is in the top left corner
  6268. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6269. # determine the coordinates for the lowest left point of the canvas
  6270. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  6271. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  6272. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  6273. # canvas) and the point (width, height) is in the top-right location
  6274. loc = self.plotcanvas.axes.transData.transform_point(location)
  6275. j_pos = (
  6276. int(x0 + loc[0]),
  6277. int(y0 - loc[1])
  6278. )
  6279. cursor.setPos(j_pos[0], j_pos[1])
  6280. self.plotcanvas.mouse = [location[0], location[1]]
  6281. if self.defaults["global_cursor_color_enabled"] is True:
  6282. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  6283. else:
  6284. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  6285. if self.grid_status():
  6286. # Update cursor
  6287. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  6288. symbol='++', edge_color=self.cursor_color_3D,
  6289. edge_width=self.defaults["global_cursor_width"],
  6290. size=self.defaults["global_cursor_size"])
  6291. # Set the position label
  6292. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6293. "<b>Y</b>: %.4f" % (location[0], location[1]))
  6294. # Set the relative position label
  6295. self.dx = location[0] - float(self.rel_point1[0])
  6296. self.dy = location[1] - float(self.rel_point1[1])
  6297. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6298. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  6299. self.inform.emit('[success] %s' % _("Done."))
  6300. return location
  6301. def on_copy_command(self):
  6302. """
  6303. Will copy a selection of objects, creating new objects.
  6304. :return:
  6305. """
  6306. self.report_usage("on_copy_command()")
  6307. def initialize(obj_init, app):
  6308. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6309. try:
  6310. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  6311. except AttributeError:
  6312. pass
  6313. try:
  6314. obj_init.apertures = deepcopy(obj.apertures)
  6315. except AttributeError:
  6316. pass
  6317. try:
  6318. if obj.tools:
  6319. obj_init.tools = deepcopy(obj.tools)
  6320. except Exception as err:
  6321. log.debug("App.on_copy_command() --> %s" % str(err))
  6322. try:
  6323. obj_init.source_file = deepcopy(obj.source_file)
  6324. except (AttributeError, TypeError):
  6325. pass
  6326. def initialize_excellon(obj_init, app):
  6327. obj_init.source_file = deepcopy(obj.source_file)
  6328. obj_init.tools = deepcopy(obj.tools)
  6329. # drills are offset, so they need to be deep copied
  6330. obj_init.drills = deepcopy(obj.drills)
  6331. # slots are offset, so they need to be deep copied
  6332. obj_init.slots = deepcopy(obj.slots)
  6333. obj_init.create_geometry()
  6334. def initialize_script(obj_init, app_obj):
  6335. obj_init.source_file = deepcopy(obj.source_file)
  6336. def initialize_document(obj_init, app_obj):
  6337. obj_init.source_file = deepcopy(obj.source_file)
  6338. for obj in self.collection.get_selected():
  6339. obj_name = obj.options["name"]
  6340. try:
  6341. if isinstance(obj, ExcellonObject):
  6342. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  6343. elif isinstance(obj, GerberObject):
  6344. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  6345. elif isinstance(obj, GeometryObject):
  6346. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  6347. elif isinstance(obj, ScriptObject):
  6348. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  6349. elif isinstance(obj, DocumentObject):
  6350. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  6351. except Exception as e:
  6352. return "Operation failed: %s" % str(e)
  6353. def on_paste_command(self):
  6354. pass
  6355. def on_copy_object2(self, custom_name):
  6356. def initialize_geometry(obj_init, app):
  6357. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6358. try:
  6359. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  6360. except AttributeError:
  6361. pass
  6362. try:
  6363. obj_init.apertures = deepcopy(obj.apertures)
  6364. except AttributeError:
  6365. pass
  6366. try:
  6367. if obj.tools:
  6368. obj_init.tools = deepcopy(obj.tools)
  6369. except Exception as ee:
  6370. log.debug("on_copy_object2() --> %s" % str(ee))
  6371. def initialize_gerber(obj_init, app):
  6372. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6373. obj_init.apertures = deepcopy(obj.apertures)
  6374. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  6375. def initialize_excellon(obj_init, app):
  6376. obj_init.tools = deepcopy(obj.tools)
  6377. # drills are offset, so they need to be deep copied
  6378. obj_init.drills = deepcopy(obj.drills)
  6379. # slots are offset, so they need to be deep copied
  6380. obj_init.slots = deepcopy(obj.slots)
  6381. obj_init.create_geometry()
  6382. for obj in self.collection.get_selected():
  6383. obj_name = obj.options["name"]
  6384. try:
  6385. if isinstance(obj, ExcellonObject):
  6386. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  6387. elif isinstance(obj, GerberObject):
  6388. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  6389. elif isinstance(obj, GeometryObject):
  6390. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  6391. except Exception as er:
  6392. return "Operation failed: %s" % str(er)
  6393. def on_rename_object(self, text):
  6394. """
  6395. Will rename an object.
  6396. :param text: New name for the object.
  6397. :return:
  6398. """
  6399. self.report_usage("on_rename_object()")
  6400. named_obj = self.collection.get_active()
  6401. for obj in named_obj:
  6402. if obj is list:
  6403. self.on_rename_object(text)
  6404. else:
  6405. try:
  6406. obj.options['name'] = text
  6407. except Exception as e:
  6408. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  6409. def convert_any2geo(self):
  6410. """
  6411. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  6412. :return:
  6413. """
  6414. self.report_usage("convert_any2geo()")
  6415. def initialize(obj_init, app):
  6416. obj_init.solid_geometry = obj.solid_geometry
  6417. try:
  6418. obj_init.follow_geometry = obj.follow_geometry
  6419. except AttributeError:
  6420. pass
  6421. try:
  6422. obj_init.apertures = obj.apertures
  6423. except AttributeError:
  6424. pass
  6425. try:
  6426. if obj.tools:
  6427. obj_init.tools = obj.tools
  6428. except AttributeError:
  6429. pass
  6430. def initialize_excellon(obj_init, app):
  6431. # objs = self.collection.get_selected()
  6432. # GeometryObject.merge(objs, obj)
  6433. solid_geo = []
  6434. for tool in obj.tools:
  6435. for geo in obj.tools[tool]['solid_geometry']:
  6436. solid_geo.append(geo)
  6437. obj_init.solid_geometry = deepcopy(solid_geo)
  6438. if not self.collection.get_selected():
  6439. log.warning("App.convert_any2geo --> No object selected")
  6440. self.inform.emit('[WARNING_NOTCL] %s' %
  6441. _("No object is selected. Select an object and try again."))
  6442. return
  6443. for obj in self.collection.get_selected():
  6444. obj_name = obj.options["name"]
  6445. try:
  6446. if isinstance(obj, ExcellonObject):
  6447. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  6448. else:
  6449. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  6450. except Exception as e:
  6451. return "Operation failed: %s" % str(e)
  6452. def convert_any2gerber(self):
  6453. """
  6454. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  6455. :return:
  6456. """
  6457. self.report_usage("convert_any2gerber()")
  6458. def initialize_geometry(obj_init, app):
  6459. apertures = {}
  6460. apid = 0
  6461. apertures[str(apid)] = {}
  6462. apertures[str(apid)]['geometry'] = []
  6463. for obj_orig in obj.solid_geometry:
  6464. new_elem = {}
  6465. new_elem['solid'] = obj_orig
  6466. try:
  6467. new_elem['follow'] = obj_orig.exterior
  6468. except AttributeError:
  6469. pass
  6470. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  6471. apertures[str(apid)]['size'] = 0.0
  6472. apertures[str(apid)]['type'] = 'C'
  6473. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6474. obj_init.apertures = deepcopy(apertures)
  6475. def initialize_excellon(obj_init, app):
  6476. apertures = {}
  6477. apid = 10
  6478. for tool in obj.tools:
  6479. apertures[str(apid)] = {}
  6480. apertures[str(apid)]['geometry'] = []
  6481. for geo in obj.tools[tool]['solid_geometry']:
  6482. new_el = {}
  6483. new_el['solid'] = geo
  6484. new_el['follow'] = geo.exterior
  6485. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  6486. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  6487. apertures[str(apid)]['type'] = 'C'
  6488. apid += 1
  6489. # create solid_geometry
  6490. solid_geometry = []
  6491. for apid in apertures:
  6492. for geo_el in apertures[apid]['geometry']:
  6493. solid_geometry.append(geo_el['solid'])
  6494. solid_geometry = MultiPolygon(solid_geometry)
  6495. solid_geometry = solid_geometry.buffer(0.0000001)
  6496. obj_init.solid_geometry = deepcopy(solid_geometry)
  6497. obj_init.apertures = deepcopy(apertures)
  6498. # clear the working objects (perhaps not necessary due of Python GC)
  6499. apertures.clear()
  6500. if not self.collection.get_selected():
  6501. log.warning("App.convert_any2gerber --> No object selected")
  6502. self.inform.emit('[WARNING_NOTCL] %s' %
  6503. _("No object is selected. Select an object and try again."))
  6504. return
  6505. for obj in self.collection.get_selected():
  6506. obj_name = obj.options["name"]
  6507. try:
  6508. if isinstance(obj, ExcellonObject):
  6509. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  6510. elif isinstance(obj, GeometryObject):
  6511. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  6512. else:
  6513. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  6514. except Exception as e:
  6515. return "Operation failed: %s" % str(e)
  6516. def abort_all_tasks(self):
  6517. """
  6518. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  6519. on the first possible occasion.
  6520. :return:
  6521. """
  6522. if self.abort_flag is False:
  6523. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  6524. self.abort_flag = True
  6525. self.cleanup.emit()
  6526. def app_is_idle(self):
  6527. if self.abort_flag:
  6528. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  6529. self.abort_flag = False
  6530. def on_selectall(self):
  6531. """
  6532. Will draw a selection box shape around the selected objects.
  6533. :return:
  6534. """
  6535. self.report_usage("on_selectall()")
  6536. # delete the possible selection box around a possible selected object
  6537. self.delete_selection_shape()
  6538. for name in self.collection.get_names():
  6539. self.collection.set_active(name)
  6540. curr_sel_obj = self.collection.get_by_name(name)
  6541. # create the selection box around the selected object
  6542. if self.defaults['global_selection_shape'] is True:
  6543. self.draw_selection_shape(curr_sel_obj)
  6544. def on_preferences(self):
  6545. """
  6546. Adds the Preferences in a Tab in Plot Area
  6547. :return:
  6548. """
  6549. # add the tab if it was closed
  6550. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  6551. # delete the absolute and relative position and messages in the infobar
  6552. self.ui.position_label.setText("")
  6553. self.ui.rel_position_label.setText("")
  6554. # Switch plot_area to preferences page
  6555. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  6556. # self.ui.show()
  6557. # detect changes in the preferences
  6558. for idx in range(self.ui.pref_tab_area.count()):
  6559. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6560. try:
  6561. try:
  6562. tb.textEdited.disconnect(self.on_preferences_edited)
  6563. except (TypeError, AttributeError):
  6564. pass
  6565. tb.textEdited.connect(self.on_preferences_edited)
  6566. except AttributeError:
  6567. pass
  6568. try:
  6569. try:
  6570. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6571. except (TypeError, AttributeError):
  6572. pass
  6573. tb.modificationChanged.connect(self.on_preferences_edited)
  6574. except AttributeError:
  6575. pass
  6576. try:
  6577. try:
  6578. tb.toggled.disconnect(self.on_preferences_edited)
  6579. except (TypeError, AttributeError):
  6580. pass
  6581. tb.toggled.connect(self.on_preferences_edited)
  6582. except AttributeError:
  6583. pass
  6584. try:
  6585. try:
  6586. tb.valueChanged.disconnect(self.on_preferences_edited)
  6587. except (TypeError, AttributeError):
  6588. pass
  6589. tb.valueChanged.connect(self.on_preferences_edited)
  6590. except AttributeError:
  6591. pass
  6592. try:
  6593. try:
  6594. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6595. except (TypeError, AttributeError):
  6596. pass
  6597. tb.currentIndexChanged.connect(self.on_preferences_edited)
  6598. except AttributeError:
  6599. pass
  6600. def on_preferences_edited(self):
  6601. """
  6602. Executed when a preference was changed in the Edit -> Preferences tab.
  6603. Will color the Preferences tab text to Red color.
  6604. :return:
  6605. """
  6606. if self.preferences_changed_flag is False:
  6607. self.inform.emit('[WARNING_NOTCL] %s' % _("Preferences edited but not saved."))
  6608. for idx in range(self.ui.plot_tab_area.count()):
  6609. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  6610. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  6611. self.ui.pref_apply_button.setStyleSheet("QPushButton {color: red;}")
  6612. self.preferences_changed_flag = True
  6613. def on_tools_database(self, source='app'):
  6614. """
  6615. Adds the Tools Database in a Tab in Plot Area.
  6616. :return:
  6617. """
  6618. for idx in range(self.ui.plot_tab_area.count()):
  6619. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6620. # there can be only one instance of Tools Database at one time
  6621. return
  6622. if source == 'app':
  6623. self.tools_db_tab = ToolsDB2(
  6624. app=self,
  6625. parent=self.ui,
  6626. callback_on_edited=self.on_tools_db_edited,
  6627. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  6628. )
  6629. elif source == 'ncc':
  6630. self.tools_db_tab = ToolsDB2(
  6631. app=self,
  6632. parent=self.ui,
  6633. callback_on_edited=self.on_tools_db_edited,
  6634. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  6635. )
  6636. elif source == 'paint':
  6637. self.tools_db_tab = ToolsDB2(
  6638. app=self,
  6639. parent=self.ui,
  6640. callback_on_edited=self.on_tools_db_edited,
  6641. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  6642. )
  6643. # add the tab if it was closed
  6644. try:
  6645. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  6646. self.tools_db_tab.setObjectName("database_tab")
  6647. except Exception as e:
  6648. log.debug("App.on_tools_database() --> %s" % str(e))
  6649. return
  6650. # delete the absolute and relative position and messages in the infobar
  6651. self.ui.position_label.setText("")
  6652. self.ui.rel_position_label.setText("")
  6653. # Switch plot_area to preferences page
  6654. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  6655. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  6656. self.tools_db_tab.ui_connect()
  6657. def on_tools_db_edited(self):
  6658. """
  6659. Executed whenever a tool is edited in Tools Database.
  6660. Will color the text of the Tools Database tab to Red color.
  6661. :return:
  6662. """
  6663. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  6664. for idx in range(self.ui.plot_tab_area.count()):
  6665. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6666. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  6667. self.tools_db_changed_flag = True
  6668. def on_geometry_tool_add_from_db_executed(self, tool):
  6669. """
  6670. Here add the tool from DB in the selected geometry object.
  6671. :return:
  6672. """
  6673. tool_from_db = deepcopy(tool)
  6674. obj = self.collection.get_active()
  6675. if isinstance(obj, GeometryObject):
  6676. obj.on_tool_from_db_inserted(tool=tool_from_db)
  6677. # close the tab and delete it
  6678. for idx in range(self.ui.plot_tab_area.count()):
  6679. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6680. wdg = self.ui.plot_tab_area.widget(idx)
  6681. wdg.deleteLater()
  6682. self.ui.plot_tab_area.removeTab(idx)
  6683. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  6684. else:
  6685. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  6686. def on_plot_area_tab_closed(self, title):
  6687. """
  6688. Executed whenever a tab is closed in the Plot Area.
  6689. :param title: The name of the tab that was closed.
  6690. :return:
  6691. """
  6692. if title == _("Preferences"):
  6693. # disconnect
  6694. for idx in range(self.ui.pref_tab_area.count()):
  6695. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6696. try:
  6697. tb.textEdited.disconnect(self.on_preferences_edited)
  6698. except (TypeError, AttributeError):
  6699. pass
  6700. try:
  6701. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6702. except (TypeError, AttributeError):
  6703. pass
  6704. try:
  6705. tb.toggled.disconnect(self.on_preferences_edited)
  6706. except (TypeError, AttributeError):
  6707. pass
  6708. try:
  6709. tb.valueChanged.disconnect(self.on_preferences_edited)
  6710. except (TypeError, AttributeError):
  6711. pass
  6712. try:
  6713. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6714. except (TypeError, AttributeError):
  6715. pass
  6716. if self.preferences_changed_flag is True:
  6717. msgbox = QtWidgets.QMessageBox()
  6718. msgbox.setText(_("One or more values are changed.\n"
  6719. "Do you want to save the Preferences?"))
  6720. msgbox.setWindowTitle(_("Save Preferences"))
  6721. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  6722. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6723. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6724. msgbox.setDefaultButton(bt_yes)
  6725. msgbox.exec_()
  6726. response = msgbox.clickedButton()
  6727. if response == bt_yes:
  6728. self.on_save_button(save_to_file=True)
  6729. self.inform.emit('[success] %s' % _("Preferences saved."))
  6730. else:
  6731. self.preferences_changed_flag = False
  6732. self.inform.emit('')
  6733. return
  6734. if title == _("Tools Database"):
  6735. # disconnect the signals from the table widget in tab
  6736. self.tools_db_tab.ui_disconnect()
  6737. if self.tools_db_changed_flag is True:
  6738. msgbox = QtWidgets.QMessageBox()
  6739. msgbox.setText(_("One or more Tools are edited.\n"
  6740. "Do you want to update the Tools Database?"))
  6741. msgbox.setWindowTitle(_("Save Tools Database"))
  6742. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  6743. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6744. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6745. msgbox.setDefaultButton(bt_yes)
  6746. msgbox.exec_()
  6747. response = msgbox.clickedButton()
  6748. if response == bt_yes:
  6749. self.tools_db_tab.on_save_tools_db()
  6750. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  6751. else:
  6752. self.tools_db_changed_flag = False
  6753. self.inform.emit('')
  6754. return
  6755. self.tools_db_tab.deleteLater()
  6756. if title == _("Code Editor"):
  6757. self.toggle_codeeditor = False
  6758. if title == _("Bookmarks Manager"):
  6759. self.book_dialog_tab.rebuild_actions()
  6760. self.book_dialog_tab.deleteLater()
  6761. def on_flipy(self):
  6762. """
  6763. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  6764. :return:
  6765. """
  6766. self.report_usage("on_flipy()")
  6767. obj_list = self.collection.get_selected()
  6768. xminlist = []
  6769. yminlist = []
  6770. xmaxlist = []
  6771. ymaxlist = []
  6772. if not obj_list:
  6773. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  6774. else:
  6775. try:
  6776. # first get a bounding box to fit all
  6777. for obj in obj_list:
  6778. xmin, ymin, xmax, ymax = obj.bounds()
  6779. xminlist.append(xmin)
  6780. yminlist.append(ymin)
  6781. xmaxlist.append(xmax)
  6782. ymaxlist.append(ymax)
  6783. # get the minimum x,y and maximum x,y for all objects selected
  6784. xminimal = min(xminlist)
  6785. yminimal = min(yminlist)
  6786. xmaximal = max(xmaxlist)
  6787. ymaximal = max(ymaxlist)
  6788. px = 0.5 * (xminimal + xmaximal)
  6789. py = 0.5 * (yminimal + ymaximal)
  6790. # execute mirroring
  6791. for obj in obj_list:
  6792. obj.mirror('X', [px, py])
  6793. obj.plot()
  6794. self.object_changed.emit(obj)
  6795. self.inform.emit('[success] %s' %
  6796. _("Flip on Y axis done."))
  6797. except Exception as e:
  6798. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  6799. return
  6800. def on_flipx(self):
  6801. """
  6802. Executed when the menu entry in Options -> Flip on X axis is clicked.
  6803. :return:
  6804. """
  6805. self.report_usage("on_flipx()")
  6806. obj_list = self.collection.get_selected()
  6807. xminlist = []
  6808. yminlist = []
  6809. xmaxlist = []
  6810. ymaxlist = []
  6811. if not obj_list:
  6812. self.inform.emit('[WARNING_NOTCL] %s' %
  6813. _("No object selected to Flip on X axis."))
  6814. else:
  6815. try:
  6816. # first get a bounding box to fit all
  6817. for obj in obj_list:
  6818. xmin, ymin, xmax, ymax = obj.bounds()
  6819. xminlist.append(xmin)
  6820. yminlist.append(ymin)
  6821. xmaxlist.append(xmax)
  6822. ymaxlist.append(ymax)
  6823. # get the minimum x,y and maximum x,y for all objects selected
  6824. xminimal = min(xminlist)
  6825. yminimal = min(yminlist)
  6826. xmaximal = max(xmaxlist)
  6827. ymaximal = max(ymaxlist)
  6828. px = 0.5 * (xminimal + xmaximal)
  6829. py = 0.5 * (yminimal + ymaximal)
  6830. # execute mirroring
  6831. for obj in obj_list:
  6832. obj.mirror('Y', [px, py])
  6833. obj.plot()
  6834. self.object_changed.emit(obj)
  6835. self.inform.emit('[success] %s' %
  6836. _("Flip on X axis done."))
  6837. except Exception as e:
  6838. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  6839. return
  6840. def on_rotate(self, silent=False, preset=None):
  6841. """
  6842. Executed when Options -> Rotate Selection menu entry is clicked.
  6843. :param silent: If silent is True then use the preset value for the angle of the rotation.
  6844. :param preset: A value to be used as predefined angle for rotation.
  6845. :return:
  6846. """
  6847. self.report_usage("on_rotate()")
  6848. obj_list = self.collection.get_selected()
  6849. xminlist = []
  6850. yminlist = []
  6851. xmaxlist = []
  6852. ymaxlist = []
  6853. if not obj_list:
  6854. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  6855. else:
  6856. if silent is False:
  6857. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6858. min=-360, max=360, decimals=4,
  6859. init_val=float(self.defaults['tools_transform_rotate']))
  6860. num, ok = rotatebox.get_value()
  6861. else:
  6862. num = preset
  6863. ok = True
  6864. if ok:
  6865. try:
  6866. # first get a bounding box to fit all
  6867. for obj in obj_list:
  6868. xmin, ymin, xmax, ymax = obj.bounds()
  6869. xminlist.append(xmin)
  6870. yminlist.append(ymin)
  6871. xmaxlist.append(xmax)
  6872. ymaxlist.append(ymax)
  6873. # get the minimum x,y and maximum x,y for all objects selected
  6874. xminimal = min(xminlist)
  6875. yminimal = min(yminlist)
  6876. xmaximal = max(xmaxlist)
  6877. ymaximal = max(ymaxlist)
  6878. px = 0.5 * (xminimal + xmaximal)
  6879. py = 0.5 * (yminimal + ymaximal)
  6880. for sel_obj in obj_list:
  6881. sel_obj.rotate(-float(num), point=(px, py))
  6882. sel_obj.plot()
  6883. self.object_changed.emit(sel_obj)
  6884. self.inform.emit('[success] %s' %
  6885. _("Rotation done."))
  6886. except Exception as e:
  6887. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  6888. return
  6889. def on_skewx(self):
  6890. """
  6891. Executed when the menu entry in Options -> Skew on X axis is clicked.
  6892. :return:
  6893. """
  6894. self.report_usage("on_skewx()")
  6895. obj_list = self.collection.get_selected()
  6896. xminlist = []
  6897. yminlist = []
  6898. if not obj_list:
  6899. self.inform.emit('[WARNING_NOTCL] %s' %
  6900. _("No object selected to Skew/Shear on X axis."))
  6901. else:
  6902. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6903. min=-360, max=360, decimals=4,
  6904. init_val=float(self.defaults['tools_transform_skew_x']))
  6905. num, ok = skewxbox.get_value()
  6906. if ok:
  6907. # first get a bounding box to fit all
  6908. for obj in obj_list:
  6909. xmin, ymin, xmax, ymax = obj.bounds()
  6910. xminlist.append(xmin)
  6911. yminlist.append(ymin)
  6912. # get the minimum x,y and maximum x,y for all objects selected
  6913. xminimal = min(xminlist)
  6914. yminimal = min(yminlist)
  6915. for obj in obj_list:
  6916. obj.skew(num, 0, point=(xminimal, yminimal))
  6917. obj.plot()
  6918. self.object_changed.emit(obj)
  6919. self.inform.emit('[success] %s' %
  6920. _("Skew on X axis done."))
  6921. def on_skewy(self):
  6922. """
  6923. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  6924. :return:
  6925. """
  6926. self.report_usage("on_skewy()")
  6927. obj_list = self.collection.get_selected()
  6928. xminlist = []
  6929. yminlist = []
  6930. if not obj_list:
  6931. self.inform.emit('[WARNING_NOTCL] %s' %
  6932. _("No object selected to Skew/Shear on Y axis."))
  6933. else:
  6934. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6935. min=-360, max=360, decimals=4,
  6936. init_val=float(self.defaults['tools_transform_skew_y']))
  6937. num, ok = skewybox.get_value()
  6938. if ok:
  6939. # first get a bounding box to fit all
  6940. for obj in obj_list:
  6941. xmin, ymin, xmax, ymax = obj.bounds()
  6942. xminlist.append(xmin)
  6943. yminlist.append(ymin)
  6944. # get the minimum x,y and maximum x,y for all objects selected
  6945. xminimal = min(xminlist)
  6946. yminimal = min(yminlist)
  6947. for obj in obj_list:
  6948. obj.skew(0, num, point=(xminimal, yminimal))
  6949. obj.plot()
  6950. self.object_changed.emit(obj)
  6951. self.inform.emit('[success] %s' %
  6952. _("Skew on Y axis done."))
  6953. def on_plots_updated(self):
  6954. """
  6955. Callback used to report when the plots have changed.
  6956. Adjust axes and zooms to fit.
  6957. :return: None
  6958. """
  6959. if self.is_legacy is False:
  6960. self.plotcanvas.update()
  6961. else:
  6962. self.plotcanvas.auto_adjust_axes()
  6963. self.on_zoom_fit(None)
  6964. self.collection.update_view()
  6965. # self.inform.emit(_("Plots updated ..."))
  6966. def on_toolbar_replot(self):
  6967. """
  6968. Callback for toolbar button. Re-plots all objects.
  6969. :return: None
  6970. """
  6971. self.report_usage("on_toolbar_replot")
  6972. self.log.debug("on_toolbar_replot()")
  6973. try:
  6974. self.collection.get_active().read_form()
  6975. except AttributeError:
  6976. self.log.debug("on_toolbar_replot(): AttributeError")
  6977. pass
  6978. self.plot_all()
  6979. def on_row_activated(self, index):
  6980. if index.isValid():
  6981. if index.internalPointer().parent_item != self.collection.root_item:
  6982. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6983. self.collection.on_item_activated(index)
  6984. def on_row_selected(self, obj_name):
  6985. """
  6986. This is a special string; when received it will make all Menu -> Objects entries unchecked
  6987. It mean we clicked outside of the items and deselected all
  6988. :param obj_name:
  6989. :return:
  6990. """
  6991. if obj_name == 'none':
  6992. for act in self.ui.menuobjects.actions():
  6993. act.setChecked(False)
  6994. return
  6995. # get the name of the selected objects and add them to a list
  6996. name_list = []
  6997. for obj in self.collection.get_selected():
  6998. name_list.append(obj.options['name'])
  6999. # set all actions as unchecked but the ones selected make them checked
  7000. for act in self.ui.menuobjects.actions():
  7001. act.setChecked(False)
  7002. if act.text() in name_list:
  7003. act.setChecked(True)
  7004. def on_collection_updated(self, obj, state, old_name):
  7005. """
  7006. Create a menu from the object loaded in the collection.
  7007. :param obj: object that was changed (added, deleted, renamed)
  7008. :param state: what was done with the object. Can be: added, deleted, delete_all, renamed
  7009. :param old_name: the old name of the object before the action that triggered this slot happened
  7010. :return: None
  7011. """
  7012. icon_files = {
  7013. "gerber": self.resource_location + "/flatcam_icon16.png",
  7014. "excellon": self.resource_location + "/drill16.png",
  7015. "cncjob": self.resource_location + "/cnc16.png",
  7016. "geometry": self.resource_location + "/geometry16.png",
  7017. "script": self.resource_location + "/script_new16.png",
  7018. "document": self.resource_location + "/notes16_1.png"
  7019. }
  7020. if state == 'append':
  7021. for act in self.ui.menuobjects.actions():
  7022. try:
  7023. act.triggered.disconnect()
  7024. except TypeError:
  7025. pass
  7026. self.ui.menuobjects.clear()
  7027. gerber_list = []
  7028. exc_list = []
  7029. cncjob_list = []
  7030. geo_list = []
  7031. script_list = []
  7032. doc_list = []
  7033. for name in self.collection.get_names():
  7034. obj_named = self.collection.get_by_name(name)
  7035. if obj_named.kind == 'gerber':
  7036. gerber_list.append(name)
  7037. elif obj_named.kind == 'excellon':
  7038. exc_list.append(name)
  7039. elif obj_named.kind == 'cncjob':
  7040. cncjob_list.append(name)
  7041. elif obj_named.kind == 'geometry':
  7042. geo_list.append(name)
  7043. elif obj_named.kind == 'script':
  7044. script_list.append(name)
  7045. elif obj_named.kind == 'document':
  7046. doc_list.append(name)
  7047. def add_act(o_name):
  7048. obj_for_icon = self.collection.get_by_name(o_name)
  7049. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  7050. add_action.setCheckable(True)
  7051. add_action.setText(o_name)
  7052. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  7053. add_action.triggered.connect(
  7054. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  7055. self.collection.set_inactive(o_name))
  7056. self.ui.menuobjects.addAction(add_action)
  7057. for name in gerber_list:
  7058. add_act(name)
  7059. self.ui.menuobjects.addSeparator()
  7060. for name in exc_list:
  7061. add_act(name)
  7062. self.ui.menuobjects.addSeparator()
  7063. for name in cncjob_list:
  7064. add_act(name)
  7065. self.ui.menuobjects.addSeparator()
  7066. for name in geo_list:
  7067. add_act(name)
  7068. self.ui.menuobjects.addSeparator()
  7069. for name in script_list:
  7070. add_act(name)
  7071. self.ui.menuobjects.addSeparator()
  7072. for name in doc_list:
  7073. add_act(name)
  7074. self.ui.menuobjects.addSeparator()
  7075. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  7076. QtGui.QIcon(self.resource_location + '/select_all.png'),
  7077. _('Select All')
  7078. )
  7079. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  7080. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  7081. _('Deselect All')
  7082. )
  7083. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  7084. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  7085. elif state == 'delete':
  7086. for act in self.ui.menuobjects.actions():
  7087. if act.text() == obj.options['name']:
  7088. try:
  7089. act.triggered.disconnect()
  7090. except TypeError:
  7091. pass
  7092. self.ui.menuobjects.removeAction(act)
  7093. break
  7094. elif state == 'rename':
  7095. for act in self.ui.menuobjects.actions():
  7096. if act.text() == old_name:
  7097. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  7098. add_action.setText(obj.options['name'])
  7099. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  7100. add_action.triggered.connect(
  7101. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  7102. self.collection.set_inactive(obj.options['name']))
  7103. self.ui.menuobjects.insertAction(act, add_action)
  7104. try:
  7105. act.triggered.disconnect()
  7106. except TypeError:
  7107. pass
  7108. self.ui.menuobjects.removeAction(act)
  7109. break
  7110. elif state == 'delete_all':
  7111. for act in self.ui.menuobjects.actions():
  7112. try:
  7113. act.triggered.disconnect()
  7114. except TypeError:
  7115. pass
  7116. self.ui.menuobjects.clear()
  7117. self.ui.menuobjects.addSeparator()
  7118. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  7119. QtGui.QIcon(self.resource_location + '/select_all.png'),
  7120. _('Select All')
  7121. )
  7122. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  7123. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  7124. _('Deselect All')
  7125. )
  7126. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  7127. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  7128. def on_objects_selection(self, on_off):
  7129. obj_list = self.collection.get_names()
  7130. if on_off is True:
  7131. self.collection.set_all_active()
  7132. for act in self.ui.menuobjects.actions():
  7133. try:
  7134. act.setChecked(True)
  7135. except Exception:
  7136. pass
  7137. if obj_list:
  7138. self.inform.emit('[selected] %s' % _("All objects are selected."))
  7139. else:
  7140. self.collection.set_all_inactive()
  7141. for act in self.ui.menuobjects.actions():
  7142. try:
  7143. act.setChecked(False)
  7144. except Exception:
  7145. pass
  7146. if obj_list:
  7147. self.inform.emit('%s' % _("Objects selection is cleared."))
  7148. else:
  7149. self.inform.emit('')
  7150. def grid_status(self):
  7151. if self.ui.grid_snap_btn.isChecked():
  7152. return True
  7153. else:
  7154. return False
  7155. def populate_cmenu_grids(self):
  7156. units = self.defaults['units'].lower()
  7157. # for act in self.ui.cmenu_gridmenu.actions():
  7158. # act.triggered.disconnect()
  7159. self.ui.cmenu_gridmenu.clear()
  7160. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  7161. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  7162. _("Grid On/Off"))
  7163. grid_toggle.setCheckable(True)
  7164. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  7165. self.ui.cmenu_gridmenu.addSeparator()
  7166. for grid in sorted_list:
  7167. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  7168. "%s" % str(grid))
  7169. action.triggered.connect(self.set_grid)
  7170. self.ui.cmenu_gridmenu.addSeparator()
  7171. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  7172. _("Add"))
  7173. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  7174. _("Delete"))
  7175. grid_add.triggered.connect(self.on_grid_add)
  7176. grid_delete.triggered.connect(self.on_grid_delete)
  7177. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  7178. def set_grid(self):
  7179. menu_action = self.sender()
  7180. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  7181. self.ui.grid_gap_x_entry.setText(menu_action.text())
  7182. self.ui.grid_gap_y_entry.setText(menu_action.text())
  7183. def on_grid_add(self):
  7184. # ## Current application units in lower Case
  7185. units = self.defaults['units'].lower()
  7186. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  7187. text=_('Enter a Grid Value:'),
  7188. min=0.0000, max=99.9999, decimals=4)
  7189. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  7190. val, ok = grid_add_popup.get_value()
  7191. if ok:
  7192. if float(val) == 0:
  7193. self.inform.emit('[WARNING_NOTCL] %s' %
  7194. _("Please enter a grid value with non-zero value, in Float format."))
  7195. return
  7196. else:
  7197. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  7198. self.defaults["global_grid_context_menu"][str(units)].append(val)
  7199. self.inform.emit('[success] %s...' %
  7200. _("New Grid added"))
  7201. else:
  7202. self.inform.emit('[WARNING_NOTCL] %s...' %
  7203. _("Grid already exists"))
  7204. else:
  7205. self.inform.emit('[WARNING_NOTCL] %s...' %
  7206. _("Adding New Grid cancelled"))
  7207. def on_grid_delete(self):
  7208. # ## Current application units in lower Case
  7209. units = self.defaults['units'].lower()
  7210. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  7211. text='Enter a Grid Value:',
  7212. min=0.0000, max=99.9999, decimals=4)
  7213. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  7214. val, ok = grid_del_popup.get_value()
  7215. if ok:
  7216. if float(val) == 0:
  7217. self.inform.emit('[WARNING_NOTCL] %s' %
  7218. _("Please enter a grid value with non-zero value, in Float format."))
  7219. return
  7220. else:
  7221. try:
  7222. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  7223. except ValueError:
  7224. self.inform.emit('[ERROR_NOTCL]%s...' %
  7225. _(" Grid Value does not exist"))
  7226. return
  7227. self.inform.emit('[success] %s...' %
  7228. _("Grid Value deleted"))
  7229. else:
  7230. self.inform.emit('[WARNING_NOTCL] %s...' %
  7231. _("Delete Grid value cancelled"))
  7232. def on_shortcut_list(self):
  7233. self.report_usage("on_shortcut_list()")
  7234. # add the tab if it was closed
  7235. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  7236. # delete the absolute and relative position and messages in the infobar
  7237. self.ui.position_label.setText("")
  7238. self.ui.rel_position_label.setText("")
  7239. # Switch plot_area to preferences page
  7240. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  7241. # self.ui.show()
  7242. def on_select_tab(self, name):
  7243. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  7244. if self.ui.splitter.sizes()[0] == 0:
  7245. self.ui.splitter.setSizes([1, 1])
  7246. else:
  7247. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  7248. self.ui.splitter.setSizes([0, 1])
  7249. if name == 'project':
  7250. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7251. elif name == 'selected':
  7252. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  7253. elif name == 'tool':
  7254. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  7255. def on_copy_name(self):
  7256. self.report_usage("on_copy_name()")
  7257. obj = self.collection.get_active()
  7258. try:
  7259. name = obj.options["name"]
  7260. except AttributeError:
  7261. log.debug("on_copy_name() --> No object selected to copy it's name")
  7262. self.inform.emit('[WARNING_NOTCL]%s' %
  7263. _(" No object selected to copy it's name"))
  7264. return
  7265. self.clipboard.setText(name)
  7266. self.inform.emit(_("Name copied on clipboard ..."))
  7267. def on_mouse_click_over_plot(self, event):
  7268. """
  7269. Default actions are:
  7270. :param event: Contains information about the event, like which button
  7271. was clicked, the pixel coordinates and the axes coordinates.
  7272. :return: None
  7273. """
  7274. self.pos = []
  7275. if self.is_legacy is False:
  7276. event_pos = event.pos
  7277. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  7278. # # Set the mouse button for panning
  7279. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  7280. else:
  7281. event_pos = (event.xdata, event.ydata)
  7282. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7283. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  7284. # So it can receive key presses
  7285. self.plotcanvas.native.setFocus()
  7286. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7287. if self.grid_status():
  7288. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  7289. else:
  7290. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  7291. try:
  7292. if event.button == 1:
  7293. # Reset here the relative coordinates so there is a new reference on the click position
  7294. if self.rel_point1 is None:
  7295. self.rel_point1 = self.pos
  7296. else:
  7297. self.rel_point2 = copy(self.rel_point1)
  7298. self.rel_point1 = self.pos
  7299. self.on_mouse_move_over_plot(event, origin_click=True)
  7300. except Exception as e:
  7301. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  7302. def on_mouse_double_click_over_plot(self, event):
  7303. if event.button == 1:
  7304. self.doubleclick = True
  7305. def on_mouse_move_over_plot(self, event, origin_click=None):
  7306. """
  7307. Callback for the mouse motion event over the plot.
  7308. :param event: Contains information about the event.
  7309. :param origin_click
  7310. :return: None
  7311. """
  7312. if self.is_legacy is False:
  7313. event_pos = event.pos
  7314. if self.defaults["global_pan_button"] == '2':
  7315. pan_button = 2
  7316. else:
  7317. pan_button = 3
  7318. self.event_is_dragging = event.is_dragging
  7319. else:
  7320. event_pos = (event.xdata, event.ydata)
  7321. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7322. if self.defaults["global_pan_button"] == '2':
  7323. pan_button = 3
  7324. else:
  7325. pan_button = 2
  7326. self.event_is_dragging = self.plotcanvas.is_dragging
  7327. # So it can receive key presses but not when the Tcl Shell is active
  7328. if not self.ui.shell_dock.isVisible():
  7329. if not self.plotcanvas.native.hasFocus():
  7330. self.plotcanvas.native.setFocus()
  7331. self.pos_jump = event_pos
  7332. self.ui.popMenu.mouse_is_panning = False
  7333. if origin_click is None:
  7334. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  7335. if event.button == pan_button and self.event_is_dragging == 1:
  7336. # if a popup menu is active don't change mouse_is_panning variable because is not True
  7337. if self.ui.popMenu.popup_active:
  7338. self.ui.popMenu.popup_active = False
  7339. return
  7340. self.ui.popMenu.mouse_is_panning = True
  7341. return
  7342. if self.rel_point1 is not None:
  7343. try: # May fail in case mouse not within axes
  7344. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7345. if self.grid_status():
  7346. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  7347. # Update cursor
  7348. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  7349. symbol='++', edge_color=self.cursor_color_3D,
  7350. edge_width=self.defaults["global_cursor_width"],
  7351. size=self.defaults["global_cursor_size"])
  7352. else:
  7353. pos = (pos_canvas[0], pos_canvas[1])
  7354. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  7355. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  7356. self.dx = pos[0] - float(self.rel_point1[0])
  7357. self.dy = pos[1] - float(self.rel_point1[1])
  7358. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  7359. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  7360. self.mouse = [pos[0], pos[1]]
  7361. # if the mouse is moved and the LMB is clicked then the action is a selection
  7362. if self.event_is_dragging == 1 and event.button == 1:
  7363. self.delete_selection_shape()
  7364. if self.dx < 0:
  7365. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  7366. face_color=self.defaults['global_alt_sel_fill'])
  7367. self.selection_type = False
  7368. elif self.dx >= 0:
  7369. self.draw_moving_selection_shape(self.pos, pos)
  7370. self.selection_type = True
  7371. else:
  7372. self.selection_type = None
  7373. else:
  7374. self.selection_type = None
  7375. # hover effect - enabled in Preferences -> General -> GUI Settings
  7376. if self.defaults['global_hover']:
  7377. for obj in self.collection.get_list():
  7378. try:
  7379. # select the object(s) only if it is enabled (plotted)
  7380. if obj.options['plot']:
  7381. if obj not in self.collection.get_selected():
  7382. poly_obj = Polygon(
  7383. [(obj.options['xmin'], obj.options['ymin']),
  7384. (obj.options['xmax'], obj.options['ymin']),
  7385. (obj.options['xmax'], obj.options['ymax']),
  7386. (obj.options['xmin'], obj.options['ymax'])]
  7387. )
  7388. if Point(pos).within(poly_obj):
  7389. if obj.isHovering is False:
  7390. obj.isHovering = True
  7391. obj.notHovering = True
  7392. # create the selection box around the selected object
  7393. self.draw_hover_shape(obj, color='#d1e0e0FF')
  7394. else:
  7395. if obj.notHovering is True:
  7396. obj.notHovering = False
  7397. obj.isHovering = False
  7398. self.delete_hover_shape()
  7399. except Exception:
  7400. # the Exception here will happen if we try to select on screen and we have an
  7401. # newly (and empty) just created Geometry or Excellon object that do not have the
  7402. # xmin, xmax, ymin, ymax options.
  7403. # In this case poly_obj creation (see above) will fail
  7404. pass
  7405. except Exception:
  7406. self.ui.position_label.setText("")
  7407. self.ui.rel_position_label.setText("")
  7408. self.mouse = None
  7409. def on_mouse_click_release_over_plot(self, event):
  7410. """
  7411. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  7412. and has been registered in ''self.__init__()''.
  7413. :param event: contains information about the event.
  7414. :return:
  7415. """
  7416. if self.is_legacy is False:
  7417. event_pos = event.pos
  7418. right_button = 2
  7419. else:
  7420. event_pos = (event.xdata, event.ydata)
  7421. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7422. right_button = 3
  7423. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7424. if self.grid_status():
  7425. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  7426. else:
  7427. pos = (pos_canvas[0], pos_canvas[1])
  7428. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  7429. # canvas menu
  7430. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  7431. self.ui.popMenu.mouse_is_panning = False
  7432. self.cursor = QtGui.QCursor()
  7433. self.populate_cmenu_grids()
  7434. self.ui.popMenu.popup(self.cursor.pos())
  7435. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  7436. # selection and then select a type of selection ("enclosing" or "touching")
  7437. if event.button == 1: # left click
  7438. modifiers = QtWidgets.QApplication.keyboardModifiers()
  7439. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  7440. if modifiers == QtCore.Qt.ShiftModifier:
  7441. # do not auto open the Project Tab
  7442. self.click_noproject = True
  7443. self.clipboard.setText(
  7444. self.defaults["global_point_clipboard_format"] %
  7445. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  7446. )
  7447. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  7448. return
  7449. if self.doubleclick is True:
  7450. self.doubleclick = False
  7451. if self.collection.get_selected():
  7452. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  7453. if self.ui.splitter.sizes()[0] == 0:
  7454. self.ui.splitter.setSizes([1, 1])
  7455. try:
  7456. # delete the selection shape(S) as it may be in the way
  7457. self.delete_selection_shape()
  7458. self.delete_hover_shape()
  7459. except Exception as e:
  7460. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  7461. return
  7462. else:
  7463. # WORKAROUND for LEGACY MODE
  7464. if self.is_legacy is True:
  7465. # if there is no move on canvas then we have no dragging selection
  7466. if self.dx == 0 or self.dy == 0:
  7467. self.selection_type = None
  7468. if self.selection_type is not None:
  7469. try:
  7470. self.selection_area_handler(self.pos, pos, self.selection_type)
  7471. self.selection_type = None
  7472. except Exception as e:
  7473. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  7474. return
  7475. else:
  7476. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  7477. if key_modifier == QtCore.Qt.ShiftModifier:
  7478. mod_key = 'Shift'
  7479. elif key_modifier == QtCore.Qt.ControlModifier:
  7480. mod_key = 'Control'
  7481. else:
  7482. mod_key = None
  7483. try:
  7484. if mod_key == self.defaults["global_mselect_key"]:
  7485. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  7486. # deselect, and if it's not selected then it will be selected
  7487. # If there is no active command (self.command_active is None) then we check if we clicked
  7488. # on a object by checking the bounding limits against mouse click position
  7489. if self.command_active is None:
  7490. self.select_objects(key='multisel')
  7491. self.delete_hover_shape()
  7492. else:
  7493. # If there is no active command (self.command_active is None) then we check if we clicked
  7494. # on a object by checking the bounding limits against mouse click position
  7495. if self.command_active is None:
  7496. self.select_objects()
  7497. self.delete_hover_shape()
  7498. except Exception as e:
  7499. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  7500. return
  7501. def selection_area_handler(self, start_pos, end_pos, sel_type):
  7502. """
  7503. :param start_pos: mouse position when the selection LMB click was done
  7504. :param end_pos: mouse position when the left mouse button is released
  7505. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  7506. :return:
  7507. """
  7508. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  7509. # delete previous selection shape
  7510. self.delete_selection_shape()
  7511. # make all objects inactive
  7512. self.collection.set_all_inactive()
  7513. for obj in self.collection.get_list():
  7514. try:
  7515. # select the object(s) only if it is enabled (plotted)
  7516. if obj.options['plot']:
  7517. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  7518. (obj.options['xmax'], obj.options['ymin']),
  7519. (obj.options['xmax'], obj.options['ymax']),
  7520. (obj.options['xmin'], obj.options['ymax'])])
  7521. if sel_type is True:
  7522. if poly_obj.within(poly_selection):
  7523. # create the selection box around the selected object
  7524. if self.defaults['global_selection_shape'] is True:
  7525. self.draw_selection_shape(obj)
  7526. self.collection.set_active(obj.options['name'])
  7527. else:
  7528. if poly_selection.intersects(poly_obj):
  7529. # create the selection box around the selected object
  7530. if self.defaults['global_selection_shape'] is True:
  7531. self.draw_selection_shape(obj)
  7532. self.collection.set_active(obj.options['name'])
  7533. obj.selection_shape_drawn = True
  7534. except Exception as e:
  7535. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  7536. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  7537. # In this case poly_obj creation (see above) will fail
  7538. log.debug("App.selection_area_handler() --> %s" % str(e))
  7539. def select_objects(self, key=None):
  7540. """
  7541. Will select objects clicked on canvas
  7542. :param key: for future use in cumulative selection
  7543. :return:
  7544. """
  7545. # list where we store the overlapped objects under our mouse left click position
  7546. if key is None:
  7547. self.objects_under_the_click_list = []
  7548. # Populate the list with the overlapped objects on the click position
  7549. curr_x, curr_y = self.pos
  7550. for obj in self.all_objects_list:
  7551. # ScriptObject and DocumentObject objects can't be selected
  7552. if isinstance(obj, ScriptObject) or isinstance(obj, DocumentObject):
  7553. continue
  7554. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  7555. continue
  7556. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  7557. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  7558. if obj.options['name'] not in self.objects_under_the_click_list:
  7559. if obj.options['plot']:
  7560. # add objects to the objects_under_the_click list only if the object is plotted
  7561. # (active and not disabled)
  7562. self.objects_under_the_click_list.append(obj.options['name'])
  7563. try:
  7564. if self.objects_under_the_click_list:
  7565. curr_sel_obj = self.collection.get_active()
  7566. # case when there is only an object under the click and we toggle it
  7567. if len(self.objects_under_the_click_list) == 1:
  7568. if curr_sel_obj is None:
  7569. self.collection.set_active(self.objects_under_the_click_list[0])
  7570. curr_sel_obj = self.collection.get_active()
  7571. # create the selection box around the selected object
  7572. if self.defaults['global_selection_shape'] is True:
  7573. self.draw_selection_shape(curr_sel_obj)
  7574. curr_sel_obj.selection_shape_drawn = True
  7575. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  7576. self.on_objects_selection(False)
  7577. self.delete_selection_shape()
  7578. curr_sel_obj.selection_shape_drawn = False
  7579. self.collection.set_active(self.objects_under_the_click_list[0])
  7580. curr_sel_obj = self.collection.get_active()
  7581. # create the selection box around the selected object
  7582. if self.defaults['global_selection_shape'] is True:
  7583. self.draw_selection_shape(curr_sel_obj)
  7584. curr_sel_obj.selection_shape_drawn = True
  7585. self.selected_message(curr_sel_obj=curr_sel_obj)
  7586. elif curr_sel_obj.selection_shape_drawn is False:
  7587. if self.defaults['global_selection_shape'] is True:
  7588. self.draw_selection_shape(curr_sel_obj)
  7589. curr_sel_obj.selection_shape_drawn = True
  7590. else:
  7591. self.on_objects_selection(False)
  7592. self.delete_selection_shape()
  7593. if self.call_source != 'app':
  7594. self.call_source = 'app'
  7595. self.selected_message(curr_sel_obj=curr_sel_obj)
  7596. else:
  7597. # If there is no selected object
  7598. # make active the first element of the overlapped objects list
  7599. if self.collection.get_active() is None:
  7600. self.collection.set_active(self.objects_under_the_click_list[0])
  7601. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  7602. name_sel_obj = self.collection.get_active().options['name']
  7603. # In case that there is a selected object but it is not in the overlapped object list
  7604. # make that object inactive and activate the first element in the overlapped object list
  7605. if name_sel_obj not in self.objects_under_the_click_list:
  7606. self.collection.set_inactive(name_sel_obj)
  7607. name_sel_obj = self.objects_under_the_click_list[0]
  7608. self.collection.set_active(name_sel_obj)
  7609. else:
  7610. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  7611. self.collection.set_all_inactive()
  7612. self.collection.set_active(
  7613. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  7614. curr_sel_obj = self.collection.get_active()
  7615. # delete the possible selection box around a possible selected object
  7616. self.delete_selection_shape()
  7617. curr_sel_obj.selection_shape_drawn = False
  7618. # create the selection box around the selected object
  7619. if self.defaults['global_selection_shape'] is True:
  7620. self.draw_selection_shape(curr_sel_obj)
  7621. curr_sel_obj.selection_shape_drawn = True
  7622. self.selected_message(curr_sel_obj=curr_sel_obj)
  7623. else:
  7624. # deselect everything
  7625. self.on_objects_selection(False)
  7626. # delete the possible selection box around a possible selected object
  7627. self.delete_selection_shape()
  7628. for o in self.collection.get_list():
  7629. o.selection_shape_drawn = False
  7630. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  7631. # only when working on App
  7632. if self.call_source == 'app':
  7633. if self.click_noproject is False:
  7634. # if the Tool Tab is in focus don't change focus to Project Tab
  7635. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  7636. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7637. else:
  7638. # restore auto open the Project Tab
  7639. self.click_noproject = False
  7640. # delete any text in the status bar, implicitly the last object name that was selected
  7641. # self.inform.emit("")
  7642. else:
  7643. self.call_source = 'app'
  7644. except Exception as e:
  7645. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  7646. def selected_message(self, curr_sel_obj):
  7647. if curr_sel_obj:
  7648. if curr_sel_obj.kind == 'gerber':
  7649. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  7650. color='green',
  7651. name=str(curr_sel_obj.options['name']),
  7652. tx=_("selected"))
  7653. )
  7654. elif curr_sel_obj.kind == 'excellon':
  7655. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  7656. color='brown',
  7657. name=str(curr_sel_obj.options['name']),
  7658. tx=_("selected"))
  7659. )
  7660. elif curr_sel_obj.kind == 'cncjob':
  7661. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  7662. color='blue',
  7663. name=str(curr_sel_obj.options['name']),
  7664. tx=_("selected"))
  7665. )
  7666. elif curr_sel_obj.kind == 'geometry':
  7667. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  7668. color='red',
  7669. name=str(curr_sel_obj.options['name']),
  7670. tx=_("selected"))
  7671. )
  7672. def delete_hover_shape(self):
  7673. self.hover_shapes.clear()
  7674. self.hover_shapes.redraw()
  7675. def draw_hover_shape(self, sel_obj, color=None):
  7676. """
  7677. :param sel_obj: The object for which the hover shape must be drawn
  7678. :param color: The color of the hover shape
  7679. :return: None
  7680. """
  7681. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7682. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7683. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7684. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7685. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  7686. if self.defaults['units'].upper() == 'MM':
  7687. hover_rect = hover_rect.buffer(-0.1)
  7688. hover_rect = hover_rect.buffer(0.2)
  7689. else:
  7690. hover_rect = hover_rect.buffer(-0.00393)
  7691. hover_rect = hover_rect.buffer(0.00787)
  7692. # if color:
  7693. # face = Color(color)
  7694. # face.alpha = 0.2
  7695. # outline = Color(color, alpha=0.8)
  7696. # else:
  7697. # face = Color(self.defaults['global_sel_fill'])
  7698. # face.alpha = 0.2
  7699. # outline = self.defaults['global_sel_line']
  7700. if color:
  7701. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7702. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7703. else:
  7704. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7705. outline = self.defaults['global_sel_line']
  7706. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  7707. if self.is_legacy is True:
  7708. self.hover_shapes.redraw()
  7709. def delete_selection_shape(self):
  7710. self.move_tool.sel_shapes.clear()
  7711. self.move_tool.sel_shapes.redraw()
  7712. def draw_selection_shape(self, sel_obj, color=None):
  7713. """
  7714. Will draw a selection shape around the selected object.
  7715. :param sel_obj: The object for which the selection shape must be drawn
  7716. :param color: The color for the selection shape.
  7717. :return: None
  7718. """
  7719. if sel_obj is None:
  7720. return
  7721. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7722. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7723. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7724. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7725. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7726. if self.defaults['units'].upper() == 'MM':
  7727. sel_rect = sel_rect.buffer(-0.1)
  7728. sel_rect = sel_rect.buffer(0.2)
  7729. else:
  7730. sel_rect = sel_rect.buffer(-0.00393)
  7731. sel_rect = sel_rect.buffer(0.00787)
  7732. if color:
  7733. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7734. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7735. else:
  7736. if self.is_legacy is False:
  7737. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7738. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  7739. else:
  7740. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  7741. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  7742. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  7743. color=outline,
  7744. face_color=face,
  7745. update=True,
  7746. layer=0,
  7747. tolerance=None))
  7748. if self.is_legacy is True:
  7749. self.move_tool.sel_shapes.redraw()
  7750. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  7751. """
  7752. Will draw a selection shape when dragging mouse on canvas.
  7753. :param old_coords: Old coordinates
  7754. :param coords: New coordinates
  7755. :param kwargs: Keyword arguments
  7756. :return:
  7757. """
  7758. if 'color' in kwargs:
  7759. color = kwargs['color']
  7760. else:
  7761. color = self.defaults['global_sel_line']
  7762. if 'face_color' in kwargs:
  7763. face_color = kwargs['face_color']
  7764. else:
  7765. face_color = self.defaults['global_sel_fill']
  7766. if 'face_alpha' in kwargs:
  7767. face_alpha = kwargs['face_alpha']
  7768. else:
  7769. face_alpha = 0.3
  7770. x0, y0 = old_coords
  7771. x1, y1 = coords
  7772. pt1 = (x0, y0)
  7773. pt2 = (x1, y0)
  7774. pt3 = (x1, y1)
  7775. pt4 = (x0, y1)
  7776. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7777. # color_t = Color(face_color)
  7778. # color_t.alpha = face_alpha
  7779. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  7780. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  7781. layer=0, tolerance=None)
  7782. if self.is_legacy is True:
  7783. self.move_tool.sel_shapes.redraw()
  7784. def on_file_new_click(self):
  7785. """
  7786. Callback for menu item File -> New.
  7787. Executed on clicking the Menu -> File -> New Project
  7788. :return:
  7789. """
  7790. if self.collection.get_list() and self.should_we_save:
  7791. msgbox = QtWidgets.QMessageBox()
  7792. # msgbox.setText("<B>Save changes ...</B>")
  7793. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7794. "Creating a New project will delete them.\n"
  7795. "Do you want to Save the project?"))
  7796. msgbox.setWindowTitle(_("Save changes"))
  7797. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  7798. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7799. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7800. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7801. msgbox.setDefaultButton(bt_yes)
  7802. msgbox.exec_()
  7803. response = msgbox.clickedButton()
  7804. if response == bt_yes:
  7805. self.on_file_saveprojectas()
  7806. elif response == bt_cancel:
  7807. return
  7808. elif response == bt_no:
  7809. self.on_file_new()
  7810. else:
  7811. self.on_file_new()
  7812. self.inform.emit('[success] %s...' % _("New Project created"))
  7813. def on_file_new(self, cli=None):
  7814. """
  7815. Returns the application to its startup state. This method is thread-safe.
  7816. :param cli: Boolean. If True this method was run from command line
  7817. :return: None
  7818. """
  7819. self.report_usage("on_file_new")
  7820. # Remove everything from memory
  7821. App.log.debug("on_file_new()")
  7822. if self.call_source != 'app':
  7823. self.editor2object(cleanup=True)
  7824. # ## EDITOR section
  7825. self.geo_editor = FlatCAMGeoEditor(self)
  7826. self.exc_editor = FlatCAMExcEditor(self)
  7827. self.grb_editor = FlatCAMGrbEditor(self)
  7828. # Clear pool
  7829. self.clear_pool()
  7830. for obj in self.collection.get_list():
  7831. # delete shapes left drawn from mark shape_collections, if any
  7832. if isinstance(obj, GerberObject):
  7833. try:
  7834. for el in obj.mark_shapes:
  7835. obj.mark_shapes[el].clear(update=True)
  7836. obj.mark_shapes[el].enabled = False
  7837. del el
  7838. except AttributeError:
  7839. pass
  7840. # also delete annotation shapes, if any
  7841. elif isinstance(obj, CNCJobObject):
  7842. try:
  7843. obj.text_col.enabled = False
  7844. del obj.text_col
  7845. obj.annotation.clear(update=True)
  7846. del obj.annotation
  7847. except AttributeError:
  7848. pass
  7849. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7850. self.shell.init_tcl()
  7851. self.delete_selection_shape()
  7852. self.collection.delete_all()
  7853. self.setup_component_editor()
  7854. # Clear project filename
  7855. self.project_filename = None
  7856. # Load the application defaults
  7857. self.load_defaults(filename='current_defaults')
  7858. # Re-fresh project options
  7859. self.on_options_app2project()
  7860. # Init Tools
  7861. self.init_tools()
  7862. if cli is None:
  7863. # Close any Tabs opened in the Plot Tab Area section
  7864. for index in range(self.ui.plot_tab_area.count()):
  7865. self.ui.plot_tab_area.closeTab(index)
  7866. # for whatever reason previous command does not close the last tab so I do it manually
  7867. self.ui.plot_tab_area.closeTab(0)
  7868. # # And then add again the Plot Area
  7869. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  7870. self.ui.plot_tab_area.protectTab(0)
  7871. # take the focus of the Notebook on Project Tab.
  7872. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7873. self.set_ui_title(name=_("New Project - Not saved"))
  7874. def obj_properties(self):
  7875. """
  7876. Will launch the object Properties Tool
  7877. :return:
  7878. """
  7879. self.report_usage("obj_properties()")
  7880. self.properties_tool.run(toggle=False)
  7881. def on_project_context_save(self):
  7882. """
  7883. Wrapper, will save the object function of it's type
  7884. :return:
  7885. """
  7886. obj = self.collection.get_active()
  7887. if type(obj) == GeometryObject:
  7888. self.on_file_exportdxf()
  7889. elif type(obj) == ExcellonObject:
  7890. self.on_file_saveexcellon()
  7891. elif type(obj) == CNCJobObject:
  7892. obj.on_exportgcode_button_click()
  7893. elif type(obj) == GerberObject:
  7894. self.on_file_savegerber()
  7895. elif type(obj) == ScriptObject:
  7896. self.on_file_savescript()
  7897. elif type(obj) == DocumentObject:
  7898. self.on_file_savedocument()
  7899. def obj_move(self):
  7900. """
  7901. Callback for the Move menu entry in various Context Menu's.
  7902. :return:
  7903. """
  7904. self.report_usage("obj_move()")
  7905. self.move_tool.run(toggle=False)
  7906. def on_fileopengerber(self, signal, name=None):
  7907. """
  7908. File menu callback for opening a Gerber.
  7909. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7910. :param name:
  7911. :return: None
  7912. """
  7913. self.report_usage("on_fileopengerber")
  7914. App.log.debug("on_fileopengerber()")
  7915. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  7916. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  7917. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  7918. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  7919. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  7920. "*.mil);;" \
  7921. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  7922. "Allegro Files (*.art);;" \
  7923. "Mentor Files (*.pho *.gdo);;" \
  7924. "All Files (*.*)"
  7925. if name is None:
  7926. try:
  7927. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  7928. directory=self.get_last_folder(),
  7929. filter=_filter_)
  7930. except TypeError:
  7931. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  7932. filenames = [str(filename) for filename in filenames]
  7933. else:
  7934. filenames = [name]
  7935. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7936. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7937. _("Opening Gerber file.")),
  7938. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7939. color=QtGui.QColor("gray"))
  7940. if len(filenames) == 0:
  7941. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7942. else:
  7943. for filename in filenames:
  7944. if filename != '':
  7945. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  7946. def on_fileopenexcellon(self, signal, name=None):
  7947. """
  7948. File menu callback for opening an Excellon file.
  7949. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7950. :param name:
  7951. :return: None
  7952. """
  7953. self.report_usage("on_fileopenexcellon")
  7954. App.log.debug("on_fileopenexcellon()")
  7955. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  7956. "All Files (*.*)"
  7957. if name is None:
  7958. try:
  7959. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  7960. directory=self.get_last_folder(),
  7961. filter=_filter_)
  7962. except TypeError:
  7963. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  7964. filenames = [str(filename) for filename in filenames]
  7965. else:
  7966. filenames = [str(name)]
  7967. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7968. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7969. _("Opening Excellon file.")),
  7970. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7971. color=QtGui.QColor("gray"))
  7972. if len(filenames) == 0:
  7973. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  7974. else:
  7975. for filename in filenames:
  7976. if filename != '':
  7977. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  7978. def on_fileopengcode(self, signal, name=None):
  7979. """
  7980. File menu call back for opening gcode.
  7981. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7982. :param name:
  7983. :return:
  7984. """
  7985. self.report_usage("on_fileopengcode")
  7986. App.log.debug("on_fileopengcode()")
  7987. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  7988. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  7989. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  7990. "All Files (*.*)"
  7991. if name is None:
  7992. try:
  7993. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  7994. directory=self.get_last_folder(),
  7995. filter=_filter_)
  7996. except TypeError:
  7997. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  7998. filenames = [str(filename) for filename in filenames]
  7999. else:
  8000. filenames = [name]
  8001. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8002. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8003. _("Opening G-Code file.")),
  8004. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8005. color=QtGui.QColor("gray"))
  8006. if len(filenames) == 0:
  8007. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  8008. else:
  8009. for filename in filenames:
  8010. if filename != '':
  8011. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  8012. def on_file_openproject(self, signal):
  8013. """
  8014. File menu callback for opening a project.
  8015. :param signal: required because clicking the entry will generate a checked signal which needs a container
  8016. :return: None
  8017. """
  8018. self.report_usage("on_file_openproject")
  8019. App.log.debug("on_file_openproject()")
  8020. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  8021. try:
  8022. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  8023. directory=self.get_last_folder(), filter=_filter_)
  8024. except TypeError:
  8025. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  8026. # The Qt methods above will return a QString which can cause problems later.
  8027. # So far json.dump() will fail to serialize it.
  8028. # TODO: Improve the serialization methods and remove this fix.
  8029. filename = str(filename)
  8030. if filename == "":
  8031. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  8032. else:
  8033. # self.worker_task.emit({'fcn': self.open_project,
  8034. # 'params': [filename]})
  8035. # The above was failing because open_project() is not
  8036. # thread safe. The new_project()
  8037. self.open_project(filename)
  8038. def on_fileopenhpgl2(self, signal, name=None):
  8039. """
  8040. File menu callback for opening a HPGL2.
  8041. :param signal: required because clicking the entry will generate a checked signal which needs a container
  8042. :param name:
  8043. :return: None
  8044. """
  8045. self.report_usage("on_fileopenhpgl2")
  8046. App.log.debug("on_fileopenhpgl2()")
  8047. _filter_ = "HPGL2 Files (*.plt);;" \
  8048. "All Files (*.*)"
  8049. if name is None:
  8050. try:
  8051. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  8052. directory=self.get_last_folder(),
  8053. filter=_filter_)
  8054. except TypeError:
  8055. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  8056. filenames = [str(filename) for filename in filenames]
  8057. else:
  8058. filenames = [name]
  8059. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8060. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8061. _("Opening HPGL2 file.")),
  8062. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8063. color=QtGui.QColor("gray"))
  8064. if len(filenames) == 0:
  8065. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  8066. else:
  8067. for filename in filenames:
  8068. if filename != '':
  8069. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  8070. def on_file_openconfig(self, signal):
  8071. """
  8072. File menu callback for opening a config file.
  8073. :param signal: required because clicking the entry will generate a checked signal which needs a container
  8074. :return: None
  8075. """
  8076. self.report_usage("on_file_openconfig")
  8077. App.log.debug("on_file_openconfig()")
  8078. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  8079. try:
  8080. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  8081. directory=self.data_path, filter=_filter_)
  8082. except TypeError:
  8083. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  8084. filter=_filter_)
  8085. if filename == "":
  8086. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  8087. else:
  8088. self.open_config_file(filename)
  8089. def on_file_exportsvg(self):
  8090. """
  8091. Callback for menu item File->Export SVG.
  8092. :return: None
  8093. """
  8094. self.report_usage("on_file_exportsvg")
  8095. App.log.debug("on_file_exportsvg()")
  8096. obj = self.collection.get_active()
  8097. if obj is None:
  8098. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  8099. msg = _("Please Select a Geometry object to export")
  8100. msgbox = QtWidgets.QMessageBox()
  8101. msgbox.setInformativeText(msg)
  8102. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8103. msgbox.setDefaultButton(bt_ok)
  8104. msgbox.exec_()
  8105. return
  8106. # Check for more compatible types and add as required
  8107. if (not isinstance(obj, GeometryObject)
  8108. and not isinstance(obj, GerberObject)
  8109. and not isinstance(obj, CNCJobObject)
  8110. and not isinstance(obj, ExcellonObject)):
  8111. msg = '[ERROR_NOTCL] %s' % \
  8112. _("Only Geometry, Gerber and CNCJob objects can be used.")
  8113. msgbox = QtWidgets.QMessageBox()
  8114. msgbox.setInformativeText(msg)
  8115. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8116. msgbox.setDefaultButton(bt_ok)
  8117. msgbox.exec_()
  8118. return
  8119. name = obj.options["name"]
  8120. _filter = "SVG File (*.svg);;All Files (*.*)"
  8121. try:
  8122. filename, _f = FCFileSaveDialog.get_saved_filename(
  8123. caption=_("Export SVG"),
  8124. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  8125. filter=_filter)
  8126. except TypeError:
  8127. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  8128. filename = str(filename)
  8129. if filename == "":
  8130. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  8131. return
  8132. else:
  8133. self.export_svg(name, filename)
  8134. if self.defaults["global_open_style"] is False:
  8135. self.file_opened.emit("SVG", filename)
  8136. self.file_saved.emit("SVG", filename)
  8137. def on_file_exportpng(self):
  8138. self.report_usage("on_file_exportpng")
  8139. App.log.debug("on_file_exportpng()")
  8140. self.date = str(datetime.today()).rpartition('.')[0]
  8141. self.date = ''.join(c for c in self.date if c not in ':-')
  8142. self.date = self.date.replace(' ', '_')
  8143. if self.is_legacy is False:
  8144. image = _screenshot()
  8145. data = np.asarray(image)
  8146. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  8147. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  8148. return
  8149. filter_ = "PNG File (*.png);;All Files (*.*)"
  8150. try:
  8151. filename, _f = FCFileSaveDialog.get_saved_filename(
  8152. caption=_("Export PNG Image"),
  8153. directory=self.get_last_save_folder() + '/png_' + self.date,
  8154. filter=filter_)
  8155. except TypeError:
  8156. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  8157. filename = str(filename)
  8158. if filename == "":
  8159. self.inform.emit(_("Cancelled."))
  8160. return
  8161. else:
  8162. if self.is_legacy is False:
  8163. write_png(filename, data)
  8164. else:
  8165. self.plotcanvas.figure.savefig(filename)
  8166. if self.defaults["global_open_style"] is False:
  8167. self.file_opened.emit("png", filename)
  8168. self.file_saved.emit("png", filename)
  8169. def on_file_savegerber(self):
  8170. """
  8171. Callback for menu item in Project context menu.
  8172. :return: None
  8173. """
  8174. self.report_usage("on_file_savegerber")
  8175. App.log.debug("on_file_savegerber()")
  8176. obj = self.collection.get_active()
  8177. if obj is None:
  8178. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  8179. return
  8180. # Check for more compatible types and add as required
  8181. if not isinstance(obj, GerberObject):
  8182. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  8183. return
  8184. name = self.collection.get_active().options["name"]
  8185. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  8186. try:
  8187. filename, _f = FCFileSaveDialog.get_saved_filename(
  8188. caption="Save Gerber source file",
  8189. directory=self.get_last_save_folder() + '/' + name,
  8190. filter=_filter)
  8191. except TypeError:
  8192. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  8193. filename = str(filename)
  8194. if filename == "":
  8195. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  8196. return
  8197. else:
  8198. self.save_source_file(name, filename)
  8199. if self.defaults["global_open_style"] is False:
  8200. self.file_opened.emit("Gerber", filename)
  8201. self.file_saved.emit("Gerber", filename)
  8202. def on_file_savescript(self):
  8203. """
  8204. Callback for menu item in Project context menu.
  8205. :return: None
  8206. """
  8207. self.report_usage("on_file_savescript")
  8208. App.log.debug("on_file_savescript()")
  8209. obj = self.collection.get_active()
  8210. if obj is None:
  8211. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  8212. return
  8213. # Check for more compatible types and add as required
  8214. if not isinstance(obj, ScriptObject):
  8215. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  8216. return
  8217. name = self.collection.get_active().options["name"]
  8218. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  8219. try:
  8220. filename, _f = FCFileSaveDialog.get_saved_filename(
  8221. caption="Save Script source file",
  8222. directory=self.get_last_save_folder() + '/' + name,
  8223. filter=_filter)
  8224. except TypeError:
  8225. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  8226. filename = str(filename)
  8227. if filename == "":
  8228. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  8229. return
  8230. else:
  8231. self.save_source_file(name, filename)
  8232. if self.defaults["global_open_style"] is False:
  8233. self.file_opened.emit("Script", filename)
  8234. self.file_saved.emit("Script", filename)
  8235. def on_file_savedocument(self):
  8236. """
  8237. Callback for menu item in Project context menu.
  8238. :return: None
  8239. """
  8240. self.report_usage("on_file_savedocument")
  8241. App.log.debug("on_file_savedocument()")
  8242. obj = self.collection.get_active()
  8243. if obj is None:
  8244. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  8245. return
  8246. # Check for more compatible types and add as required
  8247. if not isinstance(obj, ScriptObject):
  8248. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  8249. return
  8250. name = self.collection.get_active().options["name"]
  8251. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  8252. try:
  8253. filename, _f = FCFileSaveDialog.get_saved_filename(
  8254. caption="Save Document source file",
  8255. directory=self.get_last_save_folder() + '/' + name,
  8256. filter=_filter)
  8257. except TypeError:
  8258. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  8259. filename = str(filename)
  8260. if filename == "":
  8261. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  8262. return
  8263. else:
  8264. self.save_source_file(name, filename)
  8265. if self.defaults["global_open_style"] is False:
  8266. self.file_opened.emit("Document", filename)
  8267. self.file_saved.emit("Document", filename)
  8268. def on_file_saveexcellon(self):
  8269. """
  8270. Callback for menu item in project context menu.
  8271. :return: None
  8272. """
  8273. self.report_usage("on_file_saveexcellon")
  8274. App.log.debug("on_file_saveexcellon()")
  8275. obj = self.collection.get_active()
  8276. if obj is None:
  8277. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  8278. return
  8279. # Check for more compatible types and add as required
  8280. if not isinstance(obj, ExcellonObject):
  8281. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  8282. return
  8283. name = self.collection.get_active().options["name"]
  8284. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  8285. try:
  8286. filename, _f = FCFileSaveDialog.get_saved_filename(
  8287. caption=_("Save Excellon source file"),
  8288. directory=self.get_last_save_folder() + '/' + name,
  8289. filter=_filter)
  8290. except TypeError:
  8291. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  8292. filename = str(filename)
  8293. if filename == "":
  8294. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  8295. return
  8296. else:
  8297. self.save_source_file(name, filename)
  8298. if self.defaults["global_open_style"] is False:
  8299. self.file_opened.emit("Excellon", filename)
  8300. self.file_saved.emit("Excellon", filename)
  8301. def on_file_exportexcellon(self):
  8302. """
  8303. Callback for menu item File->Export->Excellon.
  8304. :return: None
  8305. """
  8306. self.report_usage("on_file_exportexcellon")
  8307. App.log.debug("on_file_exportexcellon()")
  8308. obj = self.collection.get_active()
  8309. if obj is None:
  8310. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  8311. return
  8312. # Check for more compatible types and add as required
  8313. if not isinstance(obj, ExcellonObject):
  8314. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  8315. return
  8316. name = self.collection.get_active().options["name"]
  8317. _filter = self.defaults["excellon_save_filters"]
  8318. try:
  8319. filename, _f = FCFileSaveDialog.get_saved_filename(
  8320. caption=_("Export Excellon"),
  8321. directory=self.get_last_save_folder() + '/' + name,
  8322. filter=_filter)
  8323. except TypeError:
  8324. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  8325. filename = str(filename)
  8326. if filename == "":
  8327. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  8328. return
  8329. else:
  8330. used_extension = filename.rpartition('.')[2]
  8331. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  8332. self.export_excellon(name, filename)
  8333. if self.defaults["global_open_style"] is False:
  8334. self.file_opened.emit("Excellon", filename)
  8335. self.file_saved.emit("Excellon", filename)
  8336. def on_file_exportgerber(self):
  8337. """
  8338. Callback for menu item File->Export->Gerber.
  8339. :return: None
  8340. """
  8341. self.report_usage("on_file_exportgerber")
  8342. App.log.debug("on_file_exportgerber()")
  8343. obj = self.collection.get_active()
  8344. if obj is None:
  8345. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  8346. return
  8347. # Check for more compatible types and add as required
  8348. if not isinstance(obj, GerberObject):
  8349. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  8350. return
  8351. name = self.collection.get_active().options["name"]
  8352. _filter_ = self.defaults['gerber_save_filters']
  8353. try:
  8354. filename, _f = FCFileSaveDialog.get_saved_filename(
  8355. caption=_("Export Gerber"),
  8356. directory=self.get_last_save_folder() + '/' + name,
  8357. filter=_filter_)
  8358. except TypeError:
  8359. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  8360. filename = str(filename)
  8361. if filename == "":
  8362. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  8363. return
  8364. else:
  8365. used_extension = filename.rpartition('.')[2]
  8366. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  8367. self.export_gerber(name, filename)
  8368. if self.defaults["global_open_style"] is False:
  8369. self.file_opened.emit("Gerber", filename)
  8370. self.file_saved.emit("Gerber", filename)
  8371. def on_file_exportdxf(self):
  8372. """
  8373. Callback for menu item File->Export DXF.
  8374. :return: None
  8375. """
  8376. self.report_usage("on_file_exportdxf")
  8377. App.log.debug("on_file_exportdxf()")
  8378. obj = self.collection.get_active()
  8379. if obj is None:
  8380. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  8381. msg = _("Please Select a Geometry object to export")
  8382. msgbox = QtWidgets.QMessageBox()
  8383. msgbox.setInformativeText(msg)
  8384. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8385. msgbox.setDefaultButton(bt_ok)
  8386. msgbox.exec_()
  8387. return
  8388. # Check for more compatible types and add as required
  8389. if not isinstance(obj, GeometryObject):
  8390. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  8391. msgbox = QtWidgets.QMessageBox()
  8392. msgbox.setInformativeText(msg)
  8393. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8394. msgbox.setDefaultButton(bt_ok)
  8395. msgbox.exec_()
  8396. return
  8397. name = self.collection.get_active().options["name"]
  8398. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  8399. try:
  8400. filename, _f = FCFileSaveDialog.get_saved_filename(
  8401. caption=_("Export DXF"),
  8402. directory=self.get_last_save_folder() + '/' + name,
  8403. filter=_filter_)
  8404. except TypeError:
  8405. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  8406. filename = str(filename)
  8407. if filename == "":
  8408. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  8409. return
  8410. else:
  8411. self.export_dxf(name, filename)
  8412. if self.defaults["global_open_style"] is False:
  8413. self.file_opened.emit("DXF", filename)
  8414. self.file_saved.emit("DXF", filename)
  8415. def on_file_importsvg(self, type_of_obj):
  8416. """
  8417. Callback for menu item File->Import SVG.
  8418. :param type_of_obj: to import the SVG as Geometry or as Gerber
  8419. :type type_of_obj: str
  8420. :return: None
  8421. """
  8422. self.report_usage("on_file_importsvg")
  8423. App.log.debug("on_file_importsvg()")
  8424. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  8425. try:
  8426. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  8427. directory=self.get_last_folder(), filter=_filter_)
  8428. except TypeError:
  8429. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  8430. filter=_filter_)
  8431. if type_of_obj != "geometry" and type_of_obj != "gerber":
  8432. type_of_obj = "geometry"
  8433. filenames = [str(filename) for filename in filenames]
  8434. if len(filenames) == 0:
  8435. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  8436. else:
  8437. for filename in filenames:
  8438. if filename != '':
  8439. self.worker_task.emit({'fcn': self.import_svg,
  8440. 'params': [filename, type_of_obj]})
  8441. def on_file_importdxf(self, type_of_obj):
  8442. """
  8443. Callback for menu item File->Import DXF.
  8444. :param type_of_obj: to import the DXF as Geometry or as Gerber
  8445. :type type_of_obj: str
  8446. :return: None
  8447. """
  8448. self.report_usage("on_file_importdxf")
  8449. App.log.debug("on_file_importdxf()")
  8450. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  8451. try:
  8452. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  8453. directory=self.get_last_folder(),
  8454. filter=_filter_)
  8455. except TypeError:
  8456. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  8457. filter=_filter_)
  8458. if type_of_obj != "geometry" and type_of_obj != "gerber":
  8459. type_of_obj = "geometry"
  8460. filenames = [str(filename) for filename in filenames]
  8461. if len(filenames) == 0:
  8462. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  8463. else:
  8464. for filename in filenames:
  8465. if filename != '':
  8466. self.worker_task.emit({'fcn': self.import_dxf,
  8467. 'params': [filename, type_of_obj]})
  8468. # ###############################################################################################################
  8469. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  8470. # ###############################################################################################################
  8471. def init_code_editor(self, name):
  8472. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  8473. # add the tab if it was closed
  8474. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  8475. self.text_editor_tab.setObjectName('text_editor_tab')
  8476. # delete the absolute and relative position and messages in the infobar
  8477. self.ui.position_label.setText("")
  8478. self.ui.rel_position_label.setText("")
  8479. # first clear previous text in text editor (if any)
  8480. self.text_editor_tab.code_editor.clear()
  8481. self.text_editor_tab.code_editor.setReadOnly(False)
  8482. self.toggle_codeeditor = True
  8483. self.text_editor_tab.code_editor.completer_enable = False
  8484. self.text_editor_tab.buttonRun.hide()
  8485. # make sure to keep a reference to the code editor
  8486. self.reference_code_editor = self.text_editor_tab.code_editor
  8487. # Switch plot_area to CNCJob tab
  8488. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  8489. def on_view_source(self):
  8490. """
  8491. Called when the user wants to see the source file of the selected object
  8492. :return:
  8493. """
  8494. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  8495. self.proc_container.view.set_busy(_("Loading..."))
  8496. try:
  8497. obj = self.collection.get_active()
  8498. except Exception as e:
  8499. log.debug("App.on_view_source() --> %s" % str(e))
  8500. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  8501. return 'fail'
  8502. if obj is None:
  8503. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  8504. return 'fail'
  8505. flt = "All Files (*.*)"
  8506. if obj.kind == 'gerber':
  8507. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  8508. elif obj.kind == 'excellon':
  8509. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  8510. elif obj.kind == 'cncjob':
  8511. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  8512. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  8513. # add the tab if it was closed
  8514. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  8515. self.source_editor_tab.setObjectName('source_editor_tab')
  8516. # delete the absolute and relative position and messages in the infobar
  8517. self.ui.position_label.setText("")
  8518. self.ui.rel_position_label.setText("")
  8519. # first clear previous text in text editor (if any)
  8520. self.source_editor_tab.code_editor.clear()
  8521. self.source_editor_tab.code_editor.setReadOnly(False)
  8522. self.source_editor_tab.code_editor.completer_enable = False
  8523. self.source_editor_tab.buttonRun.hide()
  8524. # Switch plot_area to CNCJob tab
  8525. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  8526. try:
  8527. self.source_editor_tab.buttonOpen.clicked.disconnect()
  8528. except TypeError:
  8529. pass
  8530. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  8531. try:
  8532. self.source_editor_tab.buttonSave.clicked.disconnect()
  8533. except TypeError:
  8534. pass
  8535. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  8536. # then append the text from GCode to the text editor
  8537. if obj.kind == 'cncjob':
  8538. try:
  8539. file = obj.export_gcode(
  8540. preamble=self.defaults["cncjob_prepend"],
  8541. postamble=self.defaults["cncjob_append"],
  8542. to_file=True)
  8543. if file == 'fail':
  8544. return 'fail'
  8545. except AttributeError:
  8546. self.inform.emit('[WARNING_NOTCL] %s' %
  8547. _("There is no selected object for which to see it's source file code."))
  8548. return 'fail'
  8549. else:
  8550. try:
  8551. file = StringIO(obj.source_file)
  8552. except (AttributeError, TypeError):
  8553. self.inform.emit('[WARNING_NOTCL] %s' %
  8554. _("There is no selected object for which to see it's source file code."))
  8555. return 'fail'
  8556. self.source_editor_tab.t_frame.hide()
  8557. try:
  8558. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  8559. # for line in file:
  8560. # QtWidgets.QApplication.processEvents()
  8561. # proc_line = str(line).strip('\n')
  8562. # self.source_editor_tab.code_editor.append(proc_line)
  8563. except Exception as e:
  8564. log.debug('App.on_view_source() -->%s' % str(e))
  8565. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  8566. return
  8567. self.source_editor_tab.handleTextChanged()
  8568. self.source_editor_tab.t_frame.show()
  8569. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  8570. self.proc_container.view.set_idle()
  8571. # self.ui.show()
  8572. def on_toggle_code_editor(self):
  8573. self.report_usage("on_toggle_code_editor()")
  8574. if self.toggle_codeeditor is False:
  8575. self.init_code_editor(name=_("Code Editor"))
  8576. self.text_editor_tab.buttonOpen.clicked.disconnect()
  8577. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  8578. self.text_editor_tab.buttonSave.clicked.disconnect()
  8579. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  8580. else:
  8581. for idx in range(self.ui.plot_tab_area.count()):
  8582. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  8583. self.ui.plot_tab_area.closeTab(idx)
  8584. break
  8585. self.toggle_codeeditor = False
  8586. def on_code_editor_close(self):
  8587. self.toggle_codeeditor = False
  8588. def goto_text_line(self):
  8589. """
  8590. Will scroll a text to the specified text line.
  8591. :return: None
  8592. """
  8593. dia_box = Dialog_box(title=_("Go to Line ..."),
  8594. label=_("Line:"),
  8595. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  8596. initial_text='')
  8597. try:
  8598. line = int(dia_box.location) - 1
  8599. except (ValueError, TypeError):
  8600. line = 0
  8601. if dia_box.ok:
  8602. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  8603. # at the top of the window
  8604. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  8605. # get the document() of the TextEditor
  8606. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  8607. # create a Text Cursor based on the searched line
  8608. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  8609. # set cursor of the code editor with the cursor at the searcehd line
  8610. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  8611. def on_filenewscript(self, silent=False, name=None, text=None):
  8612. """
  8613. Will create a new script file and open it in the Code Editor
  8614. :param silent: if True will not display status messages
  8615. :param name: if specified will be the name of the new script
  8616. :param text: pass a source file to the newly created script to be loaded in it
  8617. :return: None
  8618. """
  8619. if silent is False:
  8620. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  8621. # delete the absolute and relative position and messages in the infobar
  8622. self.ui.position_label.setText("")
  8623. self.ui.rel_position_label.setText("")
  8624. if name is not None:
  8625. self.new_script_object(name=name, text=text)
  8626. else:
  8627. self.new_script_object(text=text)
  8628. # script_text = script_obj.source_file
  8629. #
  8630. # self.proc_container.view.set_busy(_("Loading..."))
  8631. # script_obj.script_editor_tab.t_frame.hide()
  8632. #
  8633. # script_obj.script_editor_tab.t_frame.show()
  8634. # self.proc_container.view.set_idle()
  8635. def on_fileopenscript(self, name=None, silent=False):
  8636. """
  8637. Will open a Tcl script file into the Code Editor
  8638. :param silent: if True will not display status messages
  8639. :param name: name of a Tcl script file to open
  8640. :return:
  8641. """
  8642. self.report_usage("on_fileopenscript")
  8643. App.log.debug("on_fileopenscript()")
  8644. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  8645. "All Files (*.*)"
  8646. if name:
  8647. filenames = [name]
  8648. else:
  8649. try:
  8650. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  8651. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  8652. except TypeError:
  8653. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  8654. if len(filenames) == 0:
  8655. if silent is False:
  8656. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  8657. else:
  8658. for filename in filenames:
  8659. if filename != '':
  8660. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  8661. def on_fileopenscript_example(self, name=None, silent=False):
  8662. """
  8663. Will open a Tcl script file into the Code Editor
  8664. :param silent: if True will not display status messages
  8665. :param name: name of a Tcl script file to open
  8666. :return:
  8667. """
  8668. self.report_usage("on_fileopenscript_example")
  8669. App.log.debug("on_fileopenscript_example()")
  8670. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  8671. "All Files (*.*)"
  8672. # test if the app was frozen and choose the path for the configuration file
  8673. if getattr(sys, "frozen", False) is True:
  8674. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  8675. else:
  8676. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  8677. if name:
  8678. filenames = [name]
  8679. else:
  8680. try:
  8681. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  8682. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  8683. except TypeError:
  8684. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  8685. if len(filenames) == 0:
  8686. if silent is False:
  8687. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  8688. else:
  8689. for filename in filenames:
  8690. if filename != '':
  8691. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  8692. def on_filerunscript(self, name=None, silent=False):
  8693. """
  8694. File menu callback for loading and running a TCL script.
  8695. :param silent: if True will not display status messages
  8696. :param name: name of a Tcl script file to be run by FlatCAM
  8697. :return: None
  8698. """
  8699. self.report_usage("on_filerunscript")
  8700. App.log.debug("on_file_runscript()")
  8701. if name:
  8702. filename = name
  8703. if self.cmd_line_headless != 1:
  8704. self.splash.showMessage('%s: %ssec\n%s' %
  8705. (_("Canvas initialization started.\n"
  8706. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8707. _("Executing ScriptObject file.")
  8708. ),
  8709. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8710. color=QtGui.QColor("gray"))
  8711. else:
  8712. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  8713. "All Files (*.*)"
  8714. try:
  8715. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  8716. directory=self.get_last_folder(), filter=_filter_)
  8717. except TypeError:
  8718. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  8719. # The Qt methods above will return a QString which can cause problems later.
  8720. # So far json.dump() will fail to serialize it.
  8721. filename = str(filename)
  8722. if filename == "":
  8723. if silent is False:
  8724. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  8725. else:
  8726. if self.cmd_line_headless != 1:
  8727. if self.ui.shell_dock.isHidden():
  8728. self.ui.shell_dock.show()
  8729. try:
  8730. with open(filename, "r") as tcl_script:
  8731. cmd_line_shellfile_content = tcl_script.read()
  8732. if self.cmd_line_headless != 1:
  8733. self.shell.exec_command(cmd_line_shellfile_content)
  8734. else:
  8735. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  8736. if silent is False:
  8737. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  8738. except Exception as e:
  8739. log.debug("App.on_filerunscript() -> %s" % str(e))
  8740. sys.exit(2)
  8741. def on_file_saveproject(self, silent=False):
  8742. """
  8743. Callback for menu item File->Save Project. Saves the project to
  8744. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  8745. if set to None. The project is saved by calling ``self.save_project()``.
  8746. :param silent: if True will not display status messages
  8747. :return: None
  8748. """
  8749. self.report_usage("on_file_saveproject")
  8750. if self.project_filename is None:
  8751. self.on_file_saveprojectas()
  8752. else:
  8753. self.worker_task.emit({'fcn': self.save_project,
  8754. 'params': [self.project_filename, silent]})
  8755. if self.defaults["global_open_style"] is False:
  8756. self.file_opened.emit("project", self.project_filename)
  8757. self.file_saved.emit("project", self.project_filename)
  8758. self.set_ui_title(name=self.project_filename)
  8759. self.should_we_save = False
  8760. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  8761. """
  8762. Callback for menu item File->Save Project As... Opens a file
  8763. chooser and saves the project to the given file via
  8764. ``self.save_project()``.
  8765. :param make_copy if to be create a copy of the project; boolean
  8766. :param use_thread: if to be run in a separate thread; boolean
  8767. :param quit_action: if to be followed by quiting the application; boolean
  8768. :return: None
  8769. """
  8770. self.report_usage("on_file_saveprojectas")
  8771. self.date = str(datetime.today()).rpartition('.')[0]
  8772. self.date = ''.join(c for c in self.date if c not in ':-')
  8773. self.date = self.date.replace(' ', '_')
  8774. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  8775. try:
  8776. filename, _f = FCFileSaveDialog.get_saved_filename(
  8777. caption=_("Save Project As ..."),
  8778. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  8779. proj=_("Project")),
  8780. filter=filter_
  8781. )
  8782. except TypeError:
  8783. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  8784. filename = str(filename)
  8785. if filename == '':
  8786. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  8787. return
  8788. if use_thread is True:
  8789. self.worker_task.emit({'fcn': self.save_project,
  8790. 'params': [filename, quit_action]})
  8791. else:
  8792. self.save_project(filename, quit_action)
  8793. # self.save_project(filename)
  8794. if self.defaults["global_open_style"] is False:
  8795. self.file_opened.emit("project", filename)
  8796. self.file_saved.emit("project", filename)
  8797. if not make_copy:
  8798. self.project_filename = filename
  8799. self.set_ui_title(name=self.project_filename)
  8800. self.should_we_save = False
  8801. def on_file_save_objects_pdf(self, use_thread=True):
  8802. self.date = str(datetime.today()).rpartition('.')[0]
  8803. self.date = ''.join(c for c in self.date if c not in ':-')
  8804. self.date = self.date.replace(' ', '_')
  8805. try:
  8806. obj_selection = self.collection.get_selected()
  8807. if len(obj_selection) == 1:
  8808. obj_name = str(obj_selection[0].options['name'])
  8809. else:
  8810. obj_name = _("FlatCAM objects print")
  8811. except AttributeError as err:
  8812. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  8813. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  8814. return
  8815. if not obj_selection:
  8816. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  8817. return
  8818. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  8819. try:
  8820. filename, _f = FCFileSaveDialog.get_saved_filename(
  8821. caption=_("Save Object as PDF ..."),
  8822. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  8823. obj_name=obj_name,
  8824. date=self.date),
  8825. filter=filter_
  8826. )
  8827. except TypeError:
  8828. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  8829. filename = str(filename)
  8830. if filename == '':
  8831. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  8832. return
  8833. if use_thread is True:
  8834. proc = self.proc_container.new(_("Printing PDF ... Please wait."))
  8835. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  8836. else:
  8837. self.save_pdf(filename, obj_selection)
  8838. # self.save_project(filename)
  8839. if self.defaults["global_open_style"] is False:
  8840. self.file_opened.emit("pdf", filename)
  8841. self.file_saved.emit("pdf", filename)
  8842. def save_pdf(self, file_name, obj_selection):
  8843. p_size = self.defaults['global_workspaceT']
  8844. orientation = self.defaults['global_workspace_orientation']
  8845. color = 'black'
  8846. transparency_level = 1.0
  8847. self.pagesize = {}
  8848. self.pagesize.update(
  8849. {
  8850. 'Bounds': None,
  8851. 'A0': (841 * mm, 1189 * mm),
  8852. 'A1': (594 * mm, 841 * mm),
  8853. 'A2': (420 * mm, 594 * mm),
  8854. 'A3': (297 * mm, 420 * mm),
  8855. 'A4': (210 * mm, 297 * mm),
  8856. 'A5': (148 * mm, 210 * mm),
  8857. 'A6': (105 * mm, 148 * mm),
  8858. 'A7': (74 * mm, 105 * mm),
  8859. 'A8': (52 * mm, 74 * mm),
  8860. 'A9': (37 * mm, 52 * mm),
  8861. 'A10': (26 * mm, 37 * mm),
  8862. 'B0': (1000 * mm, 1414 * mm),
  8863. 'B1': (707 * mm, 1000 * mm),
  8864. 'B2': (500 * mm, 707 * mm),
  8865. 'B3': (353 * mm, 500 * mm),
  8866. 'B4': (250 * mm, 353 * mm),
  8867. 'B5': (176 * mm, 250 * mm),
  8868. 'B6': (125 * mm, 176 * mm),
  8869. 'B7': (88 * mm, 125 * mm),
  8870. 'B8': (62 * mm, 88 * mm),
  8871. 'B9': (44 * mm, 62 * mm),
  8872. 'B10': (31 * mm, 44 * mm),
  8873. 'C0': (917 * mm, 1297 * mm),
  8874. 'C1': (648 * mm, 917 * mm),
  8875. 'C2': (458 * mm, 648 * mm),
  8876. 'C3': (324 * mm, 458 * mm),
  8877. 'C4': (229 * mm, 324 * mm),
  8878. 'C5': (162 * mm, 229 * mm),
  8879. 'C6': (114 * mm, 162 * mm),
  8880. 'C7': (81 * mm, 114 * mm),
  8881. 'C8': (57 * mm, 81 * mm),
  8882. 'C9': (40 * mm, 57 * mm),
  8883. 'C10': (28 * mm, 40 * mm),
  8884. # American paper sizes
  8885. 'LETTER': (8.5 * inch, 11 * inch),
  8886. 'LEGAL': (8.5 * inch, 14 * inch),
  8887. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  8888. # From https://en.wikipedia.org/wiki/Paper_size
  8889. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  8890. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  8891. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  8892. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  8893. 'LEDGER': (17 * inch, 11 * inch),
  8894. }
  8895. )
  8896. exported_svg = []
  8897. for obj in obj_selection:
  8898. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  8899. scale_factor_x=None, scale_factor_y=None,
  8900. skew_factor_x=None, skew_factor_y=None,
  8901. mirror=None)
  8902. if obj.kind.lower() == 'gerber':
  8903. # color = self.defaults["gerber_plot_fill"][:-2]
  8904. color = obj.fill_color[:-2]
  8905. elif obj.kind.lower() == 'excellon':
  8906. color = '#C40000'
  8907. elif obj.kind.lower() == 'geometry':
  8908. color = self.defaults["global_draw_color"]
  8909. # Change the attributes of the exported SVG
  8910. # We don't need stroke-width
  8911. # We set opacity to maximum
  8912. # We set the colour to WHITE
  8913. root = ET.fromstring(svg_obj)
  8914. for child in root:
  8915. child.set('fill', str(color))
  8916. child.set('opacity', str(transparency_level))
  8917. child.set('stroke', str(color))
  8918. exported_svg.append(ET.tostring(root))
  8919. xmin = Inf
  8920. ymin = Inf
  8921. xmax = -Inf
  8922. ymax = -Inf
  8923. for obj in obj_selection:
  8924. try:
  8925. gxmin, gymin, gxmax, gymax = obj.bounds()
  8926. xmin = min([xmin, gxmin])
  8927. ymin = min([ymin, gymin])
  8928. xmax = max([xmax, gxmax])
  8929. ymax = max([ymax, gymax])
  8930. except Exception as e:
  8931. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  8932. # Determine bounding area for svg export
  8933. bounds = [xmin, ymin, xmax, ymax]
  8934. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  8935. # This contain the measure units
  8936. uom = obj_selection[0].units.lower()
  8937. # Define a boundary around SVG of about 1.0mm (~39mils)
  8938. if uom in "mm":
  8939. boundary = 1.0
  8940. else:
  8941. boundary = 0.0393701
  8942. # Convert everything to strings for use in the xml doc
  8943. svgwidth = str(size[0] + (2 * boundary))
  8944. svgheight = str(size[1] + (2 * boundary))
  8945. minx = str(bounds[0] - boundary)
  8946. miny = str(bounds[1] + boundary + size[1])
  8947. # Add a SVG Header and footer to the svg output from shapely
  8948. # The transform flips the Y Axis so that everything renders
  8949. # properly within svg apps such as inkscape
  8950. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8951. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8952. svg_header += 'width="' + svgwidth + uom + '" '
  8953. svg_header += 'height="' + svgheight + uom + '" '
  8954. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  8955. svg_header += '>'
  8956. svg_header += '<g transform="scale(1,-1)">'
  8957. svg_footer = '</g> </svg>'
  8958. svg_elem = str(svg_header)
  8959. for svg_item in exported_svg:
  8960. svg_elem += str(svg_item)
  8961. svg_elem += str(svg_footer)
  8962. # Parse the xml through a xml parser just to add line feeds
  8963. # and to make it look more pretty for the output
  8964. doc = parse_xml_string(svg_elem)
  8965. doc_final = doc.toprettyxml()
  8966. try:
  8967. if self.defaults['units'].upper() == 'IN':
  8968. unit = inch
  8969. else:
  8970. unit = mm
  8971. doc_final = StringIO(doc_final)
  8972. drawing = svg2rlg(doc_final)
  8973. if p_size == 'Bounds':
  8974. renderPDF.drawToFile(drawing, file_name)
  8975. else:
  8976. if orientation == 'p':
  8977. page_size = portrait(self.pagesize[p_size])
  8978. else:
  8979. page_size = landscape(self.pagesize[p_size])
  8980. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  8981. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  8982. renderPDF.draw(drawing, my_canvas, 0, 0)
  8983. my_canvas.save()
  8984. except Exception as e:
  8985. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  8986. return 'fail'
  8987. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  8988. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  8989. """
  8990. Exports a Geometry Object to an SVG file.
  8991. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8992. :param filename: Path to the SVG file to save to.
  8993. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  8994. :return:
  8995. """
  8996. self.report_usage("export_svg()")
  8997. if filename is None:
  8998. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8999. is not None else self.defaults["global_last_folder"]
  9000. self.log.debug("export_svg()")
  9001. try:
  9002. obj = self.collection.get_by_name(str(obj_name))
  9003. except Exception:
  9004. # TODO: The return behavior has not been established... should raise exception?
  9005. return "Could not retrieve object: %s" % obj_name
  9006. with self.proc_container.new(_("Exporting SVG")) as proc:
  9007. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  9008. # Determine bounding area for svg export
  9009. bounds = obj.bounds()
  9010. size = obj.size()
  9011. # Convert everything to strings for use in the xml doc
  9012. svgwidth = str(size[0])
  9013. svgheight = str(size[1])
  9014. minx = str(bounds[0])
  9015. miny = str(bounds[1] - size[1])
  9016. uom = obj.units.lower()
  9017. # Add a SVG Header and footer to the svg output from shapely
  9018. # The transform flips the Y Axis so that everything renders
  9019. # properly within svg apps such as inkscape
  9020. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  9021. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  9022. svg_header += 'width="' + svgwidth + uom + '" '
  9023. svg_header += 'height="' + svgheight + uom + '" '
  9024. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  9025. svg_header += '<g transform="scale(1,-1)">'
  9026. svg_footer = '</g> </svg>'
  9027. svg_elem = svg_header + exported_svg + svg_footer
  9028. # Parse the xml through a xml parser just to add line feeds
  9029. # and to make it look more pretty for the output
  9030. svgcode = parse_xml_string(svg_elem)
  9031. svgcode = svgcode.toprettyxml()
  9032. try:
  9033. with open(filename, 'w') as fp:
  9034. fp.write(svgcode)
  9035. except PermissionError:
  9036. self.inform.emit('[WARNING] %s' %
  9037. _("Permission denied, saving not possible.\n"
  9038. "Most likely another app is holding the file open and not accessible."))
  9039. return 'fail'
  9040. if self.defaults["global_open_style"] is False:
  9041. self.file_opened.emit("SVG", filename)
  9042. self.file_saved.emit("SVG", filename)
  9043. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  9044. def save_source_file(self, obj_name, filename, use_thread=True):
  9045. """
  9046. Exports a FlatCAM Object to an Gerber/Excellon file.
  9047. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  9048. :param filename: Path to the Gerber file to save to.
  9049. :param use_thread: if to be run in a separate thread
  9050. :return:
  9051. """
  9052. self.report_usage("save source file()")
  9053. if filename is None:
  9054. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  9055. is not None else self.defaults["global_last_folder"]
  9056. self.log.debug("save source file()")
  9057. obj = self.collection.get_by_name(obj_name)
  9058. file_string = StringIO(obj.source_file)
  9059. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  9060. if file_string.getvalue() == '':
  9061. self.inform.emit('[ERROR_NOTCL] %s' %
  9062. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  9063. return 'fail'
  9064. try:
  9065. with open(filename, 'w') as file:
  9066. file.writelines('G04*\n')
  9067. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  9068. (obj.kind.upper(), str(self.version), str(self.version_date)))
  9069. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  9070. file.writelines('G04 Created on : %s*\n' % time_string)
  9071. for line in file_string:
  9072. file.writelines(line)
  9073. except PermissionError:
  9074. self.inform.emit('[WARNING] %s' %
  9075. _("Permission denied, saving not possible.\n"
  9076. "Most likely another app is holding the file open and not accessible."))
  9077. return 'fail'
  9078. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  9079. """
  9080. Exports a Excellon Object to an Excellon file.
  9081. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  9082. :param filename: Path to the Excellon file to save to.
  9083. :param local_use:
  9084. :param use_thread: if to be run in a separate thread
  9085. :return:
  9086. """
  9087. self.report_usage("export_excellon()")
  9088. if filename is None:
  9089. if self.defaults["global_last_save_folder"]:
  9090. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  9091. else:
  9092. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  9093. self.log.debug("export_excellon()")
  9094. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  9095. self.defaults["excellon_exp_decimals"]
  9096. )
  9097. if local_use is None:
  9098. try:
  9099. obj = self.collection.get_by_name(str(obj_name))
  9100. except Exception:
  9101. return "Could not retrieve object: %s" % obj_name
  9102. else:
  9103. obj = local_use
  9104. if not isinstance(obj, ExcellonObject):
  9105. self.inform.emit('[ERROR_NOTCL] %s' %
  9106. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  9107. return
  9108. # updated units
  9109. eunits = self.defaults["excellon_exp_units"]
  9110. ewhole = self.defaults["excellon_exp_integer"]
  9111. efract = self.defaults["excellon_exp_decimals"]
  9112. ezeros = self.defaults["excellon_exp_zeros"]
  9113. eformat = self.defaults["excellon_exp_format"]
  9114. slot_type = self.defaults["excellon_exp_slot_type"]
  9115. fc_units = self.defaults['units'].upper()
  9116. if fc_units == 'MM':
  9117. factor = 1 if eunits == 'METRIC' else 0.03937
  9118. else:
  9119. factor = 25.4 if eunits == 'METRIC' else 1
  9120. def make_excellon():
  9121. try:
  9122. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  9123. header = 'M48\n'
  9124. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  9125. (str(self.version), str(self.version_date))
  9126. header += ';Filename: %s' % str(obj_name) + '\n'
  9127. header += ';Created on : %s' % time_str + '\n'
  9128. if eformat == 'dec':
  9129. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  9130. header += eunits + '\n'
  9131. for tool in obj.tools:
  9132. if eunits == 'METRIC':
  9133. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  9134. tool=str(tool),
  9135. dec=2)
  9136. else:
  9137. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  9138. tool=str(tool),
  9139. dec=4)
  9140. else:
  9141. if ezeros == 'LZ':
  9142. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  9143. form='ndec', e_zeros='LZ', factor=factor,
  9144. slot_type=slot_type)
  9145. header += '%s,%s\n' % (eunits, 'LZ')
  9146. header += format_exc
  9147. for tool in obj.tools:
  9148. if eunits == 'METRIC':
  9149. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  9150. tool=str(tool),
  9151. dec=2)
  9152. else:
  9153. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  9154. tool=str(tool),
  9155. dec=4)
  9156. else:
  9157. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  9158. form='ndec', e_zeros='TZ', factor=factor,
  9159. slot_type=slot_type)
  9160. header += '%s,%s\n' % (eunits, 'TZ')
  9161. header += format_exc
  9162. for tool in obj.tools:
  9163. if eunits == 'METRIC':
  9164. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  9165. tool=str(tool),
  9166. dec=2)
  9167. else:
  9168. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  9169. tool=str(tool),
  9170. dec=4)
  9171. header += '%\n'
  9172. footer = 'M30\n'
  9173. exported_excellon = header
  9174. exported_excellon += excellon_code
  9175. exported_excellon += footer
  9176. if local_use is None:
  9177. try:
  9178. with open(filename, 'w') as fp:
  9179. fp.write(exported_excellon)
  9180. except PermissionError:
  9181. self.inform.emit('[WARNING] %s' %
  9182. _("Permission denied, saving not possible.\n"
  9183. "Most likely another app is holding the file open and not accessible."))
  9184. return 'fail'
  9185. if self.defaults["global_open_style"] is False:
  9186. self.file_opened.emit("Excellon", filename)
  9187. self.file_saved.emit("Excellon", filename)
  9188. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  9189. else:
  9190. return exported_excellon
  9191. except Exception as e:
  9192. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  9193. return 'fail'
  9194. if use_thread is True:
  9195. with self.proc_container.new(_("Exporting Excellon")) as proc:
  9196. def job_thread_exc(app_obj):
  9197. ret = make_excellon()
  9198. if ret == 'fail':
  9199. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  9200. return
  9201. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  9202. else:
  9203. eret = make_excellon()
  9204. if eret == 'fail':
  9205. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  9206. return 'fail'
  9207. if local_use is not None:
  9208. return eret
  9209. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  9210. """
  9211. Exports a Gerber Object to an Gerber file.
  9212. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  9213. :param filename: Path to the Gerber file to save to.
  9214. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  9215. When not None, the value will be the actual Gerber object for which to create the Gerber code
  9216. :param use_thread: if to be run in a separate thread
  9217. :return:
  9218. """
  9219. self.report_usage("export_gerber()")
  9220. if filename is None:
  9221. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  9222. is not None else self.defaults["global_last_folder"]
  9223. self.log.debug("export_gerber()")
  9224. if local_use is None:
  9225. try:
  9226. obj = self.collection.get_by_name(str(obj_name))
  9227. except Exception:
  9228. return "Could not retrieve object: %s" % obj_name
  9229. else:
  9230. obj = local_use
  9231. # updated units
  9232. gunits = self.defaults["gerber_exp_units"]
  9233. gwhole = self.defaults["gerber_exp_integer"]
  9234. gfract = self.defaults["gerber_exp_decimals"]
  9235. gzeros = self.defaults["gerber_exp_zeros"]
  9236. fc_units = self.defaults['units'].upper()
  9237. if fc_units == 'MM':
  9238. factor = 1 if gunits == 'MM' else 0.03937
  9239. else:
  9240. factor = 25.4 if gunits == 'MM' else 1
  9241. def make_gerber():
  9242. try:
  9243. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  9244. header = 'G04*\n'
  9245. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  9246. (str(self.version), str(self.version_date))
  9247. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  9248. header += 'G04 Created on : %s*' % time_str + '\n'
  9249. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  9250. header += "%MO{units}*%\n".format(units=gunits)
  9251. for apid in obj.apertures:
  9252. if obj.apertures[apid]['type'] == 'C':
  9253. header += "%ADD{apid}{type},{size}*%\n".format(
  9254. apid=str(apid),
  9255. type='C',
  9256. size=(factor * obj.apertures[apid]['size'])
  9257. )
  9258. elif obj.apertures[apid]['type'] == 'R':
  9259. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  9260. apid=str(apid),
  9261. type='R',
  9262. width=(factor * obj.apertures[apid]['width']),
  9263. height=(factor * obj.apertures[apid]['height'])
  9264. )
  9265. elif obj.apertures[apid]['type'] == 'O':
  9266. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  9267. apid=str(apid),
  9268. type='O',
  9269. width=(factor * obj.apertures[apid]['width']),
  9270. height=(factor * obj.apertures[apid]['height'])
  9271. )
  9272. header += '\n'
  9273. # obsolete units but some software may need it
  9274. if gunits == 'IN':
  9275. header += 'G70*\n'
  9276. else:
  9277. header += 'G71*\n'
  9278. # Absolute Mode
  9279. header += 'G90*\n'
  9280. header += 'G01*\n'
  9281. # positive polarity
  9282. header += '%LPD*%\n'
  9283. footer = 'M02*\n'
  9284. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  9285. exported_gerber = header
  9286. exported_gerber += gerber_code
  9287. exported_gerber += footer
  9288. if local_use is None:
  9289. try:
  9290. with open(filename, 'w') as fp:
  9291. fp.write(exported_gerber)
  9292. except PermissionError:
  9293. self.inform.emit('[WARNING] %s' %
  9294. _("Permission denied, saving not possible.\n"
  9295. "Most likely another app is holding the file open and not accessible."))
  9296. return 'fail'
  9297. if self.defaults["global_open_style"] is False:
  9298. self.file_opened.emit("Gerber", filename)
  9299. self.file_saved.emit("Gerber", filename)
  9300. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  9301. else:
  9302. return exported_gerber
  9303. except Exception as e:
  9304. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  9305. return 'fail'
  9306. if use_thread is True:
  9307. with self.proc_container.new(_("Exporting Gerber")) as proc:
  9308. def job_thread_grb(app_obj):
  9309. ret = make_gerber()
  9310. if ret == 'fail':
  9311. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  9312. return
  9313. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  9314. else:
  9315. gret = make_gerber()
  9316. if gret == 'fail':
  9317. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  9318. return 'fail'
  9319. if local_use is not None:
  9320. return gret
  9321. def export_dxf(self, obj_name, filename, use_thread=True):
  9322. """
  9323. Exports a Geometry Object to an DXF file.
  9324. :param obj_name: the name of the FlatCAM object to be saved as DXF
  9325. :param filename: Path to the DXF file to save to.
  9326. :param use_thread: if to be run in a separate thread
  9327. :return:
  9328. """
  9329. self.report_usage("export_dxf()")
  9330. if filename is None:
  9331. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  9332. is not None else self.defaults["global_last_folder"]
  9333. self.log.debug("export_dxf()")
  9334. try:
  9335. obj = self.collection.get_by_name(str(obj_name))
  9336. except Exception:
  9337. # TODO: The return behavior has not been established... should raise exception?
  9338. return "Could not retrieve object: %s" % obj_name
  9339. def make_dxf():
  9340. try:
  9341. dxf_code = obj.export_dxf()
  9342. dxf_code.saveas(filename)
  9343. if self.defaults["global_open_style"] is False:
  9344. self.file_opened.emit("DXF", filename)
  9345. self.file_saved.emit("DXF", filename)
  9346. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  9347. except Exception:
  9348. return 'fail'
  9349. if use_thread is True:
  9350. with self.proc_container.new(_("Exporting DXF")) as proc:
  9351. def job_thread_exc(app_obj):
  9352. ret_dxf_val = make_dxf()
  9353. if ret_dxf_val == 'fail':
  9354. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  9355. return
  9356. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  9357. else:
  9358. ret = make_dxf()
  9359. if ret == 'fail':
  9360. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  9361. return
  9362. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  9363. """
  9364. Adds a new Geometry Object to the projects and populates
  9365. it with shapes extracted from the SVG file.
  9366. :param filename: Path to the SVG file.
  9367. :param geo_type: Type of FlatCAM object that will be created from SVG
  9368. :param outname:
  9369. :return:
  9370. """
  9371. self.report_usage("import_svg()")
  9372. log.debug("App.import_svg()")
  9373. obj_type = ""
  9374. if geo_type is None or geo_type == "geometry":
  9375. obj_type = "geometry"
  9376. elif geo_type == "gerber":
  9377. obj_type = "gerber"
  9378. else:
  9379. self.inform.emit('[ERROR_NOTCL] %s' %
  9380. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  9381. return
  9382. units = self.defaults['units'].upper()
  9383. def obj_init(geo_obj, app_obj):
  9384. geo_obj.import_svg(filename, obj_type, units=units)
  9385. geo_obj.multigeo = False
  9386. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  9387. with self.proc_container.new(_("Importing SVG")) as proc:
  9388. # Object name
  9389. name = outname or filename.split('/')[-1].split('\\')[-1]
  9390. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  9391. if ret == 'fail':
  9392. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  9393. return 'fail'
  9394. # Register recent file
  9395. self.file_opened.emit("svg", filename)
  9396. # GUI feedback
  9397. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9398. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  9399. """
  9400. Adds a new Geometry Object to the projects and populates
  9401. it with shapes extracted from the DXF file.
  9402. :param filename: Path to the DXF file.
  9403. :param geo_type: Type of FlatCAM object that will be created from DXF
  9404. :param outname: Name for the imported Geometry
  9405. :return:
  9406. """
  9407. self.report_usage("import_dxf()")
  9408. obj_type = ""
  9409. if geo_type is None or geo_type == "geometry":
  9410. obj_type = "geometry"
  9411. elif geo_type == "gerber":
  9412. obj_type = geo_type
  9413. else:
  9414. self.inform.emit('[ERROR_NOTCL] %s' %
  9415. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  9416. return
  9417. units = self.defaults['units'].upper()
  9418. def obj_init(geo_obj, app_obj):
  9419. geo_obj.import_dxf(filename, obj_type, units=units)
  9420. geo_obj.multigeo = False
  9421. with self.proc_container.new(_("Importing DXF")):
  9422. # Object name
  9423. name = outname or filename.split('/')[-1].split('\\')[-1]
  9424. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  9425. if ret == 'fail':
  9426. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  9427. return 'fail'
  9428. # Register recent file
  9429. self.file_opened.emit("dxf", filename)
  9430. # GUI feedback
  9431. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9432. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  9433. """
  9434. Opens a Gerber file, parses it and creates a new object for
  9435. it in the program. Thread-safe.
  9436. :param outname: Name of the resulting object. None causes the
  9437. name to be that of the file. Str.
  9438. :param filename: Gerber file filename
  9439. :type filename: str
  9440. :param plot: boolean, to plot or not the resulting object
  9441. :param from_tcl: True if run from Tcl Shell
  9442. :return: None
  9443. """
  9444. # How the object should be initialized
  9445. def obj_init(gerber_obj, app_obj):
  9446. assert isinstance(gerber_obj, GerberObject), \
  9447. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  9448. # Opening the file happens here
  9449. try:
  9450. gerber_obj.parse_file(filename)
  9451. except IOError:
  9452. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  9453. return "fail"
  9454. except ParseError as err:
  9455. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  9456. app_obj.log.error(str(err))
  9457. return "fail"
  9458. except Exception as e:
  9459. log.debug("App.open_gerber() --> %s" % str(e))
  9460. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  9461. msg += traceback.format_exc()
  9462. app_obj.inform.emit(msg)
  9463. return "fail"
  9464. if gerber_obj.is_empty():
  9465. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  9466. _("Object is not Gerber file or empty. Aborting object creation."))
  9467. return "fail"
  9468. App.log.debug("open_gerber()")
  9469. with self.proc_container.new(_("Opening Gerber")):
  9470. # Object name
  9471. name = outname or filename.split('/')[-1].split('\\')[-1]
  9472. # # ## Object creation # ##
  9473. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  9474. if ret_val == 'fail':
  9475. if from_tcl:
  9476. filename = self.defaults['global_tcl_path'] + '/' + name
  9477. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  9478. if ret_val == 'fail':
  9479. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  9480. return 'fail'
  9481. # Register recent file
  9482. self.file_opened.emit("gerber", filename)
  9483. # GUI feedback
  9484. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9485. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  9486. """
  9487. Opens an Excellon file, parses it and creates a new object for
  9488. it in the program. Thread-safe.
  9489. :param outname: Name of the resulting object. None causes the name to be that of the file.
  9490. :param filename: Excellon file filename
  9491. :type filename: str
  9492. :param plot: boolean, to plot or not the resulting object
  9493. :param from_tcl: True if run from Tcl Shell
  9494. :return: None
  9495. """
  9496. App.log.debug("open_excellon()")
  9497. # How the object should be initialized
  9498. def obj_init(excellon_obj, app_obj):
  9499. try:
  9500. ret = excellon_obj.parse_file(filename=filename)
  9501. if ret == "fail":
  9502. log.debug("Excellon parsing failed.")
  9503. self.inform.emit('[ERROR_NOTCL] %s' %
  9504. _("This is not Excellon file."))
  9505. return "fail"
  9506. except IOError:
  9507. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  9508. (_("Cannot open file"), filename))
  9509. log.debug("Could not open Excellon object.")
  9510. return "fail"
  9511. except Exception:
  9512. msg = '[ERROR_NOTCL] %s' % \
  9513. _("An internal error has occurred. See shell.\n")
  9514. msg += traceback.format_exc()
  9515. app_obj.inform.emit(msg)
  9516. return "fail"
  9517. ret = excellon_obj.create_geometry()
  9518. if ret == 'fail':
  9519. log.debug("Could not create geometry for Excellon object.")
  9520. return "fail"
  9521. for tool in excellon_obj.tools:
  9522. if excellon_obj.tools[tool]['solid_geometry']:
  9523. return
  9524. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  9525. return "fail"
  9526. with self.proc_container.new(_("Opening Excellon.")):
  9527. # Object name
  9528. name = outname or filename.split('/')[-1].split('\\')[-1]
  9529. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  9530. if ret_val == 'fail':
  9531. if from_tcl:
  9532. filename = self.defaults['global_tcl_path'] + '/' + name
  9533. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  9534. if ret_val == 'fail':
  9535. self.inform.emit('[ERROR_NOTCL] %s' %
  9536. _('Open Excellon file failed. Probable not an Excellon file.'))
  9537. return
  9538. # Register recent file
  9539. self.file_opened.emit("excellon", filename)
  9540. # GUI feedback
  9541. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9542. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  9543. """
  9544. Opens a G-gcode file, parses it and creates a new object for
  9545. it in the program. Thread-safe.
  9546. :param filename: G-code file filename
  9547. :param outname: Name of the resulting object. None causes the name to be that of the file.
  9548. :param force_parsing:
  9549. :param plot: If True plot the object on canvas
  9550. :param from_tcl: True if run from Tcl Shell
  9551. :return: None
  9552. """
  9553. App.log.debug("open_gcode()")
  9554. # How the object should be initialized
  9555. def obj_init(job_obj, app_obj_):
  9556. """
  9557. :param job_obj: the resulting object
  9558. :type app_obj_: App
  9559. """
  9560. assert isinstance(app_obj_, App), \
  9561. "Initializer expected App, got %s" % type(app_obj_)
  9562. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  9563. try:
  9564. f = open(filename)
  9565. gcode = f.read()
  9566. f.close()
  9567. except IOError:
  9568. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  9569. return "fail"
  9570. job_obj.gcode = gcode
  9571. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  9572. if gcode_ret == "fail":
  9573. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  9574. return "fail"
  9575. job_obj.create_geometry()
  9576. with self.proc_container.new(_("Opening G-Code.")):
  9577. # Object name
  9578. name = outname or filename.split('/')[-1].split('\\')[-1]
  9579. # New object creation and file processing
  9580. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  9581. if ret_val == 'fail':
  9582. if from_tcl:
  9583. filename = self.defaults['global_tcl_path'] + '/' + name
  9584. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  9585. if ret_val == 'fail':
  9586. self.inform.emit('[ERROR_NOTCL] %s' %
  9587. _("Failed to create CNCJob Object. Probable not a GCode file. "
  9588. "Try to load it from File menu.\n "
  9589. "Attempting to create a FlatCAM CNCJob Object from "
  9590. "G-Code file failed during processing"))
  9591. return "fail"
  9592. # Register recent file
  9593. self.file_opened.emit("cncjob", filename)
  9594. # GUI feedback
  9595. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9596. def open_hpgl2(self, filename, outname=None):
  9597. """
  9598. Opens a HPGL2 file, parses it and creates a new object for
  9599. it in the program. Thread-safe.
  9600. :param outname: Name of the resulting object. None causes the name to be that of the file.
  9601. :param filename: HPGL2 file filename
  9602. :return: None
  9603. """
  9604. filename = filename
  9605. # How the object should be initialized
  9606. def obj_init(geo_obj, app_obj):
  9607. assert isinstance(geo_obj, GeometryObject), \
  9608. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  9609. # Opening the file happens here
  9610. obj = HPGL2(self)
  9611. try:
  9612. HPGL2.parse_file(obj, filename)
  9613. except IOError:
  9614. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  9615. return "fail"
  9616. except ParseError as err:
  9617. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  9618. app_obj.log.error(str(err))
  9619. return "fail"
  9620. except Exception as e:
  9621. log.debug("App.open_hpgl2() --> %s" % str(e))
  9622. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  9623. msg += traceback.format_exc()
  9624. app_obj.inform.emit(msg)
  9625. return "fail"
  9626. geo_obj.multigeo = True
  9627. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  9628. geo_obj.tools = deepcopy(obj.tools)
  9629. geo_obj.source_file = deepcopy(obj.source_file)
  9630. del obj
  9631. if not geo_obj.solid_geometry:
  9632. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  9633. _("Object is not HPGL2 file or empty. Aborting object creation."))
  9634. return "fail"
  9635. App.log.debug("open_hpgl2()")
  9636. with self.proc_container.new(_("Opening HPGL2")) as proc:
  9637. # Object name
  9638. name = outname or filename.split('/')[-1].split('\\')[-1]
  9639. # # ## Object creation # ##
  9640. ret = self.new_object("geometry", name, obj_init, autoselected=False)
  9641. if ret == 'fail':
  9642. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  9643. return 'fail'
  9644. # Register recent file
  9645. self.file_opened.emit("geometry", filename)
  9646. # GUI feedback
  9647. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9648. def open_script(self, filename, outname=None, silent=False):
  9649. """
  9650. Opens a Script file, parses it and creates a new object for
  9651. it in the program. Thread-safe.
  9652. :param outname: Name of the resulting object. None causes the name to be that of the file.
  9653. :param filename: Script file filename
  9654. :return: None
  9655. """
  9656. App.log.debug("open_script()")
  9657. with self.proc_container.new(_("Opening TCL Script...")):
  9658. try:
  9659. with open(filename, "r") as opened_script:
  9660. script_content = opened_script.readlines()
  9661. script_content = ''.join(script_content)
  9662. if silent is False:
  9663. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  9664. except Exception as e:
  9665. log.debug("App.open_script() -> %s" % str(e))
  9666. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to open TCL Script."))
  9667. return
  9668. # Object name
  9669. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  9670. # New object creation and file processing
  9671. self.on_filenewscript(name=script_name, text=script_content)
  9672. # Register recent file
  9673. self.file_opened.emit("script", filename)
  9674. # GUI feedback
  9675. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9676. def open_config_file(self, filename, run_from_arg=None):
  9677. """
  9678. Loads a config file from the specified file.
  9679. :param filename: Name of the file from which to load.
  9680. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  9681. :return: None
  9682. """
  9683. App.log.debug("Opening config file: " + filename)
  9684. if run_from_arg:
  9685. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  9686. "Canvas initialization finished in"), '%.2f' % self.used_time,
  9687. _("Opening FlatCAM Config file.")),
  9688. alignment=Qt.AlignBottom | Qt.AlignLeft,
  9689. color=QtGui.QColor("gray"))
  9690. # # add the tab if it was closed
  9691. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  9692. # # first clear previous text in text editor (if any)
  9693. # self.ui.text_editor_tab.code_editor.clear()
  9694. #
  9695. # # Switch plot_area to CNCJob tab
  9696. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  9697. # close the Code editor if already open
  9698. if self.toggle_codeeditor:
  9699. self.on_toggle_code_editor()
  9700. self.on_toggle_code_editor()
  9701. try:
  9702. if filename:
  9703. f = QtCore.QFile(filename)
  9704. if f.open(QtCore.QIODevice.ReadOnly):
  9705. stream = QtCore.QTextStream(f)
  9706. code_edited = stream.readAll()
  9707. self.text_editor_tab.code_editor.setPlainText(code_edited)
  9708. f.close()
  9709. except IOError:
  9710. App.log.error("Failed to open config file: %s" % filename)
  9711. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9712. (_("Failed to open config file"), filename))
  9713. return
  9714. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  9715. """
  9716. Loads a project from the specified file.
  9717. 1) Loads and parses file
  9718. 2) Registers the file as recently opened.
  9719. 3) Calls on_file_new()
  9720. 4) Updates options
  9721. 5) Calls new_object() with the object's from_dict() as init method.
  9722. 6) Calls plot_all() if plot=True
  9723. :param filename: Name of the file from which to load.
  9724. :param run_from_arg: True if run for arguments
  9725. :param plot: If True plot all objects in the project
  9726. :param cli: Run from command line
  9727. :param from_tcl: True if run from Tcl Sehll
  9728. :return: None
  9729. """
  9730. App.log.debug("Opening project: " + filename)
  9731. # block autosaving while a project is loaded
  9732. self.block_autosave = True
  9733. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9734. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9735. if cli is None:
  9736. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  9737. if run_from_arg:
  9738. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  9739. "Canvas initialization finished in"), '%.2f' % self.used_time,
  9740. _("Opening FlatCAM Project file.")),
  9741. alignment=Qt.AlignBottom | Qt.AlignLeft,
  9742. color=QtGui.QColor("gray"))
  9743. # Open and parse an uncompressed Project file
  9744. try:
  9745. f = open(filename, 'r')
  9746. except IOError:
  9747. if from_tcl:
  9748. name = filename.split('/')[-1].split('\\')[-1]
  9749. filename = self.defaults['global_tcl_path'] + '/' + name
  9750. try:
  9751. f = open(filename, 'r')
  9752. except IOError:
  9753. log.error("Failed to open project file: %s" % filename)
  9754. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  9755. return
  9756. else:
  9757. log.error("Failed to open project file: %s" % filename)
  9758. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  9759. return
  9760. try:
  9761. d = json.load(f, object_hook=dict2obj)
  9762. except Exception as e:
  9763. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  9764. (filename, str(e)))
  9765. f.close()
  9766. # Open and parse a compressed Project file
  9767. try:
  9768. with lzma.open(filename) as f:
  9769. file_content = f.read().decode('utf-8')
  9770. d = json.loads(file_content, object_hook=dict2obj)
  9771. except Exception as e:
  9772. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  9773. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9774. (_("Failed to open project file"), filename))
  9775. return
  9776. # Clear the current project
  9777. # # NOT THREAD SAFE # ##
  9778. if run_from_arg is True:
  9779. pass
  9780. elif cli is True:
  9781. self.delete_selection_shape()
  9782. else:
  9783. self.on_file_new()
  9784. # Project options
  9785. self.options.update(d['options'])
  9786. self.project_filename = filename
  9787. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9788. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9789. if cli is None:
  9790. self.set_screen_units(self.options["units"])
  9791. # Re create objects
  9792. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  9793. for obj in d['objs']:
  9794. try:
  9795. def obj_init(obj_inst, app_inst):
  9796. obj_inst.from_dict(obj)
  9797. App.log.debug("Recreating from opened project an %s object: %s" %
  9798. (obj['kind'].capitalize(), obj['options']['name']))
  9799. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9800. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9801. if cli is None:
  9802. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  9803. obj['kind'].upper(),
  9804. obj['options']['name']
  9805. )
  9806. )
  9807. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  9808. except Exception as e:
  9809. print('App.open_project() --> ' + str(e))
  9810. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  9811. self.should_we_save = False
  9812. self.file_opened.emit("project", filename)
  9813. # restore autosaving after a project was loaded
  9814. self.block_autosave = False
  9815. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9816. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9817. if cli is None:
  9818. self.set_ui_title(name=self.project_filename)
  9819. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  9820. def propagate_defaults(self, silent=False):
  9821. """
  9822. This method is used to set default values in classes. It's
  9823. an alternative to project options but allows the use
  9824. of values invisible to the user.
  9825. :param silent: No messages
  9826. :return: None
  9827. """
  9828. if silent is False:
  9829. self.log.debug("propagate_defaults()")
  9830. # Which objects to update the given parameters.
  9831. routes = {
  9832. "global_zdownrate": CNCjob,
  9833. "excellon_zeros": Excellon,
  9834. "excellon_format_upper_in": Excellon,
  9835. "excellon_format_lower_in": Excellon,
  9836. "excellon_format_upper_mm": Excellon,
  9837. "excellon_format_lower_mm": Excellon,
  9838. "excellon_units": Excellon,
  9839. "gerber_use_buffer_for_union": Gerber,
  9840. "geometry_multidepth": Geometry
  9841. }
  9842. for param in routes:
  9843. if param in routes[param].defaults:
  9844. try:
  9845. routes[param].defaults[param] = self.defaults[param]
  9846. if silent is False:
  9847. self.log.debug(" " + param + " OK")
  9848. except KeyError:
  9849. if silent is False:
  9850. self.log.debug("FlatCAMApp.propagate_defaults() --> ERROR: " + param + " not in defaults.")
  9851. else:
  9852. # Try extracting the name:
  9853. # classname_param here is param in the object
  9854. if param.find(routes[param].__name__.lower() + "_") == 0:
  9855. p = param[len(routes[param].__name__) + 1:]
  9856. if p in routes[param].defaults:
  9857. routes[param].defaults[p] = self.defaults[param]
  9858. if silent is False:
  9859. self.log.debug(" " + param + " OK!")
  9860. def plot_all(self, fit_view=True, use_thread=True):
  9861. """
  9862. Re-generates all plots from all objects.
  9863. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  9864. :param use_thread: if True will use threading for plotting the objects
  9865. :return: None
  9866. """
  9867. self.log.debug("Plot_all()")
  9868. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  9869. for plot_obj in self.collection.get_list():
  9870. def worker_task(obj):
  9871. with self.proc_container.new("Plotting"):
  9872. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  9873. if fit_view is True:
  9874. self.object_plotted.emit(obj)
  9875. if use_thread is True:
  9876. # Send to worker
  9877. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  9878. else:
  9879. worker_task(plot_obj)
  9880. def register_folder(self, filename):
  9881. """
  9882. Register the last folder used by the app to open something
  9883. :param filename: the last folder is extracted from the filename
  9884. :return: None
  9885. """
  9886. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  9887. def register_save_folder(self, filename):
  9888. """
  9889. Register the last folder used by the app to save something
  9890. :param filename: the last folder is extracted from the filename
  9891. :return: None
  9892. """
  9893. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  9894. # def set_progress_bar(self, percentage, text=""):
  9895. # """
  9896. # Set a progress bar to a value (percentage)
  9897. #
  9898. # :param percentage: Value set to the progressbar
  9899. # :param text: Not used
  9900. # :return: None
  9901. # """
  9902. # self.ui.progress_bar.setValue(int(percentage))
  9903. def setup_recent_items(self):
  9904. """
  9905. Setup a dictionary with the recent files accessed, organized by type
  9906. :return:
  9907. """
  9908. icons = {
  9909. "gerber": self.resource_location + "/flatcam_icon16.png",
  9910. "excellon": self.resource_location + "/drill16.png",
  9911. 'geometry': self.resource_location + "/geometry16.png",
  9912. "cncjob": self.resource_location + "/cnc16.png",
  9913. "script": self.resource_location + "/script_new24.png",
  9914. "document": self.resource_location + "/notes16_1.png",
  9915. "project": self.resource_location + "/project16.png",
  9916. "svg": self.resource_location + "/geometry16.png",
  9917. "dxf": self.resource_location + "/dxf16.png",
  9918. "pdf": self.resource_location + "/pdf32.png",
  9919. "image": self.resource_location + "/image16.png"
  9920. }
  9921. try:
  9922. image_opener = self.image_tool.import_image
  9923. except AttributeError:
  9924. image_opener = None
  9925. openers = {
  9926. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  9927. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  9928. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  9929. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  9930. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  9931. "document": None,
  9932. 'project': self.open_project,
  9933. 'svg': self.import_svg,
  9934. 'dxf': self.import_dxf,
  9935. 'image': image_opener,
  9936. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  9937. }
  9938. # Open recent file for files
  9939. try:
  9940. f = open(self.data_path + '/recent.json')
  9941. except IOError:
  9942. App.log.error("Failed to load recent item list.")
  9943. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  9944. return
  9945. try:
  9946. self.recent = json.load(f)
  9947. except json.errors.JSONDecodeError:
  9948. App.log.error("Failed to parse recent item list.")
  9949. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  9950. f.close()
  9951. return
  9952. f.close()
  9953. # Open recent file for projects
  9954. try:
  9955. fp = open(self.data_path + '/recent_projects.json')
  9956. except IOError:
  9957. App.log.error("Failed to load recent project item list.")
  9958. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  9959. return
  9960. try:
  9961. self.recent_projects = json.load(fp)
  9962. except json.errors.JSONDecodeError:
  9963. App.log.error("Failed to parse recent project item list.")
  9964. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  9965. fp.close()
  9966. return
  9967. fp.close()
  9968. # Closure needed to create callbacks in a loop.
  9969. # Otherwise late binding occurs.
  9970. def make_callback(func, fname):
  9971. def opener():
  9972. func(fname)
  9973. return opener
  9974. def reset_recent_files():
  9975. # Reset menu
  9976. self.ui.recent.clear()
  9977. self.recent = []
  9978. try:
  9979. ff = open(self.data_path + '/recent.json', 'w')
  9980. except IOError:
  9981. App.log.error("Failed to open recent items file for writing.")
  9982. return
  9983. json.dump(self.recent, ff)
  9984. def reset_recent_projects():
  9985. # Reset menu
  9986. self.ui.recent_projects.clear()
  9987. self.recent_projects = []
  9988. try:
  9989. frp = open(self.data_path + '/recent_projects.json', 'w')
  9990. except IOError:
  9991. App.log.error("Failed to open recent projects items file for writing.")
  9992. return
  9993. json.dump(self.recent, frp)
  9994. # Reset menu
  9995. self.ui.recent.clear()
  9996. self.ui.recent_projects.clear()
  9997. # Create menu items for projects
  9998. for recent in self.recent_projects:
  9999. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  10000. if recent['kind'] == 'project':
  10001. try:
  10002. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  10003. # Attach callback
  10004. o = make_callback(openers[recent["kind"]], recent['filename'])
  10005. action.triggered.connect(o)
  10006. self.ui.recent_projects.addAction(action)
  10007. except KeyError:
  10008. App.log.error("Unsupported file type: %s" % recent["kind"])
  10009. # Last action in Recent Files menu is one that Clear the content
  10010. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  10011. (_("Clear Recent projects")), self)
  10012. clear_action_proj.triggered.connect(reset_recent_projects)
  10013. self.ui.recent_projects.addSeparator()
  10014. self.ui.recent_projects.addAction(clear_action_proj)
  10015. # Create menu items for files
  10016. for recent in self.recent:
  10017. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  10018. if recent['kind'] != 'project':
  10019. try:
  10020. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  10021. # Attach callback
  10022. o = make_callback(openers[recent["kind"]], recent['filename'])
  10023. action.triggered.connect(o)
  10024. self.ui.recent.addAction(action)
  10025. except KeyError:
  10026. App.log.error("Unsupported file type: %s" % recent["kind"])
  10027. # Last action in Recent Files menu is one that Clear the content
  10028. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  10029. (_("Clear Recent files")), self)
  10030. clear_action.triggered.connect(reset_recent_files)
  10031. self.ui.recent.addSeparator()
  10032. self.ui.recent.addAction(clear_action)
  10033. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  10034. # self.ui.menufilerecent.set_submenu(recent_menu)
  10035. # recent_menu.show_all()
  10036. # self.ui.recent.show()
  10037. self.log.debug("Recent items list has been populated.")
  10038. def setup_component_editor(self):
  10039. """
  10040. Default text for the Selected tab when is not taken by the Object UI.
  10041. :return:
  10042. """
  10043. # label = QtWidgets.QLabel("Choose an item from Project")
  10044. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  10045. sel_title = QtWidgets.QTextEdit(
  10046. _('<b>Shortcut Key List</b>'))
  10047. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  10048. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  10049. f_settings = QSettings("Open Source", "FlatCAM")
  10050. if f_settings.contains("notebook_font_size"):
  10051. fsize = f_settings.value('notebook_font_size', type=int)
  10052. else:
  10053. fsize = 12
  10054. tsize = fsize + int(fsize / 2)
  10055. # selected_text = (_('''
  10056. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  10057. # </p>
  10058. #
  10059. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  10060. # The normal flow when working in FlatCAM is the following:</span></p>
  10061. #
  10062. # <ol>
  10063. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  10064. # file into
  10065. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  10066. # even dragging and dropping the files on the GUI.<br />
  10067. # <br />
  10068. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  10069. # drop of the
  10070. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  10071. # &nbsp;</li>
  10072. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  10073. # and then
  10074. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  10075. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  10076. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  10077. # <br />
  10078. # If the selection of the object is done on the canvas by single click instead, and the
  10079. # <strong>SELECTED TAB</strong>
  10080. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  10081. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  10082. # it even if it was out of focus.<br />
  10083. # <br />
  10084. # You can change the parameters in this screen and the flow direction is like this:<br />
  10085. # <br />
  10086. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  10087. # <strong> Geometry Object
  10088. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  10089. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  10090. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  10091. # </ol>
  10092. #
  10093. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  10094. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  10095. # <strong>F3</strong>.</span></p>
  10096. #
  10097. # ''').format(fsize=fsize, tsize=tsize))
  10098. selected_text = '''
  10099. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  10100. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  10101. {s1}</span></p>
  10102. <ol>
  10103. <li><span style="font-size:{fsize}px">{s2}<br />
  10104. <br />
  10105. {s3}</span><br />
  10106. &nbsp;</li>
  10107. <li><span style="font-size:{fsize}px">{s4}<br />
  10108. &nbsp;</li>
  10109. <br />
  10110. <li><span style="font-size:{fsize}px">{s5}<br />
  10111. &nbsp;</li>
  10112. <br />
  10113. <li><span style="font-size:{fsize}px">{s6}<br />
  10114. <br />
  10115. {s7}</span></li>
  10116. </ol>
  10117. <p><span style="font-size:{fsize}px">{s8}</span></p>
  10118. '''.format(
  10119. title=_("Selected Tab - Choose an Item from Project Tab"),
  10120. subtitle=_("Details"),
  10121. s1=_("The normal flow when working in FlatCAM is the following:"),
  10122. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  10123. "using either the toolbars, key shortcuts or even dragging and dropping the "
  10124. "files on the GUI."),
  10125. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  10126. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  10127. "actions offered within the app."),
  10128. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  10129. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  10130. "SELECTED TAB will be updated with the object properties according to its kind: "
  10131. "Gerber, Excellon, Geometry or CNCJob object."),
  10132. s5=_("If the selection of the object is done on the canvas by single click instead, "
  10133. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  10134. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  10135. "the SELECTED TAB and populate it even if it was out of focus."),
  10136. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  10137. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  10138. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  10139. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  10140. "(again, done in SELECTED TAB) --> Save GCode."),
  10141. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  10142. "or through its own key shortcut: <b>F3</b>."),
  10143. tsize=tsize,
  10144. fsize=fsize
  10145. )
  10146. sel_title.setText(selected_text)
  10147. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  10148. self.ui.selected_scroll_area.setWidget(sel_title)
  10149. def setup_obj_classes(self):
  10150. """
  10151. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  10152. class.
  10153. :return: None
  10154. """
  10155. FlatCAMObj.app = self
  10156. ObjectCollection.app = self
  10157. Gerber.app = self
  10158. Excellon.app = self
  10159. Geometry.app = self
  10160. CNCjob.app = self
  10161. FCProcess.app = self
  10162. FCProcessContainer.app = self
  10163. OptionsGroupUI.app = self
  10164. def version_check(self):
  10165. """
  10166. Checks for the latest version of the program. Alerts the
  10167. user if theirs is outdated. This method is meant to be run
  10168. in a separate thread.
  10169. :return: None
  10170. """
  10171. self.log.debug("version_check()")
  10172. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  10173. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  10174. App.version_url,
  10175. str(self.defaults['global_serial']),
  10176. str(self.version),
  10177. str(self.os),
  10178. urllib.parse.urlencode(self.defaults["global_stats"])
  10179. )
  10180. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  10181. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  10182. # urllib.parse.urlencode(self.defaults["global_stats"])
  10183. else:
  10184. # no_stats dict; just so it won't break things on website
  10185. no_ststs_dict = {}
  10186. no_ststs_dict["global_ststs"] = {}
  10187. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version) +\
  10188. "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  10189. App.log.debug("Checking for updates @ %s" % full_url)
  10190. # ## Get the data
  10191. try:
  10192. f = urllib.request.urlopen(full_url)
  10193. except Exception:
  10194. # App.log.warning("Failed checking for latest version. Could not connect.")
  10195. self.log.warning("Failed checking for latest version. Could not connect.")
  10196. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  10197. return
  10198. try:
  10199. data = json.load(f)
  10200. except Exception as e:
  10201. App.log.error("Could not parse information about latest version.")
  10202. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  10203. App.log.debug("json.load(): %s" % str(e))
  10204. f.close()
  10205. return
  10206. f.close()
  10207. # ## Latest version?
  10208. if self.version >= data["version"]:
  10209. App.log.debug("FlatCAM is up to date!")
  10210. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  10211. return
  10212. App.log.debug("Newer version available.")
  10213. self.message.emit(
  10214. _("Newer Version Available"),
  10215. '%s<br><br>><b>%s</b><br>%s' % (
  10216. _("There is a newer version of FlatCAM available for download:"),
  10217. str(data["name"]),
  10218. str(data["message"])
  10219. ),
  10220. _("info")
  10221. )
  10222. def on_plotcanvas_setup(self, container=None):
  10223. """
  10224. This is doing the setup for the plot area (canvas).
  10225. :param container: QT Widget where to install the canvas
  10226. :return: None
  10227. """
  10228. if container:
  10229. plot_container = container
  10230. else:
  10231. plot_container = self.ui.right_layout
  10232. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  10233. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  10234. self.is_legacy = True
  10235. self.defaults["global_graphic_engine"] = "2D"
  10236. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  10237. else:
  10238. try:
  10239. self.plotcanvas = PlotCanvas(plot_container, self)
  10240. except Exception as er:
  10241. msg_txt = traceback.format_exc()
  10242. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  10243. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  10244. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  10245. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  10246. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  10247. msg += msg_txt
  10248. self.inform.emit(msg)
  10249. return 'fail'
  10250. # So it can receive key presses
  10251. self.plotcanvas.native.setFocus()
  10252. if self.is_legacy is False:
  10253. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  10254. # Set the mouse button for panning
  10255. self.plotcanvas.view.camera.pan_button_setting = pan_button
  10256. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  10257. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  10258. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  10259. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  10260. # Keys over plot enabled
  10261. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  10262. if self.defaults['global_cursor_type'] == 'small':
  10263. self.app_cursor = self.plotcanvas.new_cursor()
  10264. else:
  10265. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  10266. if self.ui.grid_snap_btn.isChecked():
  10267. self.app_cursor.enabled = True
  10268. else:
  10269. self.app_cursor.enabled = False
  10270. if self.is_legacy is False:
  10271. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  10272. else:
  10273. # will use the default Matplotlib axes
  10274. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  10275. def on_zoom_fit(self, event):
  10276. """
  10277. Callback for zoom-fit request. This can be either from the corresponding
  10278. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  10279. with axes limits from the geometry bounds of all objects.
  10280. :param event: Ignored.
  10281. :return: None
  10282. """
  10283. if self.is_legacy is False:
  10284. self.plotcanvas.fit_view()
  10285. else:
  10286. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  10287. width = xmax - xmin
  10288. height = ymax - ymin
  10289. xmin -= 0.05 * width
  10290. xmax += 0.05 * width
  10291. ymin -= 0.05 * height
  10292. ymax += 0.05 * height
  10293. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  10294. def on_zoom_in(self):
  10295. """
  10296. Callback for zoom-in request.
  10297. :return:
  10298. """
  10299. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  10300. def on_zoom_out(self):
  10301. """
  10302. Callback for zoom-out request.
  10303. :return:
  10304. """
  10305. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  10306. def disable_all_plots(self):
  10307. self.report_usage("disable_all_plots()")
  10308. self.disable_plots(self.collection.get_list())
  10309. self.inform.emit('[success] %s' %
  10310. _("All plots disabled."))
  10311. def disable_other_plots(self):
  10312. self.report_usage("disable_other_plots()")
  10313. self.disable_plots(self.collection.get_non_selected())
  10314. self.inform.emit('[success] %s' %
  10315. _("All non selected plots disabled."))
  10316. def enable_all_plots(self):
  10317. self.report_usage("enable_all_plots()")
  10318. self.enable_plots(self.collection.get_list())
  10319. self.inform.emit('[success] %s' %
  10320. _("All plots enabled."))
  10321. def on_enable_sel_plots(self):
  10322. log.debug("App.on_enable_sel_plot()")
  10323. object_list = self.collection.get_selected()
  10324. self.enable_plots(objects=object_list)
  10325. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  10326. def on_disable_sel_plots(self):
  10327. log.debug("App.on_disable_sel_plot()")
  10328. # self.inform.emit(_("Disabling plots ..."))
  10329. object_list = self.collection.get_selected()
  10330. self.disable_plots(objects=object_list)
  10331. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  10332. def enable_plots(self, objects):
  10333. """
  10334. Enable plots
  10335. :param objects: list of Objects to be enabled
  10336. :return:
  10337. """
  10338. log.debug("Enabling plots ...")
  10339. # self.inform.emit(_("Working ..."))
  10340. for obj in objects:
  10341. if obj.options['plot'] is False:
  10342. obj.options.set_change_callback(lambda x: None)
  10343. obj.options['plot'] = True
  10344. try:
  10345. # only the Gerber obj has on_plot_cb_click() method
  10346. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  10347. # disable this cb while disconnected,
  10348. # in case the operation takes time the user is not allowed to change it
  10349. obj.ui.plot_cb.setDisabled(True)
  10350. except AttributeError:
  10351. pass
  10352. obj.set_form_item("plot")
  10353. try:
  10354. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  10355. obj.ui.plot_cb.setDisabled(False)
  10356. except AttributeError:
  10357. pass
  10358. obj.options.set_change_callback(obj.on_options_change)
  10359. def worker_task(objs):
  10360. with self.proc_container.new(_("Enabling plots ...")):
  10361. for plot_obj in objs:
  10362. # obj.options['plot'] = True
  10363. if isinstance(plot_obj, CNCJobObject):
  10364. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  10365. else:
  10366. plot_obj.plot(visible=True)
  10367. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  10368. # self.plots_updated.emit()
  10369. def disable_plots(self, objects):
  10370. """
  10371. Disables plots
  10372. :param objects: list of Objects to be disabled
  10373. :return:
  10374. """
  10375. # if no objects selected then do nothing
  10376. if not self.collection.get_selected():
  10377. return
  10378. log.debug("Disabling plots ...")
  10379. # self.inform.emit(_("Working ..."))
  10380. for obj in objects:
  10381. if obj.options['plot'] is True:
  10382. obj.options.set_change_callback(lambda x: None)
  10383. obj.options['plot'] = False
  10384. try:
  10385. # only the Gerber obj has on_plot_cb_click() method
  10386. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  10387. obj.ui.plot_cb.setDisabled(True)
  10388. except AttributeError:
  10389. pass
  10390. obj.set_form_item("plot")
  10391. try:
  10392. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  10393. obj.ui.plot_cb.setDisabled(False)
  10394. except AttributeError:
  10395. pass
  10396. obj.options.set_change_callback(obj.on_options_change)
  10397. try:
  10398. self.delete_selection_shape()
  10399. except Exception as e:
  10400. log.debug("App.disable_plots() --> %s" % str(e))
  10401. # self.plots_updated.emit()
  10402. def worker_task(objs):
  10403. with self.proc_container.new(_("Disabling plots ...")):
  10404. for plot_obj in objs:
  10405. # obj.options['plot'] = True
  10406. if isinstance(plot_obj, CNCJobObject):
  10407. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  10408. else:
  10409. plot_obj.plot(visible=False)
  10410. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  10411. def toggle_plots(self, objects):
  10412. """
  10413. Toggle plots visibility
  10414. :param objects: list of Objects for which to be toggled the visibility
  10415. :return: None
  10416. """
  10417. # if no objects selected then do nothing
  10418. if not self.collection.get_selected():
  10419. return
  10420. log.debug("Toggling plots ...")
  10421. self.inform.emit(_("Working ..."))
  10422. for obj in objects:
  10423. if obj.options['plot'] is False:
  10424. obj.options['plot'] = True
  10425. else:
  10426. obj.options['plot'] = False
  10427. self.plots_updated.emit()
  10428. def clear_plots(self):
  10429. """
  10430. Clear the plots
  10431. :return: None
  10432. """
  10433. objects = self.collection.get_list()
  10434. for obj in objects:
  10435. obj.clear(obj == objects[-1])
  10436. # Clear pool to free memory
  10437. self.clear_pool()
  10438. def on_set_color_action_triggered(self):
  10439. """
  10440. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  10441. :return:
  10442. """
  10443. new_color = self.defaults['gerber_plot_fill']
  10444. clicked_action = self.sender()
  10445. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  10446. act_name = clicked_action.text()
  10447. sel_obj_list = self.collection.get_selected()
  10448. if not sel_obj_list:
  10449. return
  10450. # a default value, I just chose this one
  10451. alpha_level = 'BF'
  10452. for sel_obj in sel_obj_list:
  10453. if sel_obj.kind == 'excellon':
  10454. alpha_level = str(hex(
  10455. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  10456. elif sel_obj.kind == 'gerber':
  10457. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  10458. elif sel_obj.kind == 'geometry':
  10459. alpha_level = 'FF'
  10460. else:
  10461. log.debug(
  10462. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  10463. continue
  10464. sel_obj.alpha_level = alpha_level
  10465. if act_name == _('Red'):
  10466. new_color = '#FF0000' + alpha_level
  10467. if act_name == _('Blue'):
  10468. new_color = '#0000FF' + alpha_level
  10469. if act_name == _('Yellow'):
  10470. new_color = '#FFDF00' + alpha_level
  10471. if act_name == _('Green'):
  10472. new_color = '#00FF00' + alpha_level
  10473. if act_name == _('Purple'):
  10474. new_color = '#FF00FF' + alpha_level
  10475. if act_name == _('Brown'):
  10476. new_color = '#A52A2A' + alpha_level
  10477. if act_name == _('White'):
  10478. new_color = '#FFFFFF' + alpha_level
  10479. if act_name == _('Black'):
  10480. new_color = '#000000' + alpha_level
  10481. if act_name == _('Custom'):
  10482. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  10483. c_dialog = QtWidgets.QColorDialog()
  10484. plot_fill_color = c_dialog.getColor(initial=new_color)
  10485. if plot_fill_color.isValid() is False:
  10486. return
  10487. new_color = str(plot_fill_color.name()) + alpha_level
  10488. if act_name == _("Default"):
  10489. for sel_obj in sel_obj_list:
  10490. if sel_obj.kind == 'excellon':
  10491. new_color = self.defaults['excellon_plot_fill']
  10492. new_line_color = self.defaults['excellon_plot_line']
  10493. elif sel_obj.kind == 'gerber':
  10494. new_color = self.defaults['gerber_plot_fill']
  10495. new_line_color = self.defaults['gerber_plot_line']
  10496. elif sel_obj.kind == 'geometry':
  10497. new_color = self.defaults['geometry_plot_line']
  10498. new_line_color = self.defaults['geometry_plot_line']
  10499. else:
  10500. log.debug(
  10501. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  10502. continue
  10503. sel_obj.fill_color = new_color
  10504. sel_obj.outline_color = new_line_color
  10505. sel_obj.shapes.redraw(
  10506. update_colors=(new_color, new_line_color)
  10507. )
  10508. return
  10509. if act_name == _("Opacity"):
  10510. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  10511. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  10512. if ok_button:
  10513. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  10514. for sel_obj in sel_obj_list:
  10515. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  10516. sel_obj.shapes.redraw(
  10517. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  10518. )
  10519. return
  10520. new_line_color = color_variant(new_color[:7], 0.7)
  10521. if act_name == _("White"):
  10522. new_line_color = color_variant("#dedede", 0.7)
  10523. for sel_obj in sel_obj_list:
  10524. sel_obj.fill_color = new_color
  10525. sel_obj.outline_color = new_line_color
  10526. sel_obj.shapes.redraw(
  10527. update_colors=(new_color, new_line_color)
  10528. )
  10529. def on_grid_snap_triggered(self, state):
  10530. """
  10531. :param state: A parameter with the state of the grid, boolean
  10532. :return:
  10533. """
  10534. if state:
  10535. self.ui.snap_infobar_label.setPixmap(QtGui.QPixmap(self.resource_location + '/snap_filled_16.png'))
  10536. else:
  10537. self.ui.snap_infobar_label.setPixmap(QtGui.QPixmap(self.resource_location + '/snap_16.png'))
  10538. self.ui.snap_infobar_label.clicked_state = state
  10539. def on_grid_icon_snap_clicked(self):
  10540. """
  10541. Slot called by clicking a GUI element, in this case a FCLabel
  10542. :return:
  10543. """
  10544. if isinstance(self.sender(), FCLabel):
  10545. self.ui.grid_snap_btn.trigger()
  10546. def generate_cnc_job(self, objects):
  10547. """
  10548. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  10549. :param objects: Selected objects in the Project Tab
  10550. :return:
  10551. """
  10552. self.report_usage("generate_cnc_job()")
  10553. # for obj in objects:
  10554. # obj.generatecncjob()
  10555. for obj in objects:
  10556. obj.on_generatecnc_button_click()
  10557. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  10558. """
  10559. Saves the current project to the specified file.
  10560. :param filename: Name of the file in which to save.
  10561. :type filename: str
  10562. :param quit_action: if the project saving will be followed by an app quit; boolean
  10563. :param silent: if True will not display status messages
  10564. :param from_tcl True is run from Tcl Shell
  10565. :return: None
  10566. """
  10567. self.log.debug("save_project()")
  10568. self.save_in_progress = True
  10569. with self.proc_container.new(_("Saving FlatCAM Project")):
  10570. # Capture the latest changes
  10571. # Current object
  10572. try:
  10573. current_object = self.collection.get_active()
  10574. if current_object:
  10575. current_object.read_form()
  10576. except Exception as e:
  10577. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  10578. pass
  10579. # Serialize the whole project
  10580. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  10581. "options": self.options,
  10582. "version": self.version}
  10583. if self.defaults["global_save_compressed"] is True:
  10584. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  10585. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  10586. # # Write
  10587. f.write(g)
  10588. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  10589. else:
  10590. # Open file
  10591. try:
  10592. f = open(filename, 'w')
  10593. except IOError:
  10594. App.log.error("Failed to open file for saving: %s", filename)
  10595. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  10596. return
  10597. # Write
  10598. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  10599. f.close()
  10600. # verification of the saved project
  10601. # Open and parse
  10602. try:
  10603. saved_f = open(filename, 'r')
  10604. except IOError:
  10605. if silent is False:
  10606. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  10607. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  10608. return
  10609. try:
  10610. saved_d = json.load(saved_f, object_hook=dict2obj)
  10611. except Exception:
  10612. if silent is False:
  10613. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  10614. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  10615. f.close()
  10616. return
  10617. saved_f.close()
  10618. if silent is False:
  10619. if 'version' in saved_d:
  10620. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  10621. else:
  10622. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  10623. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  10624. tb_settings = QSettings("Open Source", "FlatCAM")
  10625. lock_state = self.ui.lock_action.isChecked()
  10626. tb_settings.setValue('toolbar_lock', lock_state)
  10627. # This will write the setting to the platform specific storage.
  10628. del tb_settings
  10629. # if quit:
  10630. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  10631. # t.start()
  10632. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  10633. def start_delayed_quit(self, delay, filename, should_quit=None):
  10634. """
  10635. :param delay: period of checking if project file size is more than zero; in seconds
  10636. :param filename: the name of the project file to be checked periodically for size more than zero
  10637. :param should_quit: if the task finished will be followed by an app quit; boolean
  10638. :return:
  10639. """
  10640. to_quit = should_quit
  10641. self.save_timer = QtCore.QTimer()
  10642. self.save_timer.setInterval(delay)
  10643. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  10644. self.save_timer.start()
  10645. def check_project_file_size(self, filename, should_quit=None):
  10646. """
  10647. :param filename: the name of the project file to be checked periodically for size more than zero
  10648. :param should_quit: will quit the app if True; boolean
  10649. :return:
  10650. """
  10651. try:
  10652. if os.stat(filename).st_size > 0:
  10653. self.save_in_progress = False
  10654. self.save_timer.stop()
  10655. if should_quit:
  10656. self.app_quit.emit()
  10657. except Exception:
  10658. traceback.print_exc()
  10659. def save_project_auto(self):
  10660. """
  10661. Called periodically to save the project.
  10662. It will save if there is no block on the save, if the project was saved at least once and if there is no save in
  10663. # progress.
  10664. :return:
  10665. """
  10666. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  10667. self.on_file_saveproject()
  10668. def save_project_auto_update(self):
  10669. """
  10670. Update the auto save time interval value.
  10671. :return:
  10672. """
  10673. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  10674. try:
  10675. if self.autosave_timer.isActive():
  10676. self.autosave_timer.stop()
  10677. except Exception:
  10678. pass
  10679. if self.defaults['global_autosave'] is True:
  10680. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  10681. self.autosave_timer.start()
  10682. def on_plotarea_tab_closed(self, tab_idx):
  10683. """
  10684. :param tab_idx: Index of the Tab from the plotarea that was closed
  10685. :return:
  10686. """
  10687. widget = self.ui.plot_tab_area.widget(tab_idx)
  10688. if widget is not None:
  10689. widget.deleteLater()
  10690. self.ui.plot_tab_area.removeTab(tab_idx)
  10691. def on_options_app2project(self):
  10692. """
  10693. Callback for Options->Transfer Options->App=>Project. Copies options
  10694. from application defaults to project defaults.
  10695. :return: None
  10696. """
  10697. self.report_usage("on_options_app2project")
  10698. self.defaults_read_form()
  10699. self.options.update(self.defaults)
  10700. # self.options_write_form()
  10701. def toggle_shell(self):
  10702. """
  10703. Toggle shell: if is visible close it, if it is closed then open it
  10704. :return: None
  10705. """
  10706. self.report_usage("toggle_shell()")
  10707. if self.ui.shell_dock.isVisible():
  10708. self.ui.shell_dock.hide()
  10709. self.plotcanvas.native.setFocus()
  10710. else:
  10711. self.ui.shell_dock.show()
  10712. # I want to take the focus and give it to the Tcl Shell when the Tcl Shell is run
  10713. # self.shell._edit.setFocus()
  10714. QtCore.QTimer.singleShot(0, lambda: self.ui.shell_dock.widget()._edit.setFocus())
  10715. # HACK - simulate a mouse click - alternative
  10716. # no_km = QtCore.Qt.KeyboardModifier(QtCore.Qt.NoModifier) # no KB modifier
  10717. # pos = QtCore.QPoint((self.shell._edit.width() - 40), (self.shell._edit.height() - 2))
  10718. # e = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonPress, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  10719. # no_km)
  10720. # QtWidgets.qApp.sendEvent(self.shell._edit, e)
  10721. # f = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  10722. # no_km)
  10723. # QtWidgets.qApp.sendEvent(self.shell._edit, f)
  10724. def on_toggle_shell_from_settings(self, state):
  10725. """
  10726. Toggle shell: if is visible close it, if it is closed then open it
  10727. :return: None
  10728. """
  10729. self.report_usage("on_toggle_shell_from_settings()")
  10730. if state is True:
  10731. if not self.ui.shell_dock.isVisible():
  10732. self.ui.shell_dock.show()
  10733. else:
  10734. if self.ui.shell_dock.isVisible():
  10735. self.ui.shell_dock.hide()
  10736. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  10737. """
  10738. Shows a message on the FlatCAM Shell
  10739. :param msg: Message to display.
  10740. :param show: Opens the shell.
  10741. :param error: Shows the message as an error.
  10742. :param warning: Shows the message as an warning.
  10743. :param success: Shows the message as an success.
  10744. :param selected: Indicate that something was selected on canvas
  10745. :return: None
  10746. """
  10747. if show:
  10748. self.ui.shell_dock.show()
  10749. try:
  10750. if error:
  10751. self.shell.append_error(msg + "\n")
  10752. elif warning:
  10753. self.shell.append_warning(msg + "\n")
  10754. elif success:
  10755. self.shell.append_success(msg + "\n")
  10756. elif selected:
  10757. self.shell.append_selected(msg + "\n")
  10758. else:
  10759. self.shell.append_output(msg + "\n")
  10760. except AttributeError:
  10761. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  10762. class ArgsThread(QtCore.QObject):
  10763. open_signal = pyqtSignal(list)
  10764. start = pyqtSignal()
  10765. if sys.platform == 'win32':
  10766. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  10767. else:
  10768. address = ('/tmp/testipc', 'AF_UNIX')
  10769. def __init__(self):
  10770. super(ArgsThread, self).__init__()
  10771. self.listener = None
  10772. self.start.connect(self.run)
  10773. def my_loop(self, address):
  10774. try:
  10775. self.listener = Listener(*address)
  10776. while True:
  10777. conn = self.listener.accept()
  10778. self.serve(conn)
  10779. except socket.error:
  10780. conn = Client(*address)
  10781. conn.send(sys.argv)
  10782. conn.send('close')
  10783. # close the current instance only if there are args
  10784. if len(sys.argv) > 1:
  10785. try:
  10786. self.listener.close()
  10787. except Exception:
  10788. pass
  10789. sys.exit()
  10790. def serve(self, conn):
  10791. while True:
  10792. msg = conn.recv()
  10793. if msg == 'close':
  10794. break
  10795. self.open_signal.emit(msg)
  10796. conn.close()
  10797. # the decorator is a must; without it this technique will not work unless the start signal is connected
  10798. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  10799. @pyqtSlot()
  10800. def run(self):
  10801. self.my_loop(self.address)
  10802. # end of file