FlatCAMApp.py 523 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ###########################################################
  8. import urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import threading
  16. import shutil
  17. from stat import S_IREAD, S_IRGRP, S_IROTH
  18. import subprocess
  19. import ctypes
  20. import tkinter as tk
  21. from PyQt5 import QtPrintSupport
  22. from contextlib import contextmanager
  23. import gc
  24. from xml.dom.minidom import parseString as parse_xml_string
  25. from multiprocessing.connection import Listener, Client
  26. from multiprocessing import Pool
  27. import socket
  28. from array import array
  29. # #######################################
  30. # # Imports part of FlatCAM ##
  31. # #######################################
  32. from ObjectCollection import *
  33. from FlatCAMObj import *
  34. from flatcamGUI.PlotCanvas import *
  35. from flatcamGUI.PlotCanvasLegacy import *
  36. from flatcamGUI.FlatCAMGUI import *
  37. from FlatCAMCommon import LoudDict
  38. from FlatCAMPostProc import load_postprocessors
  39. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  40. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  41. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  42. from FlatCAMProcess import *
  43. from FlatCAMWorkerStack import WorkerStack
  44. from flatcamGUI.VisPyVisuals import Color
  45. from vispy.gloo.util import _screenshot
  46. from vispy.io import write_png
  47. from flatcamTools import *
  48. import tclCommands
  49. import gettext
  50. import FlatCAMTranslation as fcTranslate
  51. import builtins
  52. if sys.platform == 'win32':
  53. import winreg
  54. fcTranslate.apply_language('strings')
  55. if '_' not in builtins.__dict__:
  56. _ = gettext.gettext
  57. # ########################################
  58. # # App ###
  59. # ########################################
  60. class App(QtCore.QObject):
  61. """
  62. The main application class. The constructor starts the GUI.
  63. """
  64. # Get Cmd Line Options
  65. cmd_line_shellfile = ''
  66. cmd_line_shellvar = ''
  67. cmd_line_headless = None
  68. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  69. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  70. "FlatCam.py --headless=1"
  71. try:
  72. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  73. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  74. "shellvar=",
  75. "headless=",
  76. "multiprocessing-fork="])
  77. except getopt.GetoptError:
  78. print(cmd_line_help)
  79. sys.exit(2)
  80. for opt, arg in cmd_line_options:
  81. if opt == '-h':
  82. print(cmd_line_help)
  83. sys.exit()
  84. elif opt == '--shellfile':
  85. cmd_line_shellfile = arg
  86. elif opt == '--shellvar':
  87. cmd_line_shellvar = arg
  88. elif opt == '--headless':
  89. try:
  90. cmd_line_headless = eval(arg)
  91. except NameError:
  92. pass
  93. # ## Logging ###
  94. log = logging.getLogger('base')
  95. log.setLevel(logging.DEBUG)
  96. # log.setLevel(logging.WARNING)
  97. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  98. handler = logging.StreamHandler()
  99. handler.setFormatter(formatter)
  100. log.addHandler(handler)
  101. # ##########################################################################
  102. # ################## Version and VERSION DATE ##############################
  103. # ##########################################################################
  104. version = 8.97
  105. version_date = "2019/09/27"
  106. beta = True
  107. engine = '3D'
  108. # current date now
  109. date = str(datetime.today()).rpartition('.')[0]
  110. date = ''.join(c for c in date if c not in ':-')
  111. date = date.replace(' ', '_')
  112. # URL for update checks and statistics
  113. version_url = "http://flatcam.org/version"
  114. # App URL
  115. app_url = "http://flatcam.org"
  116. # Manual URL
  117. manual_url = "http://flatcam.org/manual/index.html"
  118. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  119. gerber_spec_url ="https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  120. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  121. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  122. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  123. # this variable will hold the project status
  124. # if True it will mean that the project was modified and not saved
  125. should_we_save = False
  126. # flag is True if saving action has been triggered
  127. save_in_progress = False
  128. # ###########################################################################
  129. # ############################# Signals ################################
  130. # ###########################################################################
  131. # Inform the user
  132. # Handled by:
  133. # * App.info() --> Print on the status bar
  134. inform = QtCore.pyqtSignal(str)
  135. app_quit = QtCore.pyqtSignal()
  136. # General purpose background task
  137. worker_task = QtCore.pyqtSignal(dict)
  138. # File opened
  139. # Handled by:
  140. # * register_folder()
  141. # * register_recent()
  142. # Note: Setting the parameters to unicode does not seem
  143. # to have an effect. Then are received as Qstring
  144. # anyway.
  145. # File type and filename
  146. file_opened = QtCore.pyqtSignal(str, str)
  147. # File type and filename
  148. file_saved = QtCore.pyqtSignal(str, str)
  149. # Percentage of progress
  150. progress = QtCore.pyqtSignal(int)
  151. plots_updated = QtCore.pyqtSignal()
  152. # Emitted by new_object() and passes the new object as argument, plot flag.
  153. # on_object_created() adds the object to the collection, plots on appropriate flag
  154. # and emits new_object_available.
  155. object_created = QtCore.pyqtSignal(object, bool, bool)
  156. # Emitted when a object has been changed (like scaled, mirrored)
  157. object_changed = QtCore.pyqtSignal(object)
  158. # Emitted after object has been plotted.
  159. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  160. object_plotted = QtCore.pyqtSignal(object)
  161. # Emitted when a new object has been added or deleted from/to the collection
  162. object_status_changed = QtCore.pyqtSignal(object, str)
  163. message = QtCore.pyqtSignal(str, str, str)
  164. # Emmited when shell command is finished(one command only)
  165. shell_command_finished = QtCore.pyqtSignal(object)
  166. # Emitted when multiprocess pool has been recreated
  167. pool_recreated = QtCore.pyqtSignal(object)
  168. # Emitted when an unhandled exception happens
  169. # in the worker task.
  170. thread_exception = QtCore.pyqtSignal(object)
  171. # used to signal that there are arguments for the app
  172. args_at_startup = QtCore.pyqtSignal(list)
  173. # a reusable signal to replot a list of objects
  174. # should be disconnected after use so it can be reused
  175. replot_signal = pyqtSignal(list)
  176. def __init__(self, user_defaults=True, post_gui=None):
  177. """
  178. Starts the application.
  179. :return: app
  180. :rtype: App
  181. """
  182. App.log.info("FlatCAM Starting...")
  183. self.main_thread = QtWidgets.QApplication.instance().thread()
  184. # ############################################################################
  185. # # ################# OS-specific ############################################
  186. # ############################################################################
  187. portable = False
  188. # Folder for user settings.
  189. if sys.platform == 'win32':
  190. # #########################################################################
  191. # Setup the listening thread for another instance launching with args #####
  192. # #########################################################################
  193. # make sure the thread is stored by using a self. otherwise it's garbage collected
  194. self.th = QtCore.QThread()
  195. self.th.start(priority=QtCore.QThread.LowestPriority)
  196. self.new_launch = ArgsThread()
  197. self.new_launch.open_signal[list].connect(self.on_startup_args)
  198. self.new_launch.moveToThread(self.th)
  199. self.new_launch.start.emit()
  200. from win32com.shell import shell, shellcon
  201. if platform.architecture()[0] == '32bit':
  202. App.log.debug("Win32!")
  203. else:
  204. App.log.debug("Win64!")
  205. # #########################################################################
  206. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  207. # #########################################################################
  208. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  209. try:
  210. with open(config_file, 'r'):
  211. pass
  212. except FileNotFoundError:
  213. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  214. try:
  215. with open(config_file, 'r') as f:
  216. try:
  217. for line in f:
  218. param = str(line).replace('\n', '').rpartition('=')
  219. if param[0] == 'portable':
  220. try:
  221. portable = eval(param[2])
  222. except NameError:
  223. portable = False
  224. if param[0] == 'headless':
  225. if param[2].lower() == 'true':
  226. self.cmd_line_headless = 1
  227. else:
  228. self.cmd_line_headless = None
  229. except Exception as e:
  230. log.debug('App.__init__() -->%s' % str(e))
  231. return
  232. except FileNotFoundError as e:
  233. log.debug(str(e))
  234. pass
  235. if portable is False:
  236. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  237. else:
  238. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  239. self.os = 'windows'
  240. else: # Linux/Unix/MacOS
  241. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  242. self.os = 'unix'
  243. # ##########################################################################
  244. # ################## Setup folders and files ###############################
  245. # ##########################################################################
  246. if not os.path.exists(self.data_path):
  247. os.makedirs(self.data_path)
  248. App.log.debug('Created data folder: ' + self.data_path)
  249. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  250. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  251. self.postprocessorpaths = os.path.join(self.data_path, 'postprocessors')
  252. if not os.path.exists(self.postprocessorpaths):
  253. os.makedirs(self.postprocessorpaths)
  254. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  255. # create current_defaults.FlatConfig file if there is none
  256. try:
  257. f = open(self.data_path + '/current_defaults.FlatConfig')
  258. f.close()
  259. except IOError:
  260. App.log.debug('Creating empty current_defaults.FlatConfig')
  261. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  262. json.dump({}, f)
  263. f.close()
  264. # create factory_defaults.FlatConfig file if there is none
  265. try:
  266. f = open(self.data_path + '/factory_defaults.FlatConfig')
  267. f.close()
  268. except IOError:
  269. App.log.debug('Creating empty factory_defaults.FlatConfig')
  270. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  271. json.dump({}, f)
  272. f.close()
  273. # create a recent files json file if there is none
  274. try:
  275. f = open(self.data_path + '/recent.json')
  276. f.close()
  277. except IOError:
  278. App.log.debug('Creating empty recent.json')
  279. f = open(self.data_path + '/recent.json', 'w')
  280. json.dump([], f)
  281. f.close()
  282. # create a recent projects json file if there is none
  283. try:
  284. fp = open(self.data_path + '/recent_projects.json')
  285. fp.close()
  286. except IOError:
  287. App.log.debug('Creating empty recent_projects.json')
  288. fp = open(self.data_path + '/recent_projects.json', 'w')
  289. json.dump([], fp)
  290. fp.close()
  291. # Application directory. CHDIR to it. Otherwise, trying to load
  292. # GUI icons will fail as their path is relative.
  293. # This will fail under cx_freeze ...
  294. self.app_home = os.path.dirname(os.path.realpath(__file__))
  295. App.log.debug("Application path is " + self.app_home)
  296. App.log.debug("Started in " + os.getcwd())
  297. # cx_freeze workaround
  298. if os.path.isfile(self.app_home):
  299. self.app_home = os.path.dirname(self.app_home)
  300. os.chdir(self.app_home)
  301. # #############################################################################
  302. # ##################### CREATE MULTIPROCESSING POOL ###########################
  303. # #############################################################################
  304. self.pool = Pool()
  305. # ##########################################################################
  306. # ################## Setting the Splash Screen #############################
  307. # ##########################################################################
  308. settings = QSettings("Open Source", "FlatCAM")
  309. if settings.contains("splash_screen"):
  310. show_splash = settings.value("splash_screen")
  311. else:
  312. settings.setValue('splash_screen', 1)
  313. # This will write the setting to the platform specific storage.
  314. del settings
  315. show_splash = 1
  316. if show_splash and self.cmd_line_headless != 1:
  317. splash_pix = QtGui.QPixmap('share/splash.png')
  318. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  319. # self.splash.setMask(splash_pix.mask())
  320. # move splashscreen to the current monitor
  321. desktop = QtWidgets.QApplication.desktop()
  322. screen = desktop.screenNumber(QtGui.QCursor.pos())
  323. current_screen_center = desktop.availableGeometry(screen).center()
  324. self.splash.move(current_screen_center - self.splash.rect().center())
  325. self.splash.show()
  326. self.splash.showMessage(_("FlatCAM is initializing ..."),
  327. alignment=Qt.AlignBottom | Qt.AlignLeft,
  328. color=QtGui.QColor("gray"))
  329. else:
  330. show_splash = 0
  331. # #############################################################################
  332. # ##################### Initialize GUI ########################################
  333. # #############################################################################
  334. # FlatCAM colors used in plotting
  335. self.FC_light_green = '#BBF268BF'
  336. self.FC_dark_green = '#006E20BF'
  337. self.FC_light_blue = '#a5a5ffbf'
  338. self.FC_dark_blue = '#0000ffbf'
  339. QtCore.QObject.__init__(self)
  340. self.ui = FlatCAMGUI(self.version, self.beta, self)
  341. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  342. self.ui.final_save.connect(self.final_save)
  343. # #############################################################################
  344. # ############################## Data #########################################
  345. # #############################################################################
  346. self.recent = []
  347. self.recent_projects = []
  348. self.clipboard = QtWidgets.QApplication.clipboard()
  349. self.project_filename = None
  350. self.toggle_units_ignore = False
  351. # self.defaults_form = PreferencesUI()
  352. # when adding entries here read the comments in the method found bellow named:
  353. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  354. self.defaults_form_fields = {
  355. # General App
  356. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  357. "global_graphic_engine": self.ui.general_defaults_form.general_app_group.ge_radio,
  358. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  359. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  360. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  361. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  362. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  363. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  364. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  365. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  366. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  367. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  368. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  369. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  370. # General GUI Preferences
  371. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  372. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  373. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  374. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  375. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  376. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  377. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  378. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  379. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  380. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  381. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  382. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  383. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  384. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  385. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  386. "global_activity_icon": self.ui.general_defaults_form.general_gui_group.activity_combo,
  387. # General GUI Settings
  388. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  389. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  390. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  391. "global_systray_icon": self.ui.general_defaults_form.general_gui_set_group.systray_cb,
  392. "global_shell_at_startup": self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb,
  393. "global_project_at_startup": self.ui.general_defaults_form.general_gui_set_group.project_startup_cb,
  394. "global_project_autohide": self.ui.general_defaults_form.general_gui_set_group.project_autohide_cb,
  395. "global_toggle_tooltips": self.ui.general_defaults_form.general_gui_set_group.toggle_tooltips_cb,
  396. "global_delete_confirmation": self.ui.general_defaults_form.general_gui_set_group.delete_conf_cb,
  397. # Gerber General
  398. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  399. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  400. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  401. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  402. # Gerber Options
  403. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  404. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  405. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  406. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  407. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  408. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  409. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  410. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  411. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  412. # Gerber Advanced Options
  413. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  414. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  415. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  416. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  417. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  418. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  419. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  420. # Gerber Export
  421. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  422. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  423. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  424. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  425. # Gerber Editor
  426. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  427. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  428. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  429. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  430. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  431. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  432. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  433. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  434. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  435. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  436. "gerber_editor_circ_angle":
  437. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  438. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  439. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  440. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  441. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  442. # Excellon General
  443. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  444. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  445. "excellon_format_upper_in":
  446. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  447. "excellon_format_lower_in":
  448. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  449. "excellon_format_upper_mm":
  450. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  451. "excellon_format_lower_mm":
  452. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  453. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  454. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  455. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  456. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  457. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  458. # Excellon Options
  459. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  460. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  461. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.eendz_entry,
  462. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  463. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  464. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  465. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  466. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  467. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  468. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  469. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  470. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  471. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  472. # Excellon Advanced Options
  473. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  474. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  475. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  476. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  477. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  478. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  479. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  480. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  481. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  482. # Excellon Export
  483. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  484. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  485. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  486. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  487. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  488. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  489. # Excellon Editor
  490. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  491. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  492. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  493. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  494. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  495. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  496. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  497. "excellon_editor_circ_angle":
  498. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  499. # Excellon Slots
  500. "excellon_editor_slot_direction":
  501. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  502. "excellon_editor_slot_angle":
  503. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  504. "excellon_editor_slot_length":
  505. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  506. # Excellon Slots
  507. "excellon_editor_slot_array_size":
  508. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  509. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  510. "excellon_editor_slot_lin_pitch":
  511. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  512. "excellon_editor_slot_lin_angle":
  513. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  514. "excellon_editor_slot_circ_dir":
  515. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  516. "excellon_editor_slot_circ_angle":
  517. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  518. # Geometry General
  519. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  520. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  521. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  522. # Geometry Options
  523. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  524. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  525. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  526. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  527. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  528. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  529. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  530. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  531. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  532. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  533. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.gendz_entry,
  534. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  535. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  536. # Geometry Advanced Options
  537. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  538. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  539. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  540. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  541. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  542. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  543. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  544. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  545. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  546. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  547. # Geometry Editor
  548. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  549. "geometry_editor_milling_type": self.ui.geometry_defaults_form.geometry_editor_group.milling_type_radio,
  550. # CNCJob General
  551. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  552. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  553. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  554. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  555. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  556. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  557. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  558. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  559. # CNC Job Options
  560. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  561. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  562. # CNC Job Advanced Options
  563. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  564. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  565. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  566. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  567. # NCC Tool
  568. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  569. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  570. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  571. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  572. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  573. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  574. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  575. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  576. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  577. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  578. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  579. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  580. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  581. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  582. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  583. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  584. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  585. # CutOut Tool
  586. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  587. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  588. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  589. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  590. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  591. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  592. # Paint Area Tool
  593. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  594. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  595. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  596. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  597. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  598. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  599. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  600. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  601. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  602. # 2-sided Tool
  603. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  604. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  605. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  606. # Film Tool
  607. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  608. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  609. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  610. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  611. # Panelize Tool
  612. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  613. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  614. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  615. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  616. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  617. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  618. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  619. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  620. # Calculators Tool
  621. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  622. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  623. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  624. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  625. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  626. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  627. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  628. # Transformations Tool
  629. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  630. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  631. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  632. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  633. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  634. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  635. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  636. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  637. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  638. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  639. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  640. # SolderPaste Dispensing Tool
  641. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  642. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  643. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  644. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  645. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  646. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  647. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  648. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  649. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  650. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  651. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  652. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  653. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  654. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  655. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  656. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  657. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  658. # Utilities
  659. # File associations
  660. "fa_excellon": self.ui.util_defaults_form.fa_excellon_group.exc_list_text,
  661. "fa_gcode": self.ui.util_defaults_form.fa_gcode_group.gco_list_text,
  662. # "fa_geometry": self.ui.util_defaults_form.fa_geometry_group.close_paths_cb,
  663. "fa_gerber": self.ui.util_defaults_form.fa_gerber_group.grb_list_text,
  664. "util_autocomplete_keywords": self.ui.util_defaults_form.kw_group.kw_list_text,
  665. }
  666. # ############################
  667. # ### LOAD POSTPROCESSORS ####
  668. # ############################
  669. self.postprocessors = load_postprocessors(self)
  670. for name in list(self.postprocessors.keys()):
  671. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  672. if name.partition('_')[0] == 'Paste':
  673. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  674. continue
  675. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  676. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  677. if name == 'hpgl':
  678. continue
  679. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  680. # ############################
  681. # ### LOAD LANGUAGES ####
  682. # ############################
  683. self.languages = fcTranslate.load_languages()
  684. for name in sorted(self.languages.values()):
  685. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  686. # #################################################################################
  687. # #################### DEFAULTS - PREFERENCES STORAGE #############################
  688. # #################################################################################
  689. self.defaults = LoudDict()
  690. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  691. self.defaults.update({
  692. # Global APP Preferences
  693. "first_run": True,
  694. "units": "IN",
  695. "global_serial": 0,
  696. "global_stats": {},
  697. "global_tabs_detachable": True,
  698. "global_graphic_engine": '3D',
  699. "global_app_level": 'b',
  700. "global_portable": False,
  701. "global_language": 'English',
  702. "global_version_check": True,
  703. "global_send_stats": True,
  704. "global_pan_button": '2',
  705. "global_mselect_key": 'Control',
  706. "global_project_at_startup": False,
  707. "global_systray_icon": True,
  708. "global_project_autohide": True,
  709. "global_toggle_tooltips": True,
  710. "global_worker_number": 2,
  711. "global_tolerance": 0.005,
  712. "global_open_style": True,
  713. "global_delete_confirmation": True,
  714. "global_compression_level": 3,
  715. "global_save_compressed": True,
  716. # Global GUI Preferences
  717. "global_gridx": 0.0393701,
  718. "global_gridy": 0.0393701,
  719. "global_snap_max": 0.001968504,
  720. "global_workspace": False,
  721. "global_workspaceT": "A4P",
  722. "global_grid_context_menu": {
  723. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  724. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  725. },
  726. "global_plot_fill": '#BBF268BF',
  727. "global_plot_line": '#006E20BF',
  728. "global_sel_fill": '#a5a5ffbf',
  729. "global_sel_line": '#0000ffbf',
  730. "global_alt_sel_fill": '#BBF268BF',
  731. "global_alt_sel_line": '#006E20BF',
  732. "global_draw_color": '#FF0000',
  733. "global_sel_draw_color": '#0000FF',
  734. "global_proj_item_color": '#000000',
  735. "global_proj_item_dis_color": '#b7b7cb',
  736. "global_activity_icon": 'Ball green',
  737. "global_toolbar_view": 511,
  738. "global_background_timeout": 300000, # Default value is 5 minutes
  739. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  740. # (python trace only for unknown errors),
  741. # 1 = show trace(show trace always),
  742. # 2 = (For the future).
  743. # Persistence
  744. "global_last_folder": None,
  745. "global_last_save_folder": None,
  746. # Default window geometry
  747. "global_def_win_x": 100,
  748. "global_def_win_y": 100,
  749. "global_def_win_w": 1024,
  750. "global_def_win_h": 650,
  751. "global_def_notebook_width": 1,
  752. # Constants...
  753. "global_defaults_save_period_ms": 20000, # Time between default saves.
  754. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  755. "global_shell_at_startup": False, # Show the shell at startup.
  756. "global_recent_limit": 10, # Max. items in recent list.
  757. "fit_key": 'V',
  758. "zoom_out_key": '-',
  759. "zoom_in_key": '=',
  760. "grid_toggle_key": 'G',
  761. "global_zoom_ratio": 1.5,
  762. "global_point_clipboard_format": "(%.4f, %.4f)",
  763. "global_zdownrate": None,
  764. # General GUI Settings
  765. "global_hover": False,
  766. "global_selection_shape": True,
  767. "global_layout": "compact",
  768. # Gerber General
  769. "gerber_plot": True,
  770. "gerber_solid": True,
  771. "gerber_multicolored": False,
  772. "gerber_circle_steps": 128,
  773. "gerber_use_buffer_for_union": True,
  774. # Gerber Options
  775. "gerber_isotooldia": 0.00787402,
  776. "gerber_isopasses": 1,
  777. "gerber_isooverlap": 0.00393701,
  778. "gerber_milling_type": "cl",
  779. "gerber_combine_passes": False,
  780. "gerber_noncoppermargin": 0.00393701,
  781. "gerber_noncopperrounded": False,
  782. "gerber_bboxmargin": 0.00393701,
  783. "gerber_bboxrounded": False,
  784. # Gerber Advanced Options
  785. "gerber_aperture_display": False,
  786. "gerber_aperture_scale_factor": 1.0,
  787. "gerber_aperture_buffer_factor": 0.0,
  788. "gerber_follow": False,
  789. "gerber_buffering": "full",
  790. "gerber_simplification": False,
  791. "gerber_simp_tolerance": 0.0005,
  792. # Gerber Export
  793. "gerber_exp_units": 'IN',
  794. "gerber_exp_integer": 2,
  795. "gerber_exp_decimals": 4,
  796. "gerber_exp_zeros": 'L',
  797. # Gerber Editor
  798. "gerber_editor_sel_limit": 30,
  799. "gerber_editor_newcode": 10,
  800. "gerber_editor_newsize": 0.8,
  801. "gerber_editor_newtype": 'C',
  802. "gerber_editor_newdim": "0.5, 0.5",
  803. "gerber_editor_array_size": 5,
  804. "gerber_editor_lin_axis": 'X',
  805. "gerber_editor_lin_pitch": 1,
  806. "gerber_editor_lin_angle": 0.0,
  807. "gerber_editor_circ_dir": 'CW',
  808. "gerber_editor_circ_angle": 0.0,
  809. "gerber_editor_scale_f": 1.0,
  810. "gerber_editor_buff_f": 0.1,
  811. "gerber_editor_ma_low": 0.0,
  812. "gerber_editor_ma_high": 1.0,
  813. # Excellon General
  814. "excellon_plot": True,
  815. "excellon_solid": True,
  816. "excellon_format_upper_in": 2,
  817. "excellon_format_lower_in": 4,
  818. "excellon_format_upper_mm": 3,
  819. "excellon_format_lower_mm": 3,
  820. "excellon_zeros": "L",
  821. "excellon_units": "INCH",
  822. "excellon_update": True,
  823. "excellon_optimization_type": 'B',
  824. "excellon_search_time": 3,
  825. # Excellon Options
  826. "excellon_drillz": -0.0590551,
  827. "excellon_travelz": 0.0787402,
  828. "excellon_endz": 0.5,
  829. "excellon_feedrate": 3.14961,
  830. "excellon_spindlespeed": None,
  831. "excellon_dwell": False,
  832. "excellon_dwelltime": 1,
  833. "excellon_toolchange": False,
  834. "excellon_toolchangez": 0.5,
  835. "excellon_ppname_e": 'default',
  836. "excellon_tooldia": 0.0314961,
  837. "excellon_slot_tooldia": 0.0708661,
  838. "excellon_gcode_type": "drills",
  839. # Excellon Advanced Options
  840. "excellon_offset": 0.0,
  841. "excellon_toolchangexy": "0.0, 0.0",
  842. "excellon_startz": None,
  843. "excellon_feedrate_rapid": 31.4961,
  844. "excellon_z_pdepth": -0.02,
  845. "excellon_feedrate_probe": 3.14961,
  846. "excellon_spindledir": 'CW',
  847. "excellon_f_plunge": False,
  848. "excellon_f_retract": False,
  849. # Excellon Export
  850. "excellon_exp_units": 'INCH',
  851. "excellon_exp_format": 'ndec',
  852. "excellon_exp_integer": 2,
  853. "excellon_exp_decimals": 4,
  854. "excellon_exp_zeros": 'LZ',
  855. "excellon_exp_slot_type": 'routing',
  856. # Excellon Editor
  857. "excellon_editor_sel_limit": 30,
  858. "excellon_editor_newdia": 0.039,
  859. "excellon_editor_array_size": 5,
  860. "excellon_editor_lin_dir": 'X',
  861. "excellon_editor_lin_pitch": 0.1,
  862. "excellon_editor_lin_angle": 0.0,
  863. "excellon_editor_circ_dir": 'CW',
  864. "excellon_editor_circ_angle": 12,
  865. # Excellon Slots
  866. "excellon_editor_slot_direction": 'X',
  867. "excellon_editor_slot_angle": 0.0,
  868. "excellon_editor_slot_length": 5.0,
  869. # Excellon Slot Array
  870. "excellon_editor_slot_array_size": 5,
  871. "excellon_editor_slot_lin_dir": 'X',
  872. "excellon_editor_slot_lin_pitch": 0.1,
  873. "excellon_editor_slot_lin_angle": 0.0,
  874. "excellon_editor_slot_circ_dir": 'CW',
  875. "excellon_editor_slot_circ_angle": 0.0,
  876. # Geometry General
  877. "geometry_plot": True,
  878. "geometry_circle_steps": 128,
  879. "geometry_cnctooldia": "0.0944882",
  880. # Geometry Options
  881. "geometry_cutz": -0.0944882,
  882. "geometry_vtipdia": 0.1,
  883. "geometry_vtipangle": 30,
  884. "geometry_multidepth": False,
  885. "geometry_depthperpass": 0.0314961,
  886. "geometry_travelz": 0.0787402,
  887. "geometry_toolchange": False,
  888. "geometry_toolchangez": 0.5,
  889. "geometry_endz": 0.5,
  890. "geometry_feedrate": 3.14961,
  891. "geometry_feedrate_z": 3.14961,
  892. "geometry_spindlespeed": None,
  893. "geometry_dwell": False,
  894. "geometry_dwelltime": 1,
  895. "geometry_ppname_g": 'default',
  896. # Geometry Advanced Options
  897. "geometry_toolchangexy": "0.0, 0.0",
  898. "geometry_startz": None,
  899. "geometry_feedrate_rapid": 3.14961,
  900. "geometry_extracut": False,
  901. "geometry_z_pdepth": -0.02,
  902. "geometry_f_plunge": False,
  903. "geometry_spindledir": 'CW',
  904. "geometry_feedrate_probe": 3.14961,
  905. "geometry_segx": 0.0,
  906. "geometry_segy": 0.0,
  907. # Geometry Editor
  908. "geometry_editor_sel_limit": 30,
  909. "geometry_editor_milling_type": "cl",
  910. # CNC Job General
  911. "cncjob_plot": True,
  912. "cncjob_plot_kind": 'all',
  913. "cncjob_annotation": True,
  914. "cncjob_tooldia": 0.0393701,
  915. "cncjob_coords_type": "G90",
  916. "cncjob_coords_decimals": 4,
  917. "cncjob_fr_decimals": 2,
  918. "cncjob_steps_per_circle": 128,
  919. # CNC Job Options
  920. "cncjob_prepend": "",
  921. "cncjob_append": "",
  922. # CNC Job Advanced Options
  923. "cncjob_toolchange_macro": "",
  924. "cncjob_toolchange_macro_enable": False,
  925. "cncjob_annotation_fontsize": 9,
  926. "cncjob_annotation_fontcolor": '#990000',
  927. # NCC Tool
  928. "tools_ncctools": "0.0393701, 0.019685",
  929. "tools_nccorder": 'rev',
  930. "tools_nccoverlap": 0.015748,
  931. "tools_nccmargin": 0.0393701,
  932. "tools_nccmethod": "seed",
  933. "tools_nccconnect": True,
  934. "tools_ncccontour": True,
  935. "tools_nccrest": False,
  936. "tools_ncc_offset_choice": False,
  937. "tools_ncc_offset_value": 0.0000,
  938. "tools_nccref": 'itself',
  939. "tools_ncc_plotting": 'normal',
  940. "tools_nccmilling_type": 'cl',
  941. "tools_ncctool_type": 'V',
  942. "tools_ncccutz": -0.001968504,
  943. "tools_ncctipdia": 0.00393701,
  944. "tools_ncctipangle": 30,
  945. # Cutout Tool
  946. "tools_cutouttooldia": 0.0944882,
  947. "tools_cutoutkind": "single",
  948. "tools_cutoutmargin": 0.00393701,
  949. "tools_cutoutgapsize": 0.15748,
  950. "tools_gaps_ff": "4",
  951. "tools_cutout_convexshape": False,
  952. # Paint Tool
  953. "tools_painttooldia": 0.023622,
  954. "tools_paintorder": 'rev',
  955. "tools_paintoverlap": 0.015748,
  956. "tools_paintmargin": 0.0,
  957. "tools_paintmethod": "seed",
  958. "tools_selectmethod": "all",
  959. "tools_pathconnect": True,
  960. "tools_paintcontour": True,
  961. "tools_paint_plotting": 'normal',
  962. # 2-Sided Tool
  963. "tools_2sided_mirror_axis": "X",
  964. "tools_2sided_axis_loc": "point",
  965. "tools_2sided_drilldia": 0.11811,
  966. # Film Tool
  967. "tools_film_type": 'neg',
  968. "tools_film_boundary": 0.0393701,
  969. "tools_film_scale": 0,
  970. "tools_film_color": '#000000',
  971. # Panel Tool
  972. "tools_panelize_spacing_columns": 0,
  973. "tools_panelize_spacing_rows": 0,
  974. "tools_panelize_columns": 1,
  975. "tools_panelize_rows": 1,
  976. "tools_panelize_constrain": False,
  977. "tools_panelize_constrainx": 0.0,
  978. "tools_panelize_constrainy": 0.0,
  979. "tools_panelize_panel_type": 'gerber',
  980. # Calculators Tool
  981. "tools_calc_vshape_tip_dia": 0.007874,
  982. "tools_calc_vshape_tip_angle": 30,
  983. "tools_calc_vshape_cut_z": 0.000787,
  984. "tools_calc_electro_length": 10.0,
  985. "tools_calc_electro_width": 10.0,
  986. "tools_calc_electro_cdensity": 13.0,
  987. "tools_calc_electro_growth": 10.0,
  988. # Transform Tool
  989. "tools_transform_rotate": 90,
  990. "tools_transform_skew_x": 0.0,
  991. "tools_transform_skew_y": 0.0,
  992. "tools_transform_scale_x": 1.0,
  993. "tools_transform_scale_y": 1.0,
  994. "tools_transform_scale_link": True,
  995. "tools_transform_scale_reference": True,
  996. "tools_transform_offset_x": 0.0,
  997. "tools_transform_offset_y": 0.0,
  998. "tools_transform_mirror_reference": False,
  999. "tools_transform_mirror_point": (0, 0),
  1000. # SolderPaste Tool
  1001. "tools_solderpaste_tools": "0.0393701, 0.011811",
  1002. "tools_solderpaste_new": 0.011811,
  1003. "tools_solderpaste_z_start": 0.00019685039,
  1004. "tools_solderpaste_z_dispense": 0.00393701,
  1005. "tools_solderpaste_z_stop": 0.00019685039,
  1006. "tools_solderpaste_z_travel": 0.00393701,
  1007. "tools_solderpaste_z_toolchange": 0.0393701,
  1008. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  1009. "tools_solderpaste_frxy": 3.0,
  1010. "tools_solderpaste_frz": 3.0,
  1011. "tools_solderpaste_frz_dispense": 0.0393701,
  1012. "tools_solderpaste_speedfwd": 20,
  1013. "tools_solderpaste_dwellfwd": 1,
  1014. "tools_solderpaste_speedrev": 10,
  1015. "tools_solderpaste_dwellrev": 1,
  1016. "tools_solderpaste_pp": 'Paste_1',
  1017. # Subtract Tool
  1018. "tools_sub_close_paths": True,
  1019. # Utilities
  1020. # file associations
  1021. "fa_excellon": 'drd, drl, exc, ncd, tap, xln',
  1022. "fa_gcode": 'cnc, din, dnc, ecs, eia, fan, fgc, fnc, gc, gcd, gcode, h, hnc, i, min, mpf, mpr, nc, ncc, '
  1023. 'ncg, ncp, out, plt, ply, rol, sbp, tap, xpi',
  1024. "fa_gerber": 'art, bot, bsm, cmp, crc, crs, dim, g4, gb0, gb1, gb2, gb3, gb5, gb6, gb7, gb8, gb9, gbd, '
  1025. 'gbl, gbo, gbp, gbr, gbs, gdo, ger, gko, gm1, gm2, gm3, grb, gtl, gto, gtp, gts, ly15, ly2, '
  1026. 'mil, pho, plc, pls, smb, smt, sol, spb, spt, ssb, sst, stc, sts, top, tsm',
  1027. # Keyword list
  1028. "util_autocomplete_keywords": 'Desktop, Documents, FlatConfig, FlatPrj, Marius, My Documents, Paste_1, '
  1029. 'Repetier, Roland_MDX_20, Toolchange_Custom, Toolchange_Probe_MACH3, '
  1030. 'Toolchange_manual, Users, all, angle_x, angle_y, axis, auto, axisoffset, '
  1031. 'box, center_x, center_y, columns, combine, connect, contour, default, '
  1032. 'depthperpass, dia, diatol, dist, drilled_dias, drillz, dwell, dwelltime, '
  1033. 'feedrate_z, grbl_11, grbl_laser, gridoffsety, gridx, gridy, has_offset, '
  1034. 'holes, hpgl, iso_type, line_xyz, margin, marlin, method, milled_dias, '
  1035. 'minoffset, multidepth, name, offset, opt_type, order, outname, overlap, '
  1036. 'passes, postamble, pp, ppname_e, ppname_g, preamble, radius, ref, rest, '
  1037. 'rows, shellvar_, scale_factor, spacing_columns, spacing_rows, spindlespeed, '
  1038. 'toolchange_xy, use_threads, value, x, x0, x1, y, y0, y1, z_cut, z_move'
  1039. ,
  1040. })
  1041. # ############################################################
  1042. # ############### Load defaults from file ####################
  1043. # ############################################################
  1044. if user_defaults:
  1045. self.load_defaults(filename='current_defaults')
  1046. # #############################################################
  1047. # ############## APPLY APP LANGUAGE ###########################
  1048. # #############################################################
  1049. ret_val = fcTranslate.apply_language('strings')
  1050. if ret_val == "no language":
  1051. self.inform.emit('[ERROR] %s' %
  1052. _("Could not find the Language files. The App strings are missing."))
  1053. log.debug("Could not find the Language files. The App strings are missing.")
  1054. else:
  1055. # make the current language the current selection on the language combobox
  1056. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1057. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1058. # ##############################################################
  1059. # ################# CREATE UNIQUE SERIAL NUMBER ################
  1060. # ##############################################################
  1061. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1062. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1063. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  1064. self.save_defaults(silent=True, first_time=True)
  1065. self.propagate_defaults(silent=True)
  1066. self.restore_main_win_geom()
  1067. # def auto_save_defaults():
  1068. # try:
  1069. # self.save_defaults(silent=True)
  1070. # self.propagate_defaults(silent=True)
  1071. # finally:
  1072. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1073. # the following lines activates automatic defaults save
  1074. # if user_defaults:
  1075. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1076. # self.options_form = PreferencesUI()
  1077. self.options_form_fields = {
  1078. "units": self.ui.general_options_form.general_app_group.units_radio,
  1079. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  1080. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  1081. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  1082. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  1083. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  1084. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  1085. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  1086. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  1087. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  1088. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  1089. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  1090. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  1091. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  1092. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  1093. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  1094. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  1095. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  1096. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  1097. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  1098. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  1099. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  1100. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  1101. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  1102. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  1103. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  1104. "excellon_endz": self.ui.excellon_options_form.excellon_opt_group.eendz_entry,
  1105. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  1106. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  1107. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  1108. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  1109. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  1110. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  1111. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  1112. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  1113. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1114. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  1115. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  1116. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  1117. "excellon_spindledir": self.ui.excellon_options_form.excellon_adv_opt_group.spindledir_radio,
  1118. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  1119. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  1120. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  1121. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  1122. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  1123. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  1124. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  1125. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  1126. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  1127. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  1128. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  1129. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  1130. "geometry_endz": self.ui.geometry_options_form.geometry_opt_group.gendz_entry,
  1131. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  1132. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  1133. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  1134. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  1135. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1136. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  1137. "geometry_spindledir": self.ui.geometry_options_form.geometry_adv_opt_group.spindledir_radio,
  1138. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  1139. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  1140. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  1141. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  1142. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  1143. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  1144. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  1145. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  1146. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  1147. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  1148. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  1149. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  1150. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  1151. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  1152. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  1153. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  1154. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  1155. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  1156. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  1157. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  1158. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  1159. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  1160. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  1161. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  1162. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  1163. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  1164. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  1165. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  1166. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  1167. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  1168. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  1169. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  1170. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  1171. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  1172. }
  1173. for name in list(self.postprocessors.keys()):
  1174. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1175. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1176. self.options = LoudDict()
  1177. self.options.set_change_callback(self.on_options_dict_change)
  1178. self.options.update({
  1179. "units": "IN",
  1180. "global_gridx": 1.0,
  1181. "global_gridy": 1.0,
  1182. "global_snap_max": 0.05,
  1183. "global_background_timeout": 300000, # Default value is 5 minutes
  1184. "global_verbose_error_level": 0, # Shell verbosity:
  1185. # 0 = default(python trace only for unknown errors),
  1186. # 1 = show trace(show trace allways), 2 = (For the future).
  1187. "gerber_plot": True,
  1188. "gerber_solid": True,
  1189. "gerber_multicolored": False,
  1190. "gerber_isotooldia": 0.016,
  1191. "gerber_isopasses": 1,
  1192. "gerber_isooverlap": 0.15,
  1193. "gerber_combine_passes": True,
  1194. "gerber_noncoppermargin": 0.0,
  1195. "gerber_noncopperrounded": False,
  1196. "gerber_bboxmargin": 0.0,
  1197. "gerber_bboxrounded": False,
  1198. "excellon_plot": True,
  1199. "excellon_solid": False,
  1200. "excellon_format_upper_in": 2,
  1201. "excellon_format_lower_in": 4,
  1202. "excellon_format_upper_mm": 3,
  1203. "excellon_format_lower_mm": 3,
  1204. "excellon_units": 'INCH',
  1205. "excellon_optimization_type": 'B',
  1206. "excellon_search_time": 3,
  1207. "excellon_zeros": "L",
  1208. "excellon_drillz": -0.1,
  1209. "excellon_travelz": 0.1,
  1210. "excellon_feedrate": 3.0,
  1211. "excellon_feedrate_rapid": 3.0,
  1212. "excellon_spindlespeed": None,
  1213. "excellon_spindledir": 'CW',
  1214. "excellon_dwell": True,
  1215. "excellon_dwelltime": 1000,
  1216. "excellon_toolchange": False,
  1217. "excellon_toolchangez": 1.0,
  1218. "excellon_toolchangexy": "0.0, 0.0",
  1219. "excellon_tooldia": 0.016,
  1220. "excellon_ppname_e": 'default',
  1221. "excellon_f_plunge": False,
  1222. "excellon_startz": None,
  1223. "excellon_endz": 2.0,
  1224. "geometry_plot": True,
  1225. "geometry_segx": 0.0,
  1226. "geometry_segy": 0.0,
  1227. "geometry_cutz": -0.002,
  1228. "geometry_vtipdia": 0.1,
  1229. "geometry_vtipangle": 30,
  1230. "geometry_travelz": 0.1,
  1231. "geometry_feedrate": 3.0,
  1232. "geometry_feedrate_z": 3.0,
  1233. "geometry_feedrate_rapid": 3.0,
  1234. "geometry_spindlespeed": None,
  1235. "geometry_spindledir": 'CW',
  1236. "geometry_dwell": True,
  1237. "geometry_dwelltime": 1000,
  1238. "geometry_cnctooldia": 0.016,
  1239. "geometry_toolchange": False,
  1240. "geometry_toolchangez": 2.0,
  1241. "geometry_toolchangexy": "0.0, 0.0",
  1242. "geometry_startz": None,
  1243. "geometry_endz": 2.0,
  1244. "geometry_ppname_g": "default",
  1245. "geometry_f_plunge": False,
  1246. "geometry_depthperpass": 0.002,
  1247. "geometry_multidepth": False,
  1248. "geometry_extracut": False,
  1249. "cncjob_plot": True,
  1250. "cncjob_tooldia": 0.016,
  1251. "cncjob_prepend": "",
  1252. "cncjob_append": "",
  1253. "tools_ncctools": "1.0, 0.5",
  1254. "tools_nccoverlap": 0.4,
  1255. "tools_nccmargin": 1,
  1256. "tools_cutouttooldia": 0.07,
  1257. "tools_cutoutmargin": 0.1,
  1258. "tools_cutoutgapsize": 0.15,
  1259. "tools_gaps_ff": "8",
  1260. "tools_painttooldia": 0.07,
  1261. "tools_paintoverlap": 0.15,
  1262. "tools_paintmargin": 0.0,
  1263. "tools_paintmethod": "seed",
  1264. "tools_selectmethod": "single",
  1265. "tools_pathconnect": True,
  1266. "tools_paintcontour": True,
  1267. "tools_2sided_mirror_axis": "X",
  1268. "tools_2sided_axis_loc": 'point',
  1269. "tools_2sided_drilldia": 1,
  1270. "tools_film_type": 'neg',
  1271. "tools_film_boundary": 1,
  1272. "tools_film_scale": 0,
  1273. "tools_panelize_spacing_columns": 0,
  1274. "tools_panelize_spacing_rows": 0,
  1275. "tools_panelize_columns": 1,
  1276. "tools_panelize_rows": 1,
  1277. "tools_panelize_constrain": False,
  1278. "tools_panelize_constrainx": 0.0,
  1279. "tools_panelize_constrainy": 0.0
  1280. })
  1281. self.options.update(self.defaults) # Copy app defaults to project options
  1282. self.gen_form = None
  1283. self.ger_form = None
  1284. self.exc_form = None
  1285. self.geo_form = None
  1286. self.cnc_form = None
  1287. self.tools_form = None
  1288. self.fa_form = None
  1289. self.on_options_combo_change(0) # Will show the initial form
  1290. # ################################
  1291. # ### Initialize the color box's color in Preferences -> Global -> Color
  1292. # Init Plot Colors
  1293. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  1294. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  1295. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  1296. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  1297. int(self.defaults['global_plot_fill'][7:9], 16))
  1298. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  1299. int(self.defaults['global_plot_fill'][7:9], 16))
  1300. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  1301. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  1302. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  1303. # Init Left-Right Selection colors
  1304. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  1305. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  1306. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  1307. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1308. int(self.defaults['global_sel_fill'][7:9], 16))
  1309. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1310. int(self.defaults['global_sel_fill'][7:9], 16))
  1311. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1312. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1313. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  1314. # Init Right-Left Selection colors
  1315. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1316. self.defaults['global_alt_sel_fill'])
  1317. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1318. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  1319. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1320. int(self.defaults['global_sel_fill'][7:9], 16))
  1321. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1322. int(self.defaults['global_sel_fill'][7:9], 16))
  1323. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1324. self.defaults['global_alt_sel_line'])
  1325. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1326. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  1327. # Init Draw color and Selection Draw Color
  1328. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1329. self.defaults['global_draw_color'])
  1330. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1331. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1332. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1333. self.defaults['global_sel_draw_color'])
  1334. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1335. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1336. # Init Project Items color
  1337. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1338. self.defaults['global_proj_item_color'])
  1339. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1340. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1341. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1342. self.defaults['global_proj_item_dis_color'])
  1343. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1344. "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1345. # Init the Annotation CNC Job color
  1346. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  1347. self.defaults['cncjob_annotation_fontcolor'])
  1348. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  1349. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  1350. # Init the Tool Film color
  1351. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  1352. self.defaults['tools_film_color'])
  1353. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  1354. "background-color:%s" % str(self.defaults['tools_film_color'])[:7])
  1355. # ### End of Data ####
  1356. # ##############################################
  1357. # ######### SETUP OBJECT COLLECTION ############
  1358. # ##############################################
  1359. self.collection = ObjectCollection(self)
  1360. self.ui.project_tab_layout.addWidget(self.collection.view)
  1361. # ### Adjust tabs width ## ##
  1362. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1363. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1364. self.collection.view.setMinimumWidth(290)
  1365. self.log.debug("Finished creating Object Collection.")
  1366. # ###############################################
  1367. # ############# SETUP Plot Area #################
  1368. # ###############################################
  1369. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  1370. if self.defaults["global_graphic_engine"] == '3D':
  1371. self.is_legacy = False
  1372. else:
  1373. self.is_legacy = True
  1374. # Matplotlib axis
  1375. self.axes = None
  1376. if show_splash:
  1377. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1378. "Canvas initialization started."),
  1379. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1380. color=QtGui.QColor("gray"))
  1381. start_plot_time = time.time() # debug
  1382. self.plotcanvas = None
  1383. self.app_cursor = None
  1384. self.hover_shapes = None
  1385. self.on_plotcanvas_setup()
  1386. end_plot_time = time.time()
  1387. self.used_time = end_plot_time - start_plot_time
  1388. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1389. if show_splash:
  1390. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1391. "Canvas initialization started.\n"
  1392. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1393. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1394. color=QtGui.QColor("gray"))
  1395. self.ui.splitter.setStretchFactor(1, 2)
  1396. # #################################################################
  1397. # ####################### SYS TRAY ################################
  1398. # #################################################################
  1399. if self.defaults["global_systray_icon"]:
  1400. self.parent_w = QtWidgets.QWidget()
  1401. if self.cmd_line_headless == 1:
  1402. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1403. headless=True,
  1404. parent=self.parent_w)
  1405. else:
  1406. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1407. parent=self.parent_w)
  1408. # ###############################################
  1409. # ############# Worker SETUP ####################
  1410. # ###############################################
  1411. if self.defaults["global_worker_number"]:
  1412. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1413. else:
  1414. self.workers = WorkerStack(workers_number=2)
  1415. self.worker_task.connect(self.workers.add_task)
  1416. self.log.debug("Finished creating Workers crew.")
  1417. # ################################################
  1418. # ############### Activity Monitor ###############
  1419. # ################################################
  1420. if self.defaults["global_activity_icon"] == "Ball green":
  1421. icon = 'share/active_2_static.png'
  1422. movie = "share/active_2.gif"
  1423. elif self.defaults["global_activity_icon"] == "Ball black":
  1424. icon = 'share/active_static.png'
  1425. movie = "share/active.gif"
  1426. elif self.defaults["global_activity_icon"] == "Arrow green":
  1427. icon = 'share/active_3_static.png'
  1428. movie = "share/active_3.gif"
  1429. elif self.defaults["global_activity_icon"] == "Eclipse green":
  1430. icon = 'share/active_4_static.png'
  1431. movie = "share/active_4.gif"
  1432. else:
  1433. icon = 'share/active_static.png'
  1434. movie = "share/active.gif"
  1435. self.activity_view = FlatCAMActivityView(icon=icon, movie=movie)
  1436. self.ui.infobar.addWidget(self.activity_view)
  1437. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  1438. # ################################################
  1439. # ############### Signal handling ################
  1440. # ################################################
  1441. # ############# Custom signals ##################
  1442. # signal for displaying messages in status bar
  1443. self.inform.connect(self.info)
  1444. # signal to be called when the app is quiting
  1445. self.app_quit.connect(self.quit_application)
  1446. self.message.connect(self.message_dialog)
  1447. self.progress.connect(self.set_progress_bar)
  1448. # signals that are emitted when object state changes
  1449. self.object_created.connect(self.on_object_created)
  1450. self.object_changed.connect(self.on_object_changed)
  1451. self.object_plotted.connect(self.on_object_plotted)
  1452. self.plots_updated.connect(self.on_plots_updated)
  1453. # signals emitted when file state change
  1454. self.file_opened.connect(self.register_recent)
  1455. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1456. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1457. # ############# Standard signals ###################
  1458. # ### Menu
  1459. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1460. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1461. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1462. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1463. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1464. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1465. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1466. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1467. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1468. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1469. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1470. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1471. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1472. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1473. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1474. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1475. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1476. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1477. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1478. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1479. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1480. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1481. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1482. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1483. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1484. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1485. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1486. self.ui.menufile_exit.triggered.connect(self.final_save)
  1487. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1488. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1489. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1490. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1491. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1492. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1493. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1494. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1495. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1496. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1497. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1498. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1499. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1500. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1501. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1502. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1503. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1504. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1505. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1506. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1507. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1508. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1509. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1510. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1511. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1512. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1513. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1514. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1515. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1516. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1517. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1518. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1519. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1520. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1521. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1522. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1523. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1524. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1525. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1526. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1527. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1528. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1529. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1530. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1531. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1532. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1533. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1534. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1535. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1536. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1537. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1538. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1539. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1540. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1541. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1542. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1543. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1544. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1545. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1546. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1547. # ToolBar signals
  1548. self.connect_toolbar_signals()
  1549. # Notebook signals
  1550. # make the right click on the notebook tab connect to a function
  1551. self.ui.notebook.setupContextMenu()
  1552. self.ui.notebook.addContextMenu(
  1553. _("Detachable Tabs"), self.on_notebook_tab_rmb_click,
  1554. initial_checked=self.defaults["global_tabs_detachable"])
  1555. # activate initial state
  1556. self.on_notebook_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1557. # Context Menu
  1558. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1559. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1560. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1561. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1562. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1563. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1564. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1565. self.ui.clearplot.triggered.connect(self.clear_plots)
  1566. self.ui.replot.triggered.connect(self.plot_all)
  1567. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1568. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1569. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1570. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1571. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1572. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1573. # Preferences Plot Area TAB
  1574. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1575. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1576. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1577. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1578. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1579. # ##############################
  1580. # ### GUI PREFERENCES SIGNALS ##
  1581. # ##############################
  1582. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(
  1583. lambda: fcTranslate.restart_program(app=self)
  1584. )
  1585. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1586. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1587. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1588. )
  1589. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1590. lambda: self.on_toggle_units(no_pref=False))
  1591. # ###############################################################
  1592. # ################### GUI COLORS SIGNALS ########################
  1593. # ###############################################################
  1594. # Setting plot colors signals
  1595. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1596. self.on_pf_color_entry)
  1597. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1598. self.on_pf_color_button)
  1599. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1600. self.on_pf_color_spinner)
  1601. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1602. self.on_pf_color_slider)
  1603. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1604. self.on_pl_color_entry)
  1605. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1606. self.on_pl_color_button)
  1607. # Setting selection (left - right) colors signals
  1608. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1609. self.on_sf_color_entry)
  1610. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1611. self.on_sf_color_button)
  1612. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1613. self.on_sf_color_spinner)
  1614. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1615. self.on_sf_color_slider)
  1616. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1617. self.on_sl_color_entry)
  1618. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1619. self.on_sl_color_button)
  1620. # Setting selection (right - left) colors signals
  1621. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1622. self.on_alt_sf_color_entry)
  1623. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1624. self.on_alt_sf_color_button)
  1625. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1626. self.on_alt_sf_color_spinner)
  1627. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1628. self.on_alt_sf_color_slider)
  1629. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1630. self.on_alt_sl_color_entry)
  1631. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1632. self.on_alt_sl_color_button)
  1633. # Setting Editor Draw colors signals
  1634. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1635. self.on_draw_color_entry)
  1636. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1637. self.on_draw_color_button)
  1638. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1639. self.on_sel_draw_color_entry)
  1640. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1641. self.on_sel_draw_color_button)
  1642. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1643. self.on_proj_color_entry)
  1644. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1645. self.on_proj_color_button)
  1646. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1647. self.on_proj_color_dis_entry)
  1648. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1649. self.on_proj_color_dis_button)
  1650. # ########## workspace setting signals ###########
  1651. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1652. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1653. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1654. # ########## CNC Job related signals #############
  1655. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1656. self.on_cnc_custom_parameters)
  1657. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.editingFinished.connect(
  1658. self.on_annotation_fontcolor_entry)
  1659. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.clicked.connect(
  1660. self.on_annotation_fontcolor_button)
  1661. # ########## Tools related signals #############
  1662. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1663. self.on_film_color_entry)
  1664. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1665. self.on_film_color_button)
  1666. # ########## Modify G-CODE Plot Area TAB ###########
  1667. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1668. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1669. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1670. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1671. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1672. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1673. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1674. self.ui.button_copy_all.clicked.connect(self.handleCopyAll)
  1675. # portability changed signal
  1676. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1677. # Object list
  1678. self.collection.view.activated.connect(self.on_row_activated)
  1679. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1680. self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1681. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1682. # Export Excellon parameters.
  1683. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1684. self.on_update_exc_export
  1685. )
  1686. # call it once to make sure it is updated at startup
  1687. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1688. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1689. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1690. self.on_excellon_defaults_button)
  1691. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1692. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1693. self.on_excellon_options_button)
  1694. # when there are arguments at application startup this get launched
  1695. self.args_at_startup[list].connect(self.on_startup_args)
  1696. # ##############################################################
  1697. # ############### FILE ASSOCIATIONS SIGNALS ####################
  1698. # ##############################################################
  1699. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1700. lambda: self.restore_extensions(ext_type='excellon'))
  1701. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1702. lambda: self.restore_extensions(ext_type='gcode'))
  1703. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1704. lambda: self.restore_extensions(ext_type='gerber'))
  1705. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1706. lambda: self.delete_all_extensions(ext_type='excellon'))
  1707. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1708. lambda: self.delete_all_extensions(ext_type='gcode'))
  1709. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1710. lambda: self.delete_all_extensions(ext_type='gerber'))
  1711. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1712. lambda: self.add_extension(ext_type='excellon'))
  1713. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1714. lambda: self.add_extension(ext_type='gcode'))
  1715. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1716. lambda: self.add_extension(ext_type='gerber'))
  1717. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1718. lambda: self.del_extension(ext_type='excellon'))
  1719. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1720. lambda: self.del_extension(ext_type='gcode'))
  1721. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1722. lambda: self.del_extension(ext_type='gerber'))
  1723. # connect the 'Apply' buttons from the Preferences/File Associations
  1724. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1725. lambda: self.on_register_files(obj_type='excellon'))
  1726. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1727. lambda: self.on_register_files(obj_type='gcode'))
  1728. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1729. lambda: self.on_register_files(obj_type='gerber'))
  1730. # ##############################################################
  1731. # ###################### KEYWORDS SIGNALS ######################
  1732. # ##############################################################
  1733. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1734. lambda: self.restore_extensions(ext_type='keyword'))
  1735. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1736. lambda: self.delete_all_extensions(ext_type='keyword'))
  1737. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1738. lambda: self.add_extension(ext_type='keyword'))
  1739. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1740. lambda: self.del_extension(ext_type='keyword'))
  1741. # splash screen button signal
  1742. self.ui.general_defaults_form.general_gui_set_group.splash_cb.stateChanged.connect(self.on_splash_changed)
  1743. # connect the abort_all_tasks related slots to the related signals
  1744. self.proc_container.idle_flag.connect(self.app_is_idle)
  1745. # #####################################################################################
  1746. # ########### FINISHED CONNECTING SIGNALS #############################################
  1747. # #####################################################################################
  1748. self.log.debug("Finished connecting Signals.")
  1749. # #####################################################################################
  1750. # ########################## Other setups #############################################
  1751. # #####################################################################################
  1752. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  1753. # depending on from where those tools are called different actions can be done
  1754. self.call_source = 'app'
  1755. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1756. self.tool_tab_locked = False
  1757. # decide if to show or hide the Notebook side of the screen at startup
  1758. if self.defaults["global_project_at_startup"] is True:
  1759. self.ui.splitter.setSizes([1, 1])
  1760. else:
  1761. self.ui.splitter.setSizes([0, 1])
  1762. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1763. self.setup_obj_classes()
  1764. self.setup_recent_items()
  1765. self.setup_component_editor()
  1766. # this does not work in Legacy Mode
  1767. if self.is_legacy is True:
  1768. self.ui.general_defaults_form.general_gui_group.workspace_cb.setDisabled(True)
  1769. self.ui.general_defaults_form.general_gui_group.workspace_type_lbl.setDisabled(True)
  1770. self.ui.general_defaults_form.general_gui_group.wk_cb.setDisabled(True)
  1771. # #####################################################################################
  1772. # ######################### Auto-complete KEYWORDS ####################################
  1773. # #####################################################################################
  1774. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1775. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1776. 'delete', 'drillcncjob', 'export_gcode', 'export_svg', 'ext', 'exteriors', 'follow',
  1777. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1778. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1779. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1780. 'mirror', 'ncc',
  1781. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1782. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'origin',
  1783. 'paint', 'pan', 'panel', 'panelize', 'plot_all', 'plot_objects', 'quit_flatcam',
  1784. 'save', 'save_project',
  1785. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_sys',
  1786. 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1787. 'version', 'write_gcode'
  1788. ]
  1789. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'Marius', 'My Documents', 'Paste_1',
  1790. 'Repetier', 'Roland_MDX_20', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  1791. 'Toolchange_manual', 'Users', 'all', 'angle_x', 'angle_y', 'auto', 'axis', 'axisoffset',
  1792. 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect', 'contour', 'default',
  1793. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dwell',
  1794. 'dwelltime', 'feedrate_z', 'grbl_11', 'grbl_laser', 'gridoffsety', 'gridx', 'gridy',
  1795. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  1796. 'milled_dias', 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order',
  1797. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  1798. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  1799. 'spacing_columns',
  1800. 'spacing_rows', 'spindlespeed', 'toolchange_xy', 'use_threads', 'value', 'x',
  1801. 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1802. ]
  1803. self.tcl_keywords = [
  1804. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1805. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1806. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1807. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1808. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1809. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1810. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1811. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1812. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1813. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1814. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1815. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1816. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1817. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1818. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1819. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1820. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1821. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1822. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1823. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1824. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1825. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1826. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1827. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1828. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1829. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1830. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1831. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1832. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1833. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1834. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1835. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1836. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1837. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1838. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1839. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1840. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1841. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1842. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1843. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1844. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1845. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1846. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1847. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1848. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1849. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1850. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1851. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1852. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1853. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1854. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1855. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1856. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1857. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1858. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1859. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1860. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1861. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1862. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1863. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1864. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1865. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1866. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1867. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1868. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1869. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1870. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1871. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1872. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1873. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1874. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1875. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1876. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1877. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1878. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1879. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1880. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1881. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1882. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1883. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1884. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1885. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1886. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1887. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1888. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1889. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1890. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1891. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1892. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1893. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1894. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1895. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1896. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1897. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1898. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1899. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1900. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1901. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1902. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1903. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1904. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1905. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1906. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1907. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1908. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1909. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1910. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1911. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1912. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1913. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1914. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1915. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1916. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1917. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1918. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1919. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1920. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1921. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1922. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1923. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1924. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1925. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1926. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1927. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1928. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1929. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1930. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1931. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1932. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1933. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1934. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1935. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1936. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1937. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1938. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1939. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1940. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1941. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1942. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1943. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1944. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1945. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1946. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1947. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1948. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1949. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1950. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1951. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1952. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1953. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1954. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1955. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1956. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1957. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1958. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1959. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1960. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1961. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1962. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1963. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1964. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1965. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1966. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1967. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1968. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1969. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1970. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1971. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1972. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1973. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1974. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1975. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1976. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1977. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1978. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1979. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1980. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1981. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1982. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1983. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1984. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1985. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1986. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1987. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1988. ]
  1989. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1990. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1991. # ####################################################################################
  1992. # ####################### Shell SETUP ################################################
  1993. # ####################################################################################
  1994. self.shell = FCShell(self, version=self.version)
  1995. self.shell._edit.set_model_data(self.myKeywords)
  1996. self.ui.code_editor.set_model_data(self.myKeywords)
  1997. self.shell.setWindowIcon(self.ui.app_icon)
  1998. self.shell.setWindowTitle("FlatCAM Shell")
  1999. self.shell.resize(*self.defaults["global_shell_shape"])
  2000. self.shell.append_output("FlatCAM %s - " % self.version)
  2001. self.shell.append_output(_("Open Source Software - Type help to get started\n\n"))
  2002. self.init_tcl()
  2003. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  2004. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  2005. self.ui.shell_dock.setWidget(self.shell)
  2006. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  2007. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  2008. QtWidgets.QDockWidget.DockWidgetFloatable |
  2009. QtWidgets.QDockWidget.DockWidgetClosable)
  2010. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  2011. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  2012. if self.defaults["global_shell_at_startup"]:
  2013. self.ui.shell_dock.show()
  2014. else:
  2015. self.ui.shell_dock.hide()
  2016. # ##################################################################################
  2017. # ###################### Tools and Plugins #########################################
  2018. # ##################################################################################
  2019. self.dblsidedtool = None
  2020. self.measurement_tool = None
  2021. self.panelize_tool = None
  2022. self.film_tool = None
  2023. self.paste_tool = None
  2024. self.calculator_tool = None
  2025. self.sub_tool = None
  2026. self.move_tool = None
  2027. self.cutout_tool = None
  2028. self.ncclear_tool = None
  2029. self.paint_tool = None
  2030. self.transform_tool = None
  2031. self.properties_tool = None
  2032. self.pdf_tool = None
  2033. self.image_tool = None
  2034. self.pcb_wizard_tool = None
  2035. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  2036. self.install_tools()
  2037. # ### System Font Parsing ###
  2038. # self.f_parse = ParseFont(self)
  2039. # self.parse_system_fonts()
  2040. # #####################################################################################
  2041. # ######################## Check for updates ##########################################
  2042. # #####################################################################################
  2043. # Separate thread (Not worker)
  2044. # Check for updates on startup but only if the user consent and the app is not in Beta version
  2045. if (self.beta is False or self.beta is None) and \
  2046. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  2047. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  2048. self.thr2 = QtCore.QThread()
  2049. self.worker_task.emit({'fcn': self.version_check,
  2050. 'params': []})
  2051. self.thr2.start(QtCore.QThread.LowPriority)
  2052. # #####################################################################################
  2053. # ######################### Register files with FlatCAM; #############################
  2054. # ######################### It works only for Windows for now ########################
  2055. # #####################################################################################
  2056. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  2057. self.on_register_files()
  2058. # #####################################################################################
  2059. # ###################### Variables for global usage ###################################
  2060. # #####################################################################################
  2061. # coordinates for relative position display
  2062. self.rel_point1 = (0, 0)
  2063. self.rel_point2 = (0, 0)
  2064. # variable to store coordinates
  2065. self.pos = (0, 0)
  2066. self.pos_jump = (0, 0)
  2067. # variable to store mouse coordinates
  2068. self.mouse = [0, 0]
  2069. # decide if we have a double click or single click
  2070. self.doubleclick = False
  2071. # variable to store if a command is active (then the var is not None) and which one it is
  2072. self.command_active = None
  2073. # variable to store the status of moving selection action
  2074. # None value means that it's not an selection action
  2075. # True value = a selection from left to right
  2076. # False value = a selection from right to left
  2077. self.selection_type = None
  2078. # List to store the objects that are currently loaded in FlatCAM
  2079. # This list is updated on each object creation or object delete
  2080. self.all_objects_list = list()
  2081. # List to store the objects that are selected
  2082. self.sel_objects_list = list()
  2083. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  2084. self.key_modifiers = None
  2085. # Variable to hold the status of the axis
  2086. self.toggle_axis = True
  2087. # Variable to store the status of the fullscreen event
  2088. self.toggle_fscreen = False
  2089. # Variable to store the status of the code editor
  2090. self.toggle_codeeditor = False
  2091. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  2092. self.click_noproject = False
  2093. self.cursor = None
  2094. # Variable to store the GCODE that was edited
  2095. self.gcode_edited = ""
  2096. # reference for the self.ui.code_editor
  2097. self.reference_code_editor = None
  2098. self.script_code = ''
  2099. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  2100. self.preferences_changed_flag = False
  2101. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  2102. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  2103. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'pho',
  2104. 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top', 'tsm']
  2105. self.exc_list = ['drd', 'drl', 'exc', 'ncd', 'tap', 'txt', 'xln']
  2106. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  2107. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ncp', 'out', 'plt', 'ply', 'rol', 'sbp',
  2108. 'tap', 'xpi']
  2109. self.svg_list = ['svg']
  2110. self.dxf_list = ['dxf']
  2111. self.pdf_list = ['pdf']
  2112. self.prj_list = ['flatprj']
  2113. self.conf_list = ['flatconfig']
  2114. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  2115. # flag for polygons not cleared
  2116. self.poly_not_cleared = False
  2117. # VisPy visuals
  2118. self.isHovering = False
  2119. self.notHovering = True
  2120. # Window geometry
  2121. self.x_pos = None
  2122. self.y_pos = None
  2123. self.width = None
  2124. self.height = None
  2125. # Event signals disconnect id holders
  2126. self.mp = None
  2127. self.mm = None
  2128. self.mr = None
  2129. self.mp_zc = None
  2130. # when True, the app has to return from any thread
  2131. self.abort_flag = False
  2132. # set the value used in the Windows Title
  2133. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  2134. # ###############################################################################
  2135. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  2136. # ############# It's done only once after install ###############
  2137. # ###############################################################################
  2138. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  2139. fac_def_from_file = factory_file.read()
  2140. factory_defaults = json.loads(fac_def_from_file)
  2141. # if the file contain an empty dictionary then save the factory defaults into the file
  2142. if not factory_defaults:
  2143. self.save_factory_defaults(silent=False)
  2144. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  2145. initial_lay = 'compact'
  2146. self.on_layout(lay=initial_lay)
  2147. # Set the combobox in Preferences to the current layout
  2148. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  2149. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  2150. factory_file.close()
  2151. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  2152. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  2153. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  2154. # after the first run, this object should be False
  2155. self.defaults["first_run"] = False
  2156. # ###############################################################################
  2157. # ################# ADDING FlatCAM EDITORS section ##############################
  2158. # ###############################################################################
  2159. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2160. # at the first launch of the App , the editors will not be functional.
  2161. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  2162. self.exc_editor = FlatCAMExcEditor(self)
  2163. self.grb_editor = FlatCAMGrbEditor(self)
  2164. self.log.debug("Finished adding FlatCAM Editor's.")
  2165. self.set_ui_title(name=_("New Project - Not saved"))
  2166. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2167. current_platform = platform.architecture()[0]
  2168. if current_platform != '64bit':
  2169. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2170. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2171. # ###############################################################################
  2172. # ####################### Finished the CONSTRUCTOR ##############################
  2173. # ###############################################################################
  2174. App.log.debug("END of constructor. Releasing control.")
  2175. # #####################################################################################
  2176. # ########################## SHOW GUI #################################################
  2177. # #####################################################################################
  2178. # if the app is not started as headless, show it
  2179. if self.cmd_line_headless != 1:
  2180. # finish the splash
  2181. self.splash.finish(self.ui)
  2182. settings = QSettings("Open Source", "FlatCAM")
  2183. if settings.contains("maximized_gui"):
  2184. maximized_ui = settings.value('maximized_gui', type=bool)
  2185. if maximized_ui is True:
  2186. self.ui.showMaximized()
  2187. else:
  2188. self.ui.show()
  2189. else:
  2190. self.ui.show()
  2191. if self.defaults["global_systray_icon"]:
  2192. self.trayIcon.show()
  2193. else:
  2194. log.warning("******************* RUNNING HEADLESS *******************")
  2195. # #####################################################################################
  2196. # ########################## START-UP ARGUMENTS #######################################
  2197. # #####################################################################################
  2198. # test if the program was started with a script as parameter
  2199. if self.cmd_line_shellvar:
  2200. try:
  2201. cnt = 0
  2202. command_tcl = 0
  2203. for i in self.cmd_line_shellvar.split(','):
  2204. if i is not None:
  2205. try:
  2206. command_tcl = eval(i)
  2207. except:
  2208. command_tcl = i
  2209. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  2210. cnt += 1
  2211. # if there are Windows paths then replace the path separator with a Unix like one
  2212. if sys.platform == 'win32':
  2213. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  2214. self.shell._sysShell.exec_command(command_tcl_formatted, no_echo=True)
  2215. except Exception as ext:
  2216. print("ERROR: ", ext)
  2217. sys.exit(2)
  2218. if self.cmd_line_shellfile:
  2219. try:
  2220. if self.ui.shell_dock.isHidden():
  2221. self.ui.shell_dock.show()
  2222. with open(self.cmd_line_shellfile, "r") as myfile:
  2223. if show_splash:
  2224. self.splash.showMessage('%s: %ssec\n%s' % (
  2225. _("Canvas initialization started.\n"
  2226. "Canvas initialization finished in"), '%.2f' % self.used_time,
  2227. _("Executing Tcl Script ...")),
  2228. alignment=Qt.AlignBottom | Qt.AlignLeft,
  2229. color=QtGui.QColor("gray"))
  2230. cmd_line_shellfile_text = myfile.read()
  2231. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  2232. except Exception as ext:
  2233. print("ERROR: ", ext)
  2234. sys.exit(2)
  2235. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2236. # the path/file_name must be enclosed in quotes if it contain spaces
  2237. if App.args:
  2238. self.args_at_startup.emit(App.args)
  2239. @staticmethod
  2240. def copy_and_overwrite(from_path, to_path):
  2241. """
  2242. From here:
  2243. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2244. :param from_path: source path
  2245. :param to_path: destination path
  2246. :return: None
  2247. """
  2248. if os.path.exists(to_path):
  2249. shutil.rmtree(to_path)
  2250. try:
  2251. shutil.copytree(from_path, to_path)
  2252. except FileNotFoundError:
  2253. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2254. shutil.copytree(from_new_path, to_path)
  2255. def on_startup_args(self, args, silent=False):
  2256. """
  2257. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2258. :param args: a list containing the application args at startup
  2259. :return: None
  2260. """
  2261. if args is not None:
  2262. args_to_process = args
  2263. else:
  2264. args_to_process = App.args
  2265. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2266. for argument in args_to_process:
  2267. if '.FlatPrj'.lower() in argument.lower():
  2268. try:
  2269. project_name = str(argument)
  2270. if project_name == "":
  2271. if silent is False:
  2272. self.inform.emit(_("Open cancelled."))
  2273. else:
  2274. # self.open_project(project_name)
  2275. run_from_arg = True
  2276. # self.worker_task.emit({'fcn': self.open_project,
  2277. # 'params': [project_name, run_from_arg]})
  2278. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2279. except Exception as e:
  2280. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2281. elif '.FlatConfig'.lower() in argument.lower():
  2282. try:
  2283. file_name = str(argument)
  2284. if file_name == "":
  2285. if silent is False:
  2286. self.inform.emit(_("Open Config file failed."))
  2287. else:
  2288. run_from_arg = True
  2289. # self.worker_task.emit({'fcn': self.open_config_file,
  2290. # 'params': [file_name, run_from_arg]})
  2291. self.open_config_file(file_name, run_from_arg=run_from_arg)
  2292. except Exception as e:
  2293. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2294. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  2295. try:
  2296. file_name = str(argument)
  2297. if file_name == "":
  2298. if silent is False:
  2299. self.inform.emit(_("Open Script file failed."))
  2300. else:
  2301. if silent is False:
  2302. self.on_fileopenscript(name=file_name)
  2303. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  2304. self.on_filerunscript(name=file_name)
  2305. except Exception as e:
  2306. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2307. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  2308. log.debug("App.on_startup_args() --> Quit event.")
  2309. sys.exit()
  2310. elif 'save'.lower() in argument.lower():
  2311. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  2312. self.save_defaults()
  2313. else:
  2314. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2315. proc_arg = argument.lower()
  2316. for ext in exc_list:
  2317. proc_ext = ext.replace(' ', '')
  2318. proc_ext = '.%s' % proc_ext
  2319. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2320. file_name = str(argument)
  2321. if file_name == "":
  2322. if silent is False:
  2323. self.inform.emit(_("Open Excellon file failed."))
  2324. else:
  2325. self.on_fileopenexcellon(name=file_name)
  2326. return
  2327. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2328. for ext in gco_list:
  2329. proc_ext = ext.replace(' ', '')
  2330. proc_ext = '.%s' % proc_ext
  2331. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2332. print(proc_ext, proc_arg)
  2333. file_name = str(argument)
  2334. if file_name == "":
  2335. if silent is False:
  2336. self.inform.emit(_("Open GCode file failed."))
  2337. else:
  2338. self.on_fileopengcode(name=file_name)
  2339. return
  2340. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2341. for ext in grb_list:
  2342. proc_ext = ext.replace(' ', '')
  2343. proc_ext = '.%s' % proc_ext
  2344. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2345. file_name = str(argument)
  2346. if file_name == "":
  2347. if silent is False:
  2348. self.inform.emit(_("Open Gerber file failed."))
  2349. else:
  2350. self.on_fileopengerber(name=file_name)
  2351. return
  2352. # if it reached here without already returning then the app was registered with a file that it does not
  2353. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  2354. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  2355. for arg in args_to_process:
  2356. if 'FlatCAM.exe' in arg:
  2357. continue
  2358. else:
  2359. sys.exit(2)
  2360. def set_ui_title(self, name):
  2361. """
  2362. Sets the title of the main window.
  2363. :param name: String that store the project path and project name
  2364. :return: None
  2365. """
  2366. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  2367. (self.version,
  2368. ('BETA' if self.beta else ''),
  2369. platform.architecture()[0],
  2370. self.engine,
  2371. name)
  2372. )
  2373. def defaults_read_form(self):
  2374. """
  2375. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2376. :return: None
  2377. """
  2378. for option in self.defaults_form_fields:
  2379. try:
  2380. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2381. except Exception as e:
  2382. log.debug("App.defaults_read_form() --> %s" % str(e))
  2383. def defaults_write_form(self, factor=None, fl_units=None):
  2384. """
  2385. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2386. self.defaults dictionary.
  2387. :param factor: will apply a factor to the values that written in the GUI elements
  2388. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2389. :return: None
  2390. """
  2391. for option in self.defaults:
  2392. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2393. # try:
  2394. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2395. # except KeyError:
  2396. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2397. # # TODO: Rethink this?
  2398. # pass
  2399. def defaults_write_form_field(self, field, factor=None, units=None):
  2400. """
  2401. Basically it is the worker in the self.defaults_write_form()
  2402. :param field: the GUI element in Preferences GUI to be updated
  2403. :param factor: factor to be applied to the field parameter
  2404. :param units: current FLatCAM measuring units
  2405. :return: None, it updates GUI elements
  2406. """
  2407. try:
  2408. if factor is None:
  2409. if units is None:
  2410. self.defaults_form_fields[field].set_value(self.defaults[field])
  2411. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2412. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=6)
  2413. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2414. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=4)
  2415. else:
  2416. if units is None:
  2417. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2418. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2419. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=6)
  2420. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2421. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=4)
  2422. except KeyError:
  2423. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2424. # TODO: Rethink this?
  2425. pass
  2426. except AttributeError:
  2427. log.debug(field)
  2428. def clear_pool(self):
  2429. """
  2430. Clear the multiprocessing pool and calls garbage collector.
  2431. :return: None
  2432. """
  2433. self.pool.close()
  2434. self.pool = Pool()
  2435. self.pool_recreated.emit(self.pool)
  2436. gc.collect()
  2437. def install_tools(self):
  2438. """
  2439. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2440. Instantiation of the Tools classes.
  2441. The order that the tools are installed is important as they can depend on each other install position.
  2442. :return: None
  2443. """
  2444. self.dblsidedtool = DblSidedTool(self)
  2445. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2446. self.measurement_tool = Measurement(self)
  2447. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  2448. self.panelize_tool = Panelize(self)
  2449. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  2450. self.film_tool = Film(self)
  2451. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2452. self.paste_tool = SolderPaste(self)
  2453. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2454. self.calculator_tool = ToolCalculator(self)
  2455. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'), separator=True)
  2456. self.sub_tool = ToolSub(self)
  2457. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2458. self.move_tool = ToolMove(self)
  2459. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2460. before=self.ui.menueditorigin)
  2461. self.cutout_tool = CutOut(self)
  2462. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2463. before=self.measurement_tool.menuAction)
  2464. self.ncclear_tool = NonCopperClear(self)
  2465. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2466. before=self.measurement_tool.menuAction, separator=True)
  2467. self.paint_tool = ToolPaint(self)
  2468. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2469. before=self.measurement_tool.menuAction, separator=True)
  2470. self.transform_tool = ToolTransform(self)
  2471. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2472. self.properties_tool = Properties(self)
  2473. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2474. self.pdf_tool = ToolPDF(self)
  2475. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2476. separator=True)
  2477. self.image_tool = ToolImage(self)
  2478. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2479. separator=True)
  2480. self.pcb_wizard_tool = PcbWizard(self)
  2481. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2482. self.log.debug("Tools are installed.")
  2483. def remove_tools(self):
  2484. """
  2485. Will remove all the actions in the Tool menu.
  2486. :return: None
  2487. """
  2488. for act in self.ui.menutool.actions():
  2489. self.ui.menutool.removeAction(act)
  2490. def init_tools(self):
  2491. """
  2492. Initialize the Tool tab in the notebook side of the central widget.
  2493. Remove the actions in the Tools menu.
  2494. Instantiate again the FlatCAM tools (plugins).
  2495. All this is required when changing the layout: standard, compact etc.
  2496. :return: None
  2497. """
  2498. log.debug("init_tools()")
  2499. # delete the data currently in the Tools Tab and the Tab itself
  2500. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2501. if widget is not None:
  2502. widget.deleteLater()
  2503. self.ui.notebook.removeTab(2)
  2504. # rebuild the Tools Tab
  2505. self.ui.tool_tab = QtWidgets.QWidget()
  2506. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2507. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2508. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2509. self.ui.tool_scroll_area = VerticalScrollArea()
  2510. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2511. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2512. # first remove all of them
  2513. self.remove_tools()
  2514. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2515. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2516. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2517. # third install all of them
  2518. self.install_tools()
  2519. self.log.debug("Tools are initialized.")
  2520. # def parse_system_fonts(self):
  2521. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2522. # 'params': []})
  2523. def connect_toolbar_signals(self):
  2524. """
  2525. Reconnect the signals to the actions in the toolbar.
  2526. This has to be done each time after the FlatCAM tools are removed/installed.
  2527. :return: None
  2528. """
  2529. # Toolbar
  2530. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2531. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2532. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2533. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2534. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2535. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2536. self.ui.replot_btn.triggered.connect(self.plot_all)
  2537. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2538. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2539. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2540. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2541. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2542. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2543. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2544. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2545. self.ui.delete_btn.triggered.connect(self.on_delete)
  2546. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2547. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2548. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2549. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2550. # Tools Toolbar Signals
  2551. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2552. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2553. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2554. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2555. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2556. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2557. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2558. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2559. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2560. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2561. def object2editor(self):
  2562. """
  2563. Send the current Geometry or Excellon object (if any) into the it's editor.
  2564. :return: None
  2565. """
  2566. self.report_usage("object2editor()")
  2567. edited_object = self.collection.get_active()
  2568. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2569. isinstance(edited_object, FlatCAMExcellon):
  2570. pass
  2571. else:
  2572. self.inform.emit('[WARNING_NOTCL] %s' %
  2573. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2574. return
  2575. if isinstance(edited_object, FlatCAMGeometry):
  2576. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2577. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2578. # we set the notebook to hidden
  2579. self.ui.splitter.setSizes([0, 1])
  2580. if edited_object.multigeo is True:
  2581. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  2582. if len(edited_tools) > 1:
  2583. self.inform.emit('[WARNING_NOTCL] %s' %
  2584. _("Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  2585. "is not possible.\n"
  2586. "Edit only one geometry at a time."))
  2587. # determine the tool dia of the selected tool
  2588. selected_tooldia = float(edited_object.ui.geo_tools_table.item((edited_tools[0] - 1), 1).text())
  2589. # now find the key in the edited_object.tools that has this tooldia
  2590. multi_tool = 1
  2591. for tool in edited_object.tools:
  2592. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2593. multi_tool = tool
  2594. break
  2595. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2596. else:
  2597. self.geo_editor.edit_fcgeometry(edited_object)
  2598. # set call source to the Editor we go into
  2599. self.call_source = 'geo_editor'
  2600. elif isinstance(edited_object, FlatCAMExcellon):
  2601. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2602. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2603. if self.ui.splitter.sizes()[0] == 0:
  2604. self.ui.splitter.setSizes([1, 1])
  2605. self.exc_editor.edit_fcexcellon(edited_object)
  2606. # set call source to the Editor we go into
  2607. self.call_source = 'exc_editor'
  2608. elif isinstance(edited_object, FlatCAMGerber):
  2609. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2610. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2611. if self.ui.splitter.sizes()[0] == 0:
  2612. self.ui.splitter.setSizes([1, 1])
  2613. self.grb_editor.edit_fcgerber(edited_object)
  2614. # set call source to the Editor we go into
  2615. self.call_source = 'grb_editor'
  2616. # make sure that we can't select another object while in Editor Mode:
  2617. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2618. self.ui.project_frame.setDisabled(True)
  2619. # delete any selection shape that might be active as they are not relevant in Editor
  2620. self.delete_selection_shape()
  2621. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2622. self.ui.plot_tab_area.protectTab(0)
  2623. self.inform.emit('[WARNING_NOTCL] %s' %
  2624. _("Editor is activated ..."))
  2625. self.should_we_save = True
  2626. def editor2object(self, cleanup=None):
  2627. """
  2628. Transfers the Geometry or Excellon from it's editor to the current object.
  2629. :return: None
  2630. """
  2631. self.report_usage("editor2object()")
  2632. # do not update a geometry or excellon object unless it comes out of an editor
  2633. if self.call_source != 'app':
  2634. edited_obj = self.collection.get_active()
  2635. if cleanup is None:
  2636. msgbox = QtWidgets.QMessageBox()
  2637. msgbox.setText(_("Do you want to save the edited object?"))
  2638. msgbox.setWindowTitle(_("Close Editor"))
  2639. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2640. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2641. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2642. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2643. msgbox.setDefaultButton(bt_yes)
  2644. msgbox.exec_()
  2645. response = msgbox.clickedButton()
  2646. if response == bt_yes:
  2647. # clean the Tools Tab
  2648. self.ui.tool_scroll_area.takeWidget()
  2649. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2650. self.ui.notebook.setTabText(2, "Tool")
  2651. if isinstance(edited_obj, FlatCAMGeometry):
  2652. obj_type = "Geometry"
  2653. if cleanup is None:
  2654. self.geo_editor.update_fcgeometry(edited_obj)
  2655. self.geo_editor.update_options(edited_obj)
  2656. self.geo_editor.deactivate()
  2657. # update the geo object options so it is including the bounding box values
  2658. try:
  2659. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2660. edited_obj.options['xmin'] = xmin
  2661. edited_obj.options['ymin'] = ymin
  2662. edited_obj.options['xmax'] = xmax
  2663. edited_obj.options['ymax'] = ymax
  2664. except AttributeError as e:
  2665. self.inform.emit('[WARNING] %s' %
  2666. _("Object empty after edit."))
  2667. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2668. elif isinstance(edited_obj, FlatCAMGerber):
  2669. obj_type = "Gerber"
  2670. if cleanup is None:
  2671. self.grb_editor.update_fcgerber()
  2672. self.grb_editor.update_options(edited_obj)
  2673. self.grb_editor.deactivate_grb_editor()
  2674. # delete the old object (the source object) if it was an empty one
  2675. if len(edited_obj.solid_geometry) == 0:
  2676. old_name = edited_obj.options['name']
  2677. self.collection.set_active(old_name)
  2678. self.collection.delete_active()
  2679. # restore GUI to the Selected TAB
  2680. # Remove anything else in the GUI
  2681. self.ui.selected_scroll_area.takeWidget()
  2682. # Switch notebook to Selected page
  2683. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2684. elif isinstance(edited_obj, FlatCAMExcellon):
  2685. obj_type = "Excellon"
  2686. if cleanup is None:
  2687. self.exc_editor.update_fcexcellon(edited_obj)
  2688. self.exc_editor.update_options(edited_obj)
  2689. self.exc_editor.deactivate()
  2690. # delete the old object (the source object) if it was an empty one
  2691. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  2692. old_name = edited_obj.options['name']
  2693. self.collection.set_active(old_name)
  2694. self.collection.delete_active()
  2695. # restore GUI to the Selected TAB
  2696. # Remove anything else in the GUI
  2697. self.ui.tool_scroll_area.takeWidget()
  2698. # Switch notebook to Selected page
  2699. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2700. else:
  2701. self.inform.emit('[WARNING_NOTCL] %s' %
  2702. _("Select a Gerber, Geometry or Excellon Object to update."))
  2703. return
  2704. self.inform.emit('[selected] %s %s' %
  2705. (obj_type, _("is updated, returning to App...")))
  2706. elif response == bt_no:
  2707. # clean the Tools Tab
  2708. self.ui.tool_scroll_area.takeWidget()
  2709. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2710. self.ui.notebook.setTabText(2, "Tool")
  2711. if isinstance(edited_obj, FlatCAMGeometry):
  2712. self.geo_editor.deactivate()
  2713. elif isinstance(edited_obj, FlatCAMGerber):
  2714. self.grb_editor.deactivate_grb_editor()
  2715. elif isinstance(edited_obj, FlatCAMExcellon):
  2716. self.exc_editor.deactivate()
  2717. # set focus on the project tab
  2718. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  2719. else:
  2720. self.inform.emit('[WARNING_NOTCL] %s' %
  2721. _("Select a Gerber, Geometry or Excellon Object to update."))
  2722. return
  2723. elif response == bt_cancel:
  2724. return
  2725. else:
  2726. if isinstance(edited_obj, FlatCAMGeometry):
  2727. self.geo_editor.deactivate()
  2728. elif isinstance(edited_obj, FlatCAMGerber):
  2729. self.grb_editor.deactivate_grb_editor()
  2730. elif isinstance(edited_obj, FlatCAMExcellon):
  2731. self.exc_editor.deactivate()
  2732. else:
  2733. self.inform.emit('[WARNING_NOTCL] %s' %
  2734. _("Select a Gerber, Geometry or Excellon Object to update."))
  2735. return
  2736. # if notebook is hidden we show it
  2737. if self.ui.splitter.sizes()[0] == 0:
  2738. self.ui.splitter.setSizes([1, 1])
  2739. # restore the call_source to app
  2740. self.call_source = 'app'
  2741. edited_obj.plot()
  2742. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2743. self.ui.plot_tab_area.protectTab(0)
  2744. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2745. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2746. self.ui.project_frame.setDisabled(False)
  2747. def get_last_folder(self):
  2748. """
  2749. Get the folder path from where the last file was opened.
  2750. :return: String, last opened folder path
  2751. """
  2752. return self.defaults["global_last_folder"]
  2753. def get_last_save_folder(self):
  2754. """
  2755. Get the folder path from where the last file was saved.
  2756. :return: String, last saved folder path
  2757. """
  2758. loc = self.defaults["global_last_save_folder"]
  2759. if loc is None:
  2760. loc = self.defaults["global_last_folder"]
  2761. if loc is None:
  2762. loc = os.path.dirname(__file__)
  2763. return loc
  2764. def report_usage(self, resource):
  2765. """
  2766. Increments usage counter for the given resource
  2767. in self.defaults['global_stats'].
  2768. :param resource: Name of the resource.
  2769. :return: None
  2770. """
  2771. if resource in self.defaults['global_stats']:
  2772. self.defaults['global_stats'][resource] += 1
  2773. else:
  2774. self.defaults['global_stats'][resource] = 1
  2775. def init_tcl(self):
  2776. """
  2777. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2778. :return: None
  2779. """
  2780. if hasattr(self, 'tcl'):
  2781. # self.tcl = None
  2782. # TODO we need to clean non default variables and procedures here
  2783. # new object cannot be used here as it will not remember values created for next passes,
  2784. # because tcl was execudted in old instance of TCL
  2785. pass
  2786. else:
  2787. self.tcl = tk.Tcl()
  2788. self.setup_shell()
  2789. self.log.debug("TCL Shell has been initialized.")
  2790. # TODO: This shouldn't be here.
  2791. class TclErrorException(Exception):
  2792. """
  2793. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2794. """
  2795. pass
  2796. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2797. """
  2798. Shows a message on the FlatCAM Shell
  2799. :param msg: Message to display.
  2800. :param show: Opens the shell.
  2801. :param error: Shows the message as an error.
  2802. :param warning: Shows the message as an warning.
  2803. :param success: Shows the message as an success.
  2804. :param selected: Indicate that something was selected on canvas
  2805. :return: None
  2806. """
  2807. if show:
  2808. self.ui.shell_dock.show()
  2809. try:
  2810. if error:
  2811. self.shell.append_error(msg + "\n")
  2812. elif warning:
  2813. self.shell.append_warning(msg + "\n")
  2814. elif success:
  2815. self.shell.append_success(msg + "\n")
  2816. elif selected:
  2817. self.shell.append_selected(msg + "\n")
  2818. else:
  2819. self.shell.append_output(msg + "\n")
  2820. except AttributeError:
  2821. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2822. def raise_tcl_unknown_error(self, unknownException):
  2823. """
  2824. Raise exception if is different type than TclErrorException
  2825. this is here mainly to show unknown errors inside TCL shell console.
  2826. :param unknownException:
  2827. :return:
  2828. """
  2829. if not isinstance(unknownException, self.TclErrorException):
  2830. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2831. else:
  2832. raise unknownException
  2833. def display_tcl_error(self, error, error_info=None):
  2834. """
  2835. Escape bracket [ with '\' otherwise there is error
  2836. "ERROR: missing close-bracket" instead of real error
  2837. :param error: it may be text or exception
  2838. :param error_info: Some informations about the error
  2839. :return: None
  2840. """
  2841. if isinstance(error, Exception):
  2842. exc_type, exc_value, exc_traceback = error_info
  2843. if not isinstance(error, self.TclErrorException):
  2844. show_trace = 1
  2845. else:
  2846. show_trace = int(self.defaults['global_verbose_error_level'])
  2847. if show_trace > 0:
  2848. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2849. trc_formated = []
  2850. for a in reversed(trc):
  2851. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2852. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2853. else:
  2854. text = "%s" % error
  2855. else:
  2856. text = error
  2857. text = text.replace('[', '\\[').replace('"', '\\"')
  2858. self.tcl.eval('return -code error "%s"' % text)
  2859. def raise_tcl_error(self, text):
  2860. """
  2861. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2862. :param text: text of error
  2863. :return: raise exception
  2864. """
  2865. self.display_tcl_error(text)
  2866. raise self.TclErrorException(text)
  2867. def exec_command(self, text, no_echo=False):
  2868. """
  2869. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2870. Also handles execution in separated threads
  2871. :param text: FlatCAM TclCommand with parameters
  2872. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2873. will create crashes of the _Expandable_Edit widget
  2874. :return: output if there was any
  2875. """
  2876. self.report_usage('exec_command')
  2877. result = self.exec_command_test(text, False, no_echo=no_echo)
  2878. # MS: added this method call so the geometry is updated once the TCL command is executed
  2879. # if no_plot is None:
  2880. # self.plot_all()
  2881. return result
  2882. def exec_command_test(self, text, reraise=True, no_echo=False):
  2883. """
  2884. Same as exec_command(...) with additional control over exceptions.
  2885. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2886. :param text: Input command
  2887. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2888. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2889. will create crashes of the _Expandable_Edit widget
  2890. :return: Output from the command
  2891. """
  2892. tcl_command_string = str(text)
  2893. try:
  2894. if no_echo is False:
  2895. self.shell.open_proccessing() # Disables input box.
  2896. result = self.tcl.eval(str(tcl_command_string))
  2897. if result != 'None' and no_echo is False:
  2898. self.shell.append_output(result + '\n')
  2899. except tk.TclError as e:
  2900. # This will display more precise answer if something in TCL shell fails
  2901. result = self.tcl.eval("set errorInfo")
  2902. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2903. if no_echo is False:
  2904. self.shell.append_error('ERROR: ' + result + '\n')
  2905. # Show error in console and just return or in test raise exception
  2906. if reraise:
  2907. raise e
  2908. finally:
  2909. if no_echo is False:
  2910. self.shell.close_proccessing()
  2911. pass
  2912. return result
  2913. # """
  2914. # Code below is unsused. Saved for later.
  2915. # """
  2916. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2917. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2918. # self.log.debug(parts)
  2919. # try:
  2920. # if parts[0] not in commands:
  2921. # self.shell.append_error("Unknown command\n")
  2922. # return
  2923. #
  2924. # #import inspect
  2925. # #inspect.getargspec(someMethod)
  2926. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2927. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2928. # self.shell.append_error(
  2929. # "Command %s takes %d arguments. %d given.\n" %
  2930. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2931. # )
  2932. # return
  2933. #
  2934. # cmdfcn = commands[parts[0]]["fcn"]
  2935. # cmdconv = commands[parts[0]]["converters"]
  2936. # if len(parts) - 1 > 0:
  2937. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2938. # else:
  2939. # retval = cmdfcn()
  2940. # retfcn = commands[parts[0]]["retfcn"]
  2941. # if retval and retfcn(retval):
  2942. # self.shell.append_output(retfcn(retval) + "\n")
  2943. #
  2944. # except Exception as e:
  2945. # #self.shell.append_error(''.join(traceback.format_exc()))
  2946. # #self.shell.append_error("?\n")
  2947. # self.shell.append_error(str(e) + "\n")
  2948. def info(self, msg):
  2949. """
  2950. Informs the user. Normally on the status bar, optionally
  2951. also on the shell.
  2952. :param msg: Text to write.
  2953. :return: None
  2954. """
  2955. # Type of message in brackets at the beginning of the message.
  2956. match = re.search("\[([^\]]+)\](.*)", msg)
  2957. if match:
  2958. level = match.group(1)
  2959. msg_ = match.group(2)
  2960. self.ui.fcinfo.set_status(str(msg_), level=level)
  2961. if level.lower() == "error":
  2962. self.shell_message(msg, error=True, show=True)
  2963. elif level.lower() == "warning":
  2964. self.shell_message(msg, warning=True, show=True)
  2965. elif level.lower() == "error_notcl":
  2966. self.shell_message(msg, error=True, show=False)
  2967. elif level.lower() == "warning_notcl":
  2968. self.shell_message(msg, warning=True, show=False)
  2969. elif level.lower() == "success":
  2970. self.shell_message(msg, success=True, show=False)
  2971. elif level.lower() == "selected":
  2972. self.shell_message(msg, selected=True, show=False)
  2973. else:
  2974. self.shell_message(msg, show=False)
  2975. else:
  2976. self.ui.fcinfo.set_status(str(msg), level="info")
  2977. # make sure that if the message is to clear the infobar with a space
  2978. # is not printed over and over on the shell
  2979. if msg != '':
  2980. self.shell_message(msg)
  2981. def restore_toolbar_view(self):
  2982. """
  2983. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  2984. was saved in the defaults dictionary.
  2985. :return: None
  2986. """
  2987. tb = self.defaults["global_toolbar_view"]
  2988. if tb & 1:
  2989. self.ui.toolbarfile.setVisible(True)
  2990. else:
  2991. self.ui.toolbarfile.setVisible(False)
  2992. if tb & 2:
  2993. self.ui.toolbargeo.setVisible(True)
  2994. else:
  2995. self.ui.toolbargeo.setVisible(False)
  2996. if tb & 4:
  2997. self.ui.toolbarview.setVisible(True)
  2998. else:
  2999. self.ui.toolbarview.setVisible(False)
  3000. if tb & 8:
  3001. self.ui.toolbartools.setVisible(True)
  3002. else:
  3003. self.ui.toolbartools.setVisible(False)
  3004. if tb & 16:
  3005. self.ui.exc_edit_toolbar.setVisible(True)
  3006. else:
  3007. self.ui.exc_edit_toolbar.setVisible(False)
  3008. if tb & 32:
  3009. self.ui.geo_edit_toolbar.setVisible(True)
  3010. else:
  3011. self.ui.geo_edit_toolbar.setVisible(False)
  3012. if tb & 64:
  3013. self.ui.grb_edit_toolbar.setVisible(True)
  3014. else:
  3015. self.ui.grb_edit_toolbar.setVisible(False)
  3016. if tb & 128:
  3017. self.ui.snap_toolbar.setVisible(True)
  3018. else:
  3019. self.ui.snap_toolbar.setVisible(False)
  3020. if tb & 256:
  3021. self.ui.toolbarshell.setVisible(True)
  3022. else:
  3023. self.ui.toolbarshell.setVisible(False)
  3024. def load_defaults(self, filename):
  3025. """
  3026. Loads the aplication's default settings from current_defaults.FlatConfig into
  3027. ``self.defaults``.
  3028. :return: None
  3029. """
  3030. try:
  3031. f = open(self.data_path + "/" + filename + ".FlatConfig")
  3032. options = f.read()
  3033. f.close()
  3034. except IOError:
  3035. self.log.error("Could not load defaults file.")
  3036. self.inform.emit('[ERROR] %s' %
  3037. _("Could not load defaults file."))
  3038. # in case the defaults file can't be loaded, show all toolbars
  3039. self.defaults["global_toolbar_view"] = 511
  3040. return
  3041. try:
  3042. defaults = json.loads(options)
  3043. except:
  3044. # in case the defaults file can't be loaded, show all toolbars
  3045. self.defaults["global_toolbar_view"] = 511
  3046. e = sys.exc_info()[0]
  3047. App.log.error(str(e))
  3048. self.inform.emit('[ERROR] %s' %
  3049. _("Failed to parse defaults file."))
  3050. return
  3051. self.defaults.update(defaults)
  3052. log.debug("FlatCAM defaults loaded from: %s" % filename)
  3053. # restore the toolbar view
  3054. self.restore_toolbar_view()
  3055. def on_import_preferences(self):
  3056. """
  3057. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  3058. ``self.defaults``.
  3059. :return: None
  3060. """
  3061. self.report_usage("on_import_preferences")
  3062. App.log.debug("on_import_preferences()")
  3063. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  3064. try:
  3065. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3066. directory=self.data_path,
  3067. filter=filter_)
  3068. except TypeError:
  3069. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3070. filter=filter_)
  3071. filename = str(filename)
  3072. if filename == "":
  3073. self.inform.emit('[WARNING_NOTCL] %s' %
  3074. _("FlatCAM preferences import cancelled."))
  3075. else:
  3076. try:
  3077. f = open(filename)
  3078. options = f.read()
  3079. f.close()
  3080. except IOError:
  3081. self.log.error("Could not load defaults file.")
  3082. self.inform.emit('[ERROR_NOTCL] %s' %
  3083. _("Could not load defaults file."))
  3084. return
  3085. try:
  3086. defaults_from_file = json.loads(options)
  3087. except Exception as e:
  3088. e = sys.exc_info()[0]
  3089. App.log.error(str(e))
  3090. self.inform.emit('[ERROR_NOTCL] %s' %
  3091. _("Failed to parse defaults file."))
  3092. return
  3093. self.defaults.update(defaults_from_file)
  3094. self.on_preferences_edited()
  3095. self.inform.emit('[success] %s: %s' %
  3096. (_("Imported Defaults from"), filename))
  3097. def on_export_preferences(self):
  3098. """
  3099. Save the defaults dictionary to a file.
  3100. :return: None
  3101. """
  3102. self.report_usage("on_export_preferences")
  3103. App.log.debug("on_export_preferences()")
  3104. defaults_file_content = None
  3105. self.date = str(datetime.today()).rpartition('.')[0]
  3106. self.date = ''.join(c for c in self.date if c not in ':-')
  3107. self.date = self.date.replace(' ', '_')
  3108. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  3109. try:
  3110. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  3111. caption=_("Export FlatCAM Preferences"),
  3112. directory=self.data_path + '/preferences_' + self.date,
  3113. filter=filter__
  3114. )
  3115. except TypeError:
  3116. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  3117. filter=filter__)
  3118. filename = str(filename)
  3119. defaults_from_file = {}
  3120. if filename == "":
  3121. self.inform.emit('[WARNING_NOTCL] %s' %
  3122. _("FlatCAM preferences export cancelled."))
  3123. return
  3124. else:
  3125. try:
  3126. f = open(filename, 'w')
  3127. defaults_file_content = f.read()
  3128. f.close()
  3129. except PermissionError:
  3130. self.inform.emit('[WARNING] %s' %
  3131. _("Permission denied, saving not possible.\n"
  3132. "Most likely another app is holding the file open and not accessible."))
  3133. return
  3134. except IOError:
  3135. App.log.debug('Creating a new preferences file ...')
  3136. f = open(filename, 'w')
  3137. json.dump({}, f)
  3138. f.close()
  3139. except:
  3140. e = sys.exc_info()[0]
  3141. App.log.error("Could not load defaults file.")
  3142. App.log.error(str(e))
  3143. self.inform.emit('[ERROR_NOTCL] %s' %
  3144. _("Could not load preferences file."))
  3145. return
  3146. try:
  3147. defaults_from_file = json.loads(defaults_file_content)
  3148. except:
  3149. App.log.warning("Trying to read an empty Preferences file. Continue.")
  3150. # Update options
  3151. self.defaults_read_form()
  3152. defaults_from_file.update(self.defaults)
  3153. self.propagate_defaults(silent=True)
  3154. # Save update options
  3155. try:
  3156. f = open(filename, "w")
  3157. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  3158. f.close()
  3159. except:
  3160. self.inform.emit('[ERROR_NOTCL] %s' %
  3161. _("Failed to write defaults to file."))
  3162. return
  3163. if self.defaults["global_open_style"] is False:
  3164. self.file_opened.emit("preferences", filename)
  3165. self.file_saved.emit("preferences", filename)
  3166. self.inform.emit('[success] %s: %s' %
  3167. (_("Exported preferences to"), filename))
  3168. def on_preferences_open_folder(self):
  3169. """
  3170. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  3171. :return: None
  3172. """
  3173. self.report_usage("on_preferences_open_folder()")
  3174. if sys.platform == 'win32':
  3175. subprocess.Popen('explorer %s' % self.data_path)
  3176. elif sys.platform == 'darwin':
  3177. os.system('open "%s"' % self.data_path)
  3178. else:
  3179. subprocess.Popen(['xdg-open', self.data_path])
  3180. self.inform.emit('[success] %s' %
  3181. _("FlatCAM Preferences Folder opened."))
  3182. def save_geometry(self, x, y, width, height, notebook_width):
  3183. """
  3184. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  3185. launch of the application.
  3186. :param x: X position of the main window
  3187. :param y: Y position of the main window
  3188. :param width: width of the main window
  3189. :param height: height of the main window
  3190. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  3191. :return: None
  3192. """
  3193. self.defaults["global_def_win_x"] = x
  3194. self.defaults["global_def_win_y"] = y
  3195. self.defaults["global_def_win_w"] = width
  3196. self.defaults["global_def_win_h"] = height
  3197. self.defaults["global_def_notebook_width"] = notebook_width
  3198. self.save_defaults()
  3199. def restore_main_win_geom(self):
  3200. try:
  3201. self.ui.setGeometry(self.defaults["global_def_win_x"],
  3202. self.defaults["global_def_win_y"],
  3203. self.defaults["global_def_win_w"],
  3204. self.defaults["global_def_win_h"])
  3205. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  3206. except KeyError as e:
  3207. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  3208. def message_dialog(self, title, message, kind="info"):
  3209. """
  3210. Builds and show a custom QMessageBox to be used in FlatCAM.
  3211. :param title: title of the QMessageBox
  3212. :param message: message to be displayed
  3213. :param kind: type of QMessageBox; will display a specific icon.
  3214. :return:
  3215. """
  3216. icon = {"info": QtWidgets.QMessageBox.Information,
  3217. "warning": QtWidgets.QMessageBox.Warning,
  3218. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3219. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  3220. dlg.setText(message)
  3221. dlg.exec_()
  3222. def register_recent(self, kind, filename):
  3223. """
  3224. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  3225. dictionary.
  3226. :param kind: type of file that was opened
  3227. :param filename: the path and file name for the file that was opened
  3228. :return:
  3229. """
  3230. self.log.debug("register_recent()")
  3231. self.log.debug(" %s" % kind)
  3232. self.log.debug(" %s" % filename)
  3233. record = {'kind': str(kind), 'filename': str(filename)}
  3234. if record in self.recent:
  3235. return
  3236. if record in self.recent_projects:
  3237. return
  3238. if record['kind'] == 'project':
  3239. self.recent_projects.insert(0, record)
  3240. else:
  3241. self.recent.insert(0, record)
  3242. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3243. self.recent.pop()
  3244. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3245. self.recent_projects.pop()
  3246. try:
  3247. f = open(self.data_path + '/recent.json', 'w')
  3248. except IOError:
  3249. App.log.error("Failed to open recent items file for writing.")
  3250. self.inform.emit('[ERROR_NOTCL] %s' %
  3251. _('Failed to open recent files file for writing.'))
  3252. return
  3253. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3254. f.close()
  3255. try:
  3256. fp = open(self.data_path + '/recent_projects.json', 'w')
  3257. except IOError:
  3258. App.log.error("Failed to open recent items file for writing.")
  3259. self.inform.emit('[ERROR_NOTCL] %s' %
  3260. _('Failed to open recent projects file for writing.'))
  3261. return
  3262. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3263. fp.close()
  3264. # Re-build the recent items menu
  3265. self.setup_recent_items()
  3266. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3267. """
  3268. Creates a new specialized FlatCAMObj and attaches it to the application,
  3269. this is, updates the GUI accordingly, any other records and plots it.
  3270. This method is thread-safe.
  3271. Notes:
  3272. * If the name is in use, the self.collection will modify it
  3273. when appending it to the collection. There is no need to handle
  3274. name conflicts here.
  3275. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3276. :type kind: str
  3277. :param name: Name for the object.
  3278. :type name: str
  3279. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3280. The function is called with 2 parameters: the new object and the App instance.
  3281. :type initialize: function
  3282. :param active:
  3283. :param fit:
  3284. :param plot: If to plot the resulting object
  3285. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3286. self.colleaction
  3287. :return: None
  3288. :rtype: None
  3289. """
  3290. App.log.debug("new_object()")
  3291. obj_plot = plot
  3292. obj_autoselected = autoselected
  3293. t0 = time.time() # Debug
  3294. # ## Create object
  3295. classdict = {
  3296. "gerber": FlatCAMGerber,
  3297. "excellon": FlatCAMExcellon,
  3298. "cncjob": FlatCAMCNCjob,
  3299. "geometry": FlatCAMGeometry
  3300. }
  3301. App.log.debug("Calling object constructor...")
  3302. obj = classdict[kind](name)
  3303. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3304. # Set options from "Project options" form
  3305. self.options_read_form()
  3306. # IMPORTANT
  3307. # The key names in defaults and options dictionary's are not random:
  3308. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3309. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  3310. # the options from project options form into the self.options. After that, below, depending on the type of
  3311. # object that is created, it will strip the name of the object and the underline (if the original key was
  3312. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3313. # "toolchange"
  3314. for option in self.options:
  3315. if option.find(kind + "_") == 0:
  3316. oname = option[len(kind) + 1:]
  3317. obj.options[oname] = self.options[option]
  3318. obj.isHovering = False
  3319. obj.notHovering = True
  3320. # Initialize as per user request
  3321. # User must take care to implement initialize
  3322. # in a thread-safe way as is is likely that we
  3323. # have been invoked in a separate thread.
  3324. t1 = time.time()
  3325. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3326. try:
  3327. return_value = initialize(obj, self)
  3328. except Exception as e:
  3329. msg = '[ERROR_NOTCL] %s' % \
  3330. _("An internal error has ocurred. See shell.\n")
  3331. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3332. msg += traceback.format_exc()
  3333. self.inform.emit(msg)
  3334. # if str(e) == "Empty Geometry":
  3335. # self.inform.emit("[ERROR_NOTCL] )
  3336. # else:
  3337. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  3338. return "fail"
  3339. t2 = time.time()
  3340. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3341. if return_value == 'fail':
  3342. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3343. return "fail"
  3344. # Check units and convert if necessary
  3345. # This condition CAN be true because initialize() can change obj.units
  3346. if self.options["units"].upper() != obj.units.upper():
  3347. self.inform.emit('%s: %s' %
  3348. (_("Converting units to "), self.options["units"]))
  3349. obj.convert_units(self.options["units"])
  3350. t3 = time.time()
  3351. self.log.debug("%f seconds converting units." % (t3 - t2))
  3352. # Create the bounding box for the object and then add the results to the obj.options
  3353. try:
  3354. xmin, ymin, xmax, ymax = obj.bounds()
  3355. obj.options['xmin'] = xmin
  3356. obj.options['ymin'] = ymin
  3357. obj.options['xmax'] = xmax
  3358. obj.options['ymax'] = ymax
  3359. except Exception as e:
  3360. log.warning("The object has no bounds properties. %s" % str(e))
  3361. return "fail"
  3362. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3363. # Move the object to the main thread and let the app know that it is available.
  3364. obj.moveToThread(self.main_thread)
  3365. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3366. return obj
  3367. def new_excellon_object(self):
  3368. """
  3369. Creates a new, blank Excellon object.
  3370. :return: None
  3371. """
  3372. self.report_usage("new_excellon_object()")
  3373. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3374. def new_geometry_object(self):
  3375. """
  3376. Creates a new, blank and single-tool Geometry object.
  3377. :return: None
  3378. """
  3379. self.report_usage("new_geometry_object()")
  3380. def initialize(obj, self):
  3381. obj.multitool = False
  3382. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3383. def new_gerber_object(self):
  3384. """
  3385. Creates a new, blank Gerber object.
  3386. :return: None
  3387. """
  3388. self.report_usage("new_gerber_object()")
  3389. def initialize(grb_obj, self):
  3390. grb_obj.multitool = False
  3391. grb_obj.source_file = []
  3392. grb_obj.multigeo = False
  3393. grb_obj.follow = False
  3394. grb_obj.apertures = {}
  3395. grb_obj.solid_geometry = []
  3396. try:
  3397. grb_obj.options['xmin'] = 0
  3398. grb_obj.options['ymin'] = 0
  3399. grb_obj.options['xmax'] = 0
  3400. grb_obj.options['ymax'] = 0
  3401. except KeyError:
  3402. pass
  3403. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3404. def on_object_created(self, obj, plot, autoselect):
  3405. """
  3406. Event callback for object creation.
  3407. It will add the new object to the collection. After that it will plot the object in a threaded way
  3408. :param obj: The newly created FlatCAM object.
  3409. :param plot: if the newly create object t obe plotted
  3410. :param autoselect: if the newly created object to be autoselected after creation
  3411. :return: None
  3412. """
  3413. t0 = time.time() # DEBUG
  3414. self.log.debug("on_object_created()")
  3415. # The Collection might change the name if there is a collision
  3416. self.collection.append(obj)
  3417. # after adding the object to the collection always update the list of objects that are in the collection
  3418. self.all_objects_list = self.collection.get_list()
  3419. # self.inform.emit('[selected] %s created & selected: %s' %
  3420. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3421. if obj.kind == 'gerber':
  3422. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3423. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3424. elif obj.kind == 'excellon':
  3425. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3426. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3427. elif obj.kind == 'cncjob':
  3428. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3429. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3430. elif obj.kind == 'geometry':
  3431. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3432. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3433. # update the SHELL auto-completer model with the name of the new object
  3434. self.myKeywords.append(obj.options['name'])
  3435. self.shell._edit.set_model_data(self.myKeywords)
  3436. self.ui.code_editor.set_model_data(self.myKeywords)
  3437. if autoselect:
  3438. # select the just opened object but deselect the previous ones
  3439. self.collection.set_all_inactive()
  3440. self.collection.set_active(obj.options["name"])
  3441. else:
  3442. self.collection.set_all_inactive()
  3443. # here it is done the object plotting
  3444. def worker_task(t_obj):
  3445. with self.proc_container.new(_("Plotting")):
  3446. if isinstance(t_obj, FlatCAMCNCjob):
  3447. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3448. else:
  3449. t_obj.plot()
  3450. t1 = time.time() # DEBUG
  3451. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3452. self.object_plotted.emit(t_obj)
  3453. # Send to worker
  3454. # self.worker.add_task(worker_task, [self])
  3455. if plot is True:
  3456. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3457. def on_object_changed(self, obj):
  3458. """
  3459. Called whenever the geometry of the object was changed in some way.
  3460. This require the update of it's bounding values so it can be the selected on canvas.
  3461. Update the bounding box data from obj.options
  3462. :param obj: the object that was changed
  3463. :return: None
  3464. """
  3465. xmin, ymin, xmax, ymax = obj.bounds()
  3466. obj.options['xmin'] = xmin
  3467. obj.options['ymin'] = ymin
  3468. obj.options['xmax'] = xmax
  3469. obj.options['ymax'] = ymax
  3470. log.debug("Object changed, updating the bounding box data on self.options")
  3471. # delete the old selection shape
  3472. self.delete_selection_shape()
  3473. self.should_we_save = True
  3474. def on_object_plotted(self, obj):
  3475. """
  3476. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3477. :param obj: object to be fit into view
  3478. :return: None
  3479. """
  3480. self.on_zoom_fit(None)
  3481. def options_read_form(self):
  3482. """
  3483. Same as it's equivalent from the defaults.
  3484. self.options use to store the preferences per project. No longer used.
  3485. :return: None
  3486. """
  3487. for option in self.options_form_fields:
  3488. self.options[option] = self.options_form_fields[option].get_value()
  3489. def options_write_form(self):
  3490. """
  3491. Same as it's equivalent from the defaults.
  3492. self.options use to store the preferences per project. No longer used.
  3493. :return: None
  3494. """
  3495. for option in self.options:
  3496. self.options_write_form_field(option)
  3497. def options_write_form_field(self, field):
  3498. """
  3499. Same as it's equivalent from the defaults.
  3500. self.options use to store the preferences per project. No longer used.
  3501. :return: None
  3502. """
  3503. try:
  3504. self.options_form_fields[field].set_value(self.options[field])
  3505. except KeyError:
  3506. # Changed from error to debug. This allows to have data stored
  3507. # which is not user-editable.
  3508. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  3509. pass
  3510. def on_about(self):
  3511. """
  3512. Displays the "about" dialog found in the Menu --> Help.
  3513. :return: None
  3514. """
  3515. self.report_usage("on_about")
  3516. version = self.version
  3517. version_date = self.version_date
  3518. beta = self.beta
  3519. class AboutDialog(QtWidgets.QDialog):
  3520. def __init__(self, parent=None):
  3521. QtWidgets.QDialog.__init__(self, parent)
  3522. # Icon and title
  3523. self.setWindowIcon(parent.app_icon)
  3524. self.setWindowTitle(_("About FlatCAM"))
  3525. self.resize(600, 200)
  3526. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3527. # self.setStyleSheet(
  3528. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3529. # "background-attachment: fixed"
  3530. # )
  3531. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3532. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3533. # palette = QtGui.QPalette()
  3534. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3535. # self.setPalette(palette)
  3536. logo = QtWidgets.QLabel()
  3537. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3538. title = QtWidgets.QLabel(
  3539. "<font size=8><B>FlatCAM</B></font><BR>"
  3540. "{title}<BR>"
  3541. "<BR>"
  3542. "<BR>"
  3543. # "<B>{devel}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3544. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3545. # "<b>{down}</B> area &nbsp;&nbsp;&nbsp;&nbsp;"
  3546. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3547. # "<b> {issue}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3548. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3549. "<B>{issue}</B></a><BR>".format(
  3550. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3551. devel=_("Development"),
  3552. down=_("DOWNLOAD"),
  3553. issue=_("Issue tracker"))
  3554. )
  3555. title.setOpenExternalLinks(True)
  3556. closebtn = QtWidgets.QPushButton(_("Close"))
  3557. tab_widget = QtWidgets.QTabWidget()
  3558. description_label = QtWidgets.QLabel(
  3559. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3560. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3561. version=version,
  3562. beta=('BETA' if beta else ''),
  3563. date=version_date,
  3564. arch=platform.architecture()[0])
  3565. )
  3566. description_label.setOpenExternalLinks(True)
  3567. license_label = QtWidgets.QLabel(
  3568. _(
  3569. '(c) Copyright 2014 Juan Pablo Caram.\n\n'
  3570. 'Licensed under the MIT license:\n'
  3571. 'http://www.opensource.org/licenses/mit-license.php\n\n'
  3572. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3573. 'of this software and associated documentation files (the "Software"), to deal\n'
  3574. 'in the Software without restriction, including without limitation the rights\n'
  3575. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3576. 'copies of the Software, and to permit persons to whom the Software is\n'
  3577. ' furnished to do so, subject to the following conditions:\n\n'
  3578. 'The above copyright notice and this permission notice shall be included in\n'
  3579. 'all copies or substantial portions of the Software.\n\n'
  3580. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3581. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3582. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3583. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3584. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3585. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3586. 'THE SOFTWARE.'
  3587. )
  3588. )
  3589. license_label.setOpenExternalLinks(True)
  3590. # layouts
  3591. layout1 = QtWidgets.QVBoxLayout()
  3592. layout1_1 = QtWidgets.QHBoxLayout()
  3593. layout1_2 = QtWidgets.QHBoxLayout()
  3594. layout2 = QtWidgets.QHBoxLayout()
  3595. layout3 = QtWidgets.QHBoxLayout()
  3596. self.setLayout(layout1)
  3597. layout1.addLayout(layout1_1)
  3598. layout1.addLayout(layout1_2)
  3599. layout1.addLayout(layout2)
  3600. layout1.addLayout(layout3)
  3601. layout1_1.addStretch()
  3602. layout1_1.addWidget(description_label)
  3603. layout1_2.addWidget(tab_widget)
  3604. self.splash_tab = QtWidgets.QWidget()
  3605. self.splash_tab.setObjectName("splash_about")
  3606. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3607. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3608. tab_widget.addTab(self.splash_tab, _("Splash"))
  3609. self.programmmers_tab = QtWidgets.QWidget()
  3610. self.programmmers_tab.setObjectName("programmers_about")
  3611. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3612. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3613. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3614. self.translators_tab = QtWidgets.QWidget()
  3615. self.translators_tab.setObjectName("translators_about")
  3616. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3617. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3618. tab_widget.addTab(self.translators_tab, _("Translators"))
  3619. self.license_tab = QtWidgets.QWidget()
  3620. self.license_tab.setObjectName("license_about")
  3621. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3622. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3623. tab_widget.addTab(self.license_tab, _("License"))
  3624. self.splash_tab_layout.addWidget(logo, stretch=0)
  3625. self.splash_tab_layout.addWidget(title, stretch=1)
  3626. pal = QtGui.QPalette()
  3627. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3628. self.prog_form_lay = QtWidgets.QFormLayout()
  3629. self.prog_form_lay.setHorizontalSpacing(20)
  3630. prog_widget = QtWidgets.QWidget()
  3631. prog_widget.setLayout(self.prog_form_lay)
  3632. prog_scroll = QtWidgets.QScrollArea()
  3633. prog_scroll.setWidget(prog_widget)
  3634. prog_scroll.setWidgetResizable(True)
  3635. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3636. prog_scroll.setPalette(pal)
  3637. self.programmmers_tab_layout.addWidget(prog_scroll)
  3638. self.prog_form_lay.addRow(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")),
  3639. QtWidgets.QLabel('<b>%s</b>' % _("Status")))
  3640. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Juan Pablo Caram"),
  3641. QtWidgets.QLabel('%s' % _("Program Author")))
  3642. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Denis Hayrullin"))
  3643. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Kamil Sopko"))
  3644. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marius Stanciu"),
  3645. QtWidgets.QLabel('%s' % _("Maintainer >=2019")))
  3646. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3647. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Alexandru Lazar"))
  3648. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Matthieu Berthomé"))
  3649. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Evans"))
  3650. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Victor Benso"))
  3651. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3652. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Barnaby Walters"))
  3653. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"))
  3654. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lei Zheng"))
  3655. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marco A Quezada"))
  3656. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3657. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Cedric Dussud"))
  3658. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Chris Hemingway"))
  3659. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Damian Wrobel"))
  3660. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Daniel Sallin"))
  3661. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3662. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Bruno Vunderl"))
  3663. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Gonzalo Lopez"))
  3664. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jakob Staudt"))
  3665. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Smith"))
  3666. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3667. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lubos Medovarsky"))
  3668. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Steve Martina"))
  3669. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Thomas Duffin"))
  3670. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3671. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Idechix"))
  3672. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@SM"))
  3673. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@grbf"))
  3674. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Symonty"))
  3675. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@mgix"))
  3676. self.translator_grid_lay = QtWidgets.QGridLayout()
  3677. # trans_widget = QtWidgets.QWidget()
  3678. # trans_widget.setLayout(self.translator_grid_lay)
  3679. # self.translators_tab_layout.addWidget(trans_widget)
  3680. # self.translators_tab_layout.addStretch()
  3681. trans_widget = QtWidgets.QWidget()
  3682. trans_widget.setLayout(self.translator_grid_lay)
  3683. trans_scroll = QtWidgets.QScrollArea()
  3684. trans_scroll.setWidget(trans_widget)
  3685. trans_scroll.setWidgetResizable(True)
  3686. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3687. trans_scroll.setPalette(pal)
  3688. self.translators_tab_layout.addWidget(trans_scroll)
  3689. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  3690. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  3691. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3692. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Brasilian - Portuguese"), 1, 0)
  3693. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  3694. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 1, 2)
  3695. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  3696. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 2, 1)
  3697. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 2)
  3698. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  3699. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 3, 1)
  3700. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  3701. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  3702. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  3703. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  3704. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  3705. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  3706. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 2)
  3707. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  3708. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 6, 1)
  3709. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 2)
  3710. self.translator_grid_lay.setColumnStretch(0, 0)
  3711. self.translators_tab_layout.addStretch()
  3712. self.license_tab_layout.addWidget(license_label)
  3713. self.license_tab_layout.addStretch()
  3714. layout3.addStretch()
  3715. layout3.addWidget(closebtn)
  3716. closebtn.clicked.connect(self.accept)
  3717. AboutDialog(self.ui).exec_()
  3718. def on_file_savedefaults(self):
  3719. """
  3720. Callback for menu item File->Save Defaults. Saves application default options
  3721. ``self.defaults`` to current_defaults.FlatConfig.
  3722. :return: None
  3723. """
  3724. self.save_defaults()
  3725. # def on_app_exit(self):
  3726. # self.report_usage("on_app_exit()")
  3727. #
  3728. # if self.collection.get_list():
  3729. # msgbox = QtWidgets.QMessageBox()
  3730. # # msgbox.setText("<B>Save changes ...</B>")
  3731. # msgbox.setText("There are files/objects opened in FlatCAM. "
  3732. # "\n"
  3733. # "Do you want to Save the project?")
  3734. # msgbox.setWindowTitle("Save changes")
  3735. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3736. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  3737. # QtWidgets.QMessageBox.Cancel)
  3738. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  3739. #
  3740. # response = msgbox.exec_()
  3741. #
  3742. # if response == QtWidgets.QMessageBox.Yes:
  3743. # self.on_file_saveprojectas(thread=False)
  3744. # elif response == QtWidgets.QMessageBox.Cancel:
  3745. # return
  3746. # self.save_defaults()
  3747. # else:
  3748. # self.save_defaults()
  3749. # log.debug("Application defaults saved ... Exit event.")
  3750. # QtWidgets.qApp.quit()
  3751. def save_defaults(self, silent=False, data_path=None, first_time=False):
  3752. """
  3753. Saves application default options
  3754. ``self.defaults`` to current_defaults.FlatConfig file.
  3755. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  3756. used at the next launch of the application.
  3757. :param silent: whether to display a message in status bar or not; boolean
  3758. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  3759. When the application is portable it should be a mobile location.
  3760. :return: None
  3761. """
  3762. self.report_usage("save_defaults")
  3763. if data_path is None:
  3764. data_path = self.data_path
  3765. # Read options from file
  3766. try:
  3767. f = open(data_path + "/current_defaults.FlatConfig")
  3768. defaults_file_content = f.read()
  3769. f.close()
  3770. except:
  3771. e = sys.exc_info()[0]
  3772. App.log.error("Could not load defaults file.")
  3773. App.log.error(str(e))
  3774. self.inform.emit('[ERROR_NOTCL] %s' %
  3775. _("Could not load defaults file."))
  3776. return
  3777. try:
  3778. defaults = json.loads(defaults_file_content)
  3779. except:
  3780. e = sys.exc_info()[0]
  3781. App.log.error("Failed to parse defaults file.")
  3782. App.log.error(str(e))
  3783. self.inform.emit('[ERROR_NOTCL] %s' %
  3784. _("Failed to parse defaults file."))
  3785. return
  3786. # Update options
  3787. self.defaults_read_form()
  3788. defaults.update(self.defaults)
  3789. self.propagate_defaults(silent=True)
  3790. # Save the toolbar view
  3791. tb_status = 0
  3792. if self.ui.toolbarfile.isVisible():
  3793. tb_status += 1
  3794. if self.ui.toolbargeo.isVisible():
  3795. tb_status += 2
  3796. if self.ui.toolbarview.isVisible():
  3797. tb_status += 4
  3798. if self.ui.toolbartools.isVisible():
  3799. tb_status += 8
  3800. if self.ui.exc_edit_toolbar.isVisible():
  3801. tb_status += 16
  3802. if self.ui.geo_edit_toolbar.isVisible():
  3803. tb_status += 32
  3804. if self.ui.grb_edit_toolbar.isVisible():
  3805. tb_status += 64
  3806. if self.ui.snap_toolbar.isVisible():
  3807. tb_status += 128
  3808. if self.ui.toolbarshell.isVisible():
  3809. tb_status += 256
  3810. if first_time is False:
  3811. self.defaults["global_toolbar_view"] = tb_status
  3812. # Save update options
  3813. try:
  3814. f = open(data_path + "/current_defaults.FlatConfig", "w")
  3815. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  3816. f.close()
  3817. except:
  3818. self.inform.emit('[ERROR_NOTCL] %s' %
  3819. _("Failed to write defaults to file."))
  3820. return
  3821. if not silent:
  3822. self.inform.emit('[success] %s' %
  3823. _("Preferences saved."))
  3824. def save_factory_defaults(self, silent=False, data_path=None):
  3825. """
  3826. Saves application factory default options
  3827. ``self.defaults`` to factory_defaults.FlatConfig.
  3828. It's a one time job done just after the first install.
  3829. :param silent: whether to display a message in status bar or not; boolean
  3830. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  3831. When the application is portable it should be a mobile location.
  3832. :return: None
  3833. """
  3834. self.report_usage("save_factory_defaults")
  3835. if data_path is None:
  3836. data_path = self.data_path
  3837. # Read options from file
  3838. try:
  3839. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  3840. factory_defaults_file_content = f_f_def.read()
  3841. f_f_def.close()
  3842. except:
  3843. e = sys.exc_info()[0]
  3844. App.log.error("Could not load factory defaults file.")
  3845. App.log.error(str(e))
  3846. self.inform.emit('[ERROR_NOTCL] %s' %
  3847. _("Could not load factory defaults file."))
  3848. return
  3849. try:
  3850. factory_defaults = json.loads(factory_defaults_file_content)
  3851. except:
  3852. e = sys.exc_info()[0]
  3853. App.log.error("Failed to parse factory defaults file.")
  3854. App.log.error(str(e))
  3855. self.inform.emit('[ERROR_NOTCL] %s' %
  3856. _("Failed to parse factory defaults file."))
  3857. return
  3858. # Update options
  3859. self.defaults_read_form()
  3860. factory_defaults.update(self.defaults)
  3861. self.propagate_defaults(silent=True)
  3862. # Save update options
  3863. try:
  3864. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  3865. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3866. f_f_def_s.close()
  3867. except:
  3868. self.inform.emit('[ERROR_NOTCL] %s' %
  3869. _("Failed to write factory defaults to file."))
  3870. return
  3871. if silent is False:
  3872. self.inform.emit(_("Factory defaults saved."))
  3873. def final_save(self):
  3874. """
  3875. Callback for doing a preferences save to file whenever the application is about to quit.
  3876. If the project has changes, it will ask the user to save the project.
  3877. :return: None
  3878. """
  3879. if self.save_in_progress:
  3880. self.inform.emit('[WARNING_NOTCL] %s' %
  3881. _("Application is saving the project. Please wait ..."))
  3882. return
  3883. if self.should_we_save and self.collection.get_list():
  3884. msgbox = QtWidgets.QMessageBox()
  3885. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  3886. "\n"
  3887. "Do you want to Save the project?"))
  3888. msgbox.setWindowTitle(_("Save changes"))
  3889. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3890. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  3891. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  3892. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3893. msgbox.setDefaultButton(bt_yes)
  3894. msgbox.exec_()
  3895. response = msgbox.clickedButton()
  3896. if response == bt_yes:
  3897. try:
  3898. self.trayIcon.hide()
  3899. except:
  3900. pass
  3901. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  3902. elif response == bt_no:
  3903. try:
  3904. self.trayIcon.hide()
  3905. except:
  3906. pass
  3907. self.quit_application()
  3908. elif response == bt_cancel:
  3909. return
  3910. else:
  3911. try:
  3912. self.trayIcon.hide()
  3913. except:
  3914. pass
  3915. self.quit_application()
  3916. def quit_application(self):
  3917. """
  3918. Called (as a pyslot or not) when the application is quit.
  3919. :return: None
  3920. """
  3921. self.save_defaults()
  3922. log.debug("App.final_save() --> App Defaults saved.")
  3923. if self.cmd_line_headless != 1:
  3924. # save app state to file
  3925. settings = QSettings("Open Source", "FlatCAM")
  3926. settings.setValue('saved_gui_state', self.ui.saveState())
  3927. settings.setValue('maximized_gui', self.ui.isMaximized())
  3928. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  3929. settings.setValue(
  3930. 'notebook_font_size',
  3931. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  3932. )
  3933. settings.setValue('axis_font_size',
  3934. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value())
  3935. settings.setValue(
  3936. 'textbox_font_size',
  3937. self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  3938. )
  3939. settings.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  3940. # This will write the setting to the platform specific storage.
  3941. del settings
  3942. log.debug("App.final_save() --> App UI state saved.")
  3943. QtWidgets.qApp.quit()
  3944. def on_portable_checked(self, state):
  3945. """
  3946. Callback called when the checkbox in Preferences GUI is checked.
  3947. It will set the application as portable by creating the preferences and recent files in the
  3948. 'config' folder found in the FlatCAM installation folder.
  3949. :param state: boolean, the state of the checkbox when clicked/checked
  3950. :return:
  3951. """
  3952. line_no = 0
  3953. data = None
  3954. if sys.platform != 'win32':
  3955. # this won't work in Linux or MacOS
  3956. return
  3957. # test if the app was frozen and choose the path for the configuration file
  3958. if getattr(sys, "frozen", False) is True:
  3959. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  3960. else:
  3961. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  3962. config_file = current_data_path + '\\configuration.txt'
  3963. try:
  3964. with open(config_file, 'r') as f:
  3965. try:
  3966. data = f.readlines()
  3967. except Exception as e:
  3968. log.debug('App.__init__() -->%s' % str(e))
  3969. return
  3970. except FileNotFoundError:
  3971. pass
  3972. for line in data:
  3973. line = line.strip('\n')
  3974. param = str(line).rpartition('=')
  3975. if param[0] == 'portable':
  3976. break
  3977. line_no += 1
  3978. if state:
  3979. data[line_no] = 'portable=True\n'
  3980. # create the new defauults files
  3981. # create current_defaults.FlatConfig file if there is none
  3982. try:
  3983. f = open(current_data_path + '/current_defaults.FlatConfig')
  3984. f.close()
  3985. except IOError:
  3986. App.log.debug('Creating empty current_defaults.FlatConfig')
  3987. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3988. json.dump({}, f)
  3989. f.close()
  3990. # create factory_defaults.FlatConfig file if there is none
  3991. try:
  3992. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3993. f.close()
  3994. except IOError:
  3995. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3996. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3997. json.dump({}, f)
  3998. f.close()
  3999. try:
  4000. f = open(current_data_path + '/recent.json')
  4001. f.close()
  4002. except IOError:
  4003. App.log.debug('Creating empty recent.json')
  4004. f = open(current_data_path + '/recent.json', 'w')
  4005. json.dump([], f)
  4006. f.close()
  4007. try:
  4008. fp = open(current_data_path + '/recent_projects.json')
  4009. fp.close()
  4010. except IOError:
  4011. App.log.debug('Creating empty recent_projects.json')
  4012. fp = open(current_data_path + '/recent_projects.json', 'w')
  4013. json.dump([], fp)
  4014. fp.close()
  4015. # save the current defaults to the new defaults file
  4016. self.save_defaults(silent=True, data_path=current_data_path)
  4017. self.save_factory_defaults(silent=True, data_path=current_data_path)
  4018. else:
  4019. data[line_no] = 'portable=False\n'
  4020. with open(config_file, 'w') as f:
  4021. f.writelines(data)
  4022. def on_toggle_shell(self):
  4023. """
  4024. Toggle shell: if is visible close it, if it is closed then open it
  4025. :return:
  4026. """
  4027. self.report_usage("on_toggle_shell()")
  4028. if self.ui.shell_dock.isVisible():
  4029. self.ui.shell_dock.hide()
  4030. else:
  4031. self.ui.shell_dock.show()
  4032. def on_register_files(self, obj_type=None):
  4033. """
  4034. Called whenever there is a need to register file extensions with FlatCAM.
  4035. Works only in Windows and should be called only when FlatCAM is run in Windows.
  4036. :param obj_type: the type of object to be register for.
  4037. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  4038. :return: None
  4039. """
  4040. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  4041. new_reg_path = 'Software\\Classes\\'
  4042. # find if the current user is admin
  4043. try:
  4044. is_admin = os.getuid() == 0
  4045. except AttributeError:
  4046. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  4047. if is_admin is True:
  4048. root_path = winreg.HKEY_LOCAL_MACHINE
  4049. else:
  4050. root_path = winreg.HKEY_CURRENT_USER
  4051. # create the keys
  4052. def set_reg(name, root_path, new_reg_path, value):
  4053. try:
  4054. winreg.CreateKey(root_path, new_reg_path)
  4055. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  4056. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  4057. return True
  4058. except WindowsError:
  4059. return False
  4060. # delete key in registry
  4061. def delete_reg(root_path, reg_path, key_to_del):
  4062. key_to_del_path = reg_path + key_to_del
  4063. try:
  4064. winreg.DeleteKey(root_path, key_to_del_path)
  4065. return True
  4066. except WindowsError:
  4067. return False
  4068. if obj_type is None or obj_type == 'excellon':
  4069. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4070. exc_list = [x for x in exc_list if x != '']
  4071. # register all keys in the Preferences window
  4072. for ext in exc_list:
  4073. new_k = new_reg_path + '.%s' % ext
  4074. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4075. # and unregister those that are no longer in the Preferences windows but are in the file
  4076. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  4077. if ext not in exc_list:
  4078. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4079. # now write the updated extensions to the self.defaults
  4080. # new_ext = ''
  4081. # for ext in exc_list:
  4082. # new_ext = new_ext + ext + ', '
  4083. # self.defaults["fa_excellon"] = new_ext
  4084. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  4085. if obj_type is None or obj_type == 'gcode':
  4086. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4087. gco_list = [x for x in gco_list if x != '']
  4088. # register all keys in the Preferences window
  4089. for ext in gco_list:
  4090. new_k = new_reg_path + '.%s' % ext
  4091. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4092. # and unregister those that are no longer in the Preferences windows but are in the file
  4093. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  4094. if ext not in gco_list:
  4095. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4096. # now write the updated extensions to the self.defaults
  4097. # new_ext = ''
  4098. # for ext in gco_list:
  4099. # new_ext = new_ext + ext + ', '
  4100. # self.defaults["fa_gcode"] = new_ext
  4101. self.inform.emit('[success] %s' %
  4102. _("Selected GCode file extensions registered with FlatCAM."))
  4103. if obj_type is None or obj_type == 'gerber':
  4104. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4105. grb_list = [x for x in grb_list if x != '']
  4106. # register all keys in the Preferences window
  4107. for ext in grb_list:
  4108. new_k = new_reg_path + '.%s' % ext
  4109. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4110. # and unregister those that are no longer in the Preferences windows but are in the file
  4111. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  4112. if ext not in grb_list:
  4113. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4114. # now write the updated extensions to the self.defaults
  4115. # new_ext = ''
  4116. # for ext in grb_list:
  4117. # new_ext = new_ext + ext + ', '
  4118. # self.defaults["fa_gerber"] = new_ext
  4119. self.inform.emit('[success] %s' %
  4120. _("Selected Gerber file extensions registered with FlatCAM."))
  4121. def add_extension(self, ext_type):
  4122. if ext_type == 'excellon':
  4123. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4124. if new_ext == '':
  4125. return
  4126. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4127. if new_ext in old_val:
  4128. return
  4129. old_val.append(new_ext)
  4130. old_val.sort()
  4131. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4132. if ext_type == 'gcode':
  4133. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4134. if new_ext == '':
  4135. return
  4136. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4137. if new_ext in old_val:
  4138. return
  4139. old_val.append(new_ext)
  4140. old_val.sort()
  4141. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4142. if ext_type == 'gerber':
  4143. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4144. if new_ext == '':
  4145. return
  4146. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4147. if new_ext in old_val:
  4148. return
  4149. old_val.append(new_ext)
  4150. old_val.sort()
  4151. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4152. if ext_type == 'keyword':
  4153. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4154. if new_kw == '':
  4155. return
  4156. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4157. if new_kw in old_val:
  4158. return
  4159. old_val.append(new_kw)
  4160. old_val.sort()
  4161. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4162. # update the self.myKeywords so the model is updated
  4163. self.autocomplete_kw_list = \
  4164. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4165. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4166. self.shell._edit.set_model_data(self.myKeywords)
  4167. self.ui.code_editor.set_model_data(self.myKeywords)
  4168. def del_extension(self, ext_type):
  4169. if ext_type == 'excellon':
  4170. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4171. if new_ext == '':
  4172. return
  4173. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4174. if new_ext not in old_val:
  4175. return
  4176. old_val.remove(new_ext)
  4177. old_val.sort()
  4178. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4179. if ext_type == 'gcode':
  4180. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4181. if new_ext == '':
  4182. return
  4183. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4184. if new_ext not in old_val:
  4185. return
  4186. old_val.remove(new_ext)
  4187. old_val.sort()
  4188. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4189. if ext_type == 'gerber':
  4190. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4191. if new_ext == '':
  4192. return
  4193. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4194. if new_ext not in old_val:
  4195. return
  4196. old_val.remove(new_ext)
  4197. old_val.sort()
  4198. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4199. if ext_type == 'keyword':
  4200. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4201. if new_kw == '':
  4202. return
  4203. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4204. if new_kw not in old_val:
  4205. return
  4206. old_val.remove(new_kw)
  4207. old_val.sort()
  4208. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4209. # update the self.myKeywords so the model is updated
  4210. self.autocomplete_kw_list = \
  4211. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4212. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4213. self.shell._edit.set_model_data(self.myKeywords)
  4214. self.ui.code_editor.set_model_data(self.myKeywords)
  4215. def restore_extensions(self, ext_type):
  4216. if ext_type == 'excellon':
  4217. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  4218. # for the ability to open Excellon files with .txt extension
  4219. new_exc_list = deepcopy(self.exc_list)
  4220. try:
  4221. new_exc_list.remove('txt')
  4222. except ValueError:
  4223. pass
  4224. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  4225. if ext_type == 'gcode':
  4226. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  4227. if ext_type == 'gerber':
  4228. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  4229. if ext_type == 'keyword':
  4230. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  4231. # update the self.myKeywords so the model is updated
  4232. self.autocomplete_kw_list = self.default_keywords
  4233. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4234. self.shell._edit.set_model_data(self.myKeywords)
  4235. self.ui.code_editor.set_model_data(self.myKeywords)
  4236. def delete_all_extensions(self, ext_type):
  4237. if ext_type == 'excellon':
  4238. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4239. if ext_type == 'gcode':
  4240. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4241. if ext_type == 'gerber':
  4242. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4243. if ext_type == 'keyword':
  4244. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4245. # update the self.myKeywords so the model is updated
  4246. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4247. self.shell._edit.set_model_data(self.myKeywords)
  4248. self.ui.code_editor.set_model_data(self.myKeywords)
  4249. def on_edit_join(self, name=None):
  4250. """
  4251. Callback for Edit->Join. Joins the selected geometry objects into
  4252. a new one.
  4253. :return: None
  4254. """
  4255. self.report_usage("on_edit_join()")
  4256. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4257. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4258. tooldias = []
  4259. geo_type_list = set()
  4260. objs = self.collection.get_selected()
  4261. if len(objs) < 2:
  4262. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4263. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4264. return 'fail'
  4265. for obj in objs:
  4266. geo_type_list.add(obj.multigeo)
  4267. # if len(geo_type_list) == 1 means that all list elements are the same
  4268. if len(geo_type_list) != 1:
  4269. self.inform.emit('[ERROR] %s' %
  4270. _("Failed join. The Geometry objects are of different types.\n"
  4271. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4272. "convert from one to another and retry joining \n"
  4273. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4274. "the result may not be what was expected. \n"
  4275. "Check the generated GCODE."))
  4276. return
  4277. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4278. if True in geo_type_list:
  4279. def initialize(obj, app):
  4280. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=True)
  4281. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4282. for v in obj.tools.values():
  4283. v['data']['name'] = obj_name_multi
  4284. self.new_object("geometry", obj_name_multi, initialize)
  4285. else:
  4286. def initialize(obj, app):
  4287. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=False)
  4288. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4289. for v in obj.tools.values():
  4290. v['data']['name'] = obj_name_single
  4291. self.new_object("geometry", obj_name_single, initialize)
  4292. self.should_we_save = True
  4293. def on_edit_join_exc(self):
  4294. """
  4295. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4296. a new Excellon.
  4297. :return: None
  4298. """
  4299. self.report_usage("on_edit_join_exc()")
  4300. objs = self.collection.get_selected()
  4301. for obj in objs:
  4302. if not isinstance(obj, FlatCAMExcellon):
  4303. self.inform.emit('[ERROR_NOTCL] %s' %
  4304. _("Failed. Excellon joining works only on Excellon objects."))
  4305. return
  4306. if len(objs) < 2:
  4307. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4308. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4309. return 'fail'
  4310. def initialize(obj, app):
  4311. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=obj)
  4312. self.new_object("excellon", 'Combo_Excellon', initialize)
  4313. self.should_we_save = True
  4314. def on_edit_join_grb(self):
  4315. """
  4316. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4317. a new Gerber object.
  4318. :return: None
  4319. """
  4320. self.report_usage("on_edit_join_grb()")
  4321. objs = self.collection.get_selected()
  4322. for obj in objs:
  4323. if not isinstance(obj, FlatCAMGerber):
  4324. self.inform.emit('[ERROR_NOTCL] %s' %
  4325. _("Failed. Gerber joining works only on Gerber objects."))
  4326. return
  4327. if len(objs) < 2:
  4328. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4329. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4330. return 'fail'
  4331. def initialize(obj, app):
  4332. FlatCAMGerber.merge(self, grb_list=objs, grb_final=obj)
  4333. self.new_object("gerber", 'Combo_Gerber', initialize)
  4334. self.should_we_save = True
  4335. def on_convert_singlegeo_to_multigeo(self):
  4336. """
  4337. Called for converting a Geometry object from single-geo to multi-geo.
  4338. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4339. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4340. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4341. the solid-geometry of that tool.
  4342. :return: None
  4343. """
  4344. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4345. obj = self.collection.get_active()
  4346. if obj is None:
  4347. self.inform.emit('[ERROR_NOTCL] %s' %
  4348. _("Failed. Select a Geometry Object and try again."))
  4349. return
  4350. if not isinstance(obj, FlatCAMGeometry):
  4351. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4352. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4353. return
  4354. obj.multigeo = True
  4355. for tooluid, dict_value in obj.tools.items():
  4356. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4357. if not isinstance(obj.solid_geometry, list):
  4358. obj.solid_geometry = [obj.solid_geometry]
  4359. obj.solid_geometry[:] = []
  4360. obj.plot()
  4361. self.should_we_save = True
  4362. self.inform.emit('[success] %s' %
  4363. _("A Geometry object was converted to MultiGeo type."))
  4364. def on_convert_multigeo_to_singlegeo(self):
  4365. """
  4366. Called for converting a Geometry object from multi-geo to single-geo.
  4367. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4368. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4369. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4370. the solid-geometry of that tool.
  4371. :return: None
  4372. """
  4373. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4374. obj = self.collection.get_active()
  4375. if obj is None:
  4376. self.inform.emit('[ERROR_NOTCL] %s' %
  4377. _("Failed. Select a Geometry Object and try again."))
  4378. return
  4379. if not isinstance(obj, FlatCAMGeometry):
  4380. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4381. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4382. return
  4383. obj.multigeo = False
  4384. total_solid_geometry = []
  4385. for tooluid, dict_value in obj.tools.items():
  4386. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4387. # clear the original geometry
  4388. dict_value['solid_geometry'][:] = []
  4389. obj.solid_geometry = deepcopy(total_solid_geometry)
  4390. obj.plot()
  4391. self.should_we_save = True
  4392. self.inform.emit('[success] %s' %
  4393. _("A Geometry object was converted to SingleGeo type."))
  4394. def on_options_dict_change(self, field):
  4395. """
  4396. Called whenever a key changed in the self.options dictionary. This dict was used to store the preferences of the
  4397. current project. This feature is no longer used.
  4398. :param field:
  4399. :return:
  4400. """
  4401. self.options_write_form_field(field)
  4402. if field == "units":
  4403. self.set_screen_units(self.options['units'])
  4404. def on_defaults_dict_change(self, field):
  4405. """
  4406. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4407. Edit -> Preferences tab window.
  4408. :param field: the key of the self.defaults dictionary that was changed.
  4409. :return: None
  4410. """
  4411. self.defaults_write_form_field(field)
  4412. if field == "units":
  4413. self.set_screen_units(self.defaults['units'])
  4414. def set_screen_units(self, units):
  4415. """
  4416. Set the FlatCAM units on the status bar.
  4417. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4418. :return: None
  4419. """
  4420. self.ui.units_label.setText("[" + units.lower() + "]")
  4421. def on_toggle_units(self, no_pref=False):
  4422. """
  4423. Callback for the Units radio-button change in the Preferences tab.
  4424. Changes the application's default units adn for the project too.
  4425. If changing the project's units, the change propagates to all of
  4426. the objects in the project.
  4427. :return: None
  4428. """
  4429. self.report_usage("on_toggle_units")
  4430. if self.toggle_units_ignore:
  4431. return
  4432. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4433. # If option is the same, then ignore
  4434. if new_units == self.defaults["units"].upper():
  4435. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4436. return
  4437. # Options to scale
  4438. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  4439. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  4440. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4441. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  4442. "excellon_z_pdepth",
  4443. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4444. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4445. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  4446. "geometry_feedrate_probe",
  4447. 'cncjob_tooldia',
  4448. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4449. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia"
  4450. "tools_2sided_drilldia", "tools_film_boundary",
  4451. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4452. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4453. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4454. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4455. "tools_transform_offset_y",
  4456. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4457. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4458. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4459. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4460. 'global_gridx', 'global_gridy', 'global_snap_max']
  4461. def scale_options(sfactor):
  4462. for dim in dimensions:
  4463. if dim == 'excellon_toolchangexy':
  4464. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4465. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4466. coords_xy[0] *= sfactor
  4467. coords_xy[1] *= sfactor
  4468. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4469. elif dim == 'geometry_toolchangexy':
  4470. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4471. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4472. coords_xy[0] *= sfactor
  4473. coords_xy[1] *= sfactor
  4474. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4475. elif dim == 'geometry_cnctooldia':
  4476. tools_diameters = []
  4477. try:
  4478. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4479. tools_diameters = [eval(a) for a in tools_string if a != '']
  4480. except Exception as e:
  4481. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4482. self.options['geometry_cnctooldia'] = ''
  4483. for t in range(len(tools_diameters)):
  4484. tools_diameters[t] *= sfactor
  4485. self.options['geometry_cnctooldia'] += "%f," % tools_diameters[t]
  4486. elif dim == 'tools_ncctools':
  4487. ncctools = []
  4488. try:
  4489. tools_string = self.defaults["tools_ncctools"].split(",")
  4490. ncctools = [eval(a) for a in tools_string if a != '']
  4491. except Exception as e:
  4492. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4493. self.options['tools_ncctools'] = ''
  4494. for t in range(len(ncctools)):
  4495. ncctools[t] *= sfactor
  4496. self.options['tools_ncctools'] += "%f," % ncctools[t]
  4497. elif dim == 'tools_solderpaste_tools':
  4498. sptools = []
  4499. try:
  4500. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4501. sptools = [eval(a) for a in tools_string if a != '']
  4502. except Exception as e:
  4503. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4504. self.options['tools_solderpaste_tools'] = ""
  4505. for t in range(len(sptools)):
  4506. sptools[t] *= sfactor
  4507. self.options['tools_solderpaste_tools'] += "%f," % sptools[t]
  4508. elif dim == 'tools_solderpaste_xy_toolchange':
  4509. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4510. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4511. sp_coords[0] *= sfactor
  4512. sp_coords[1] *= sfactor
  4513. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  4514. elif dim == 'global_gridx' or dim == 'global_gridy':
  4515. if new_units == 'IN':
  4516. val = 0.1
  4517. try:
  4518. val = float(self.defaults[dim]) * sfactor
  4519. except Exception as e:
  4520. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4521. self.options[dim] = float('%.6f' % val)
  4522. else:
  4523. val = 0.1
  4524. try:
  4525. val = float(self.defaults[dim]) * sfactor
  4526. except Exception as e:
  4527. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4528. self.options[dim] = float('%.4f' % val)
  4529. else:
  4530. val = 0.1
  4531. try:
  4532. val = float(self.options[dim]) * sfactor
  4533. except Exception as e:
  4534. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  4535. self.options[dim] = val
  4536. def scale_defaults(sfactor):
  4537. for dim in dimensions:
  4538. if dim == 'excellon_toolchangexy':
  4539. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4540. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4541. coords_xy[0] *= sfactor
  4542. coords_xy[1] *= sfactor
  4543. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4544. elif dim == 'geometry_toolchangexy':
  4545. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4546. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4547. coords_xy[0] *= sfactor
  4548. coords_xy[1] *= sfactor
  4549. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4550. elif dim == 'geometry_cnctooldia':
  4551. tools_diameters = []
  4552. try:
  4553. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4554. tools_diameters = [eval(a) for a in tools_string if a != '']
  4555. except Exception as e:
  4556. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4557. self.defaults['geometry_cnctooldia'] = ''
  4558. for t in range(len(tools_diameters)):
  4559. tools_diameters[t] *= sfactor
  4560. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  4561. elif dim == 'tools_ncctools':
  4562. ncctools = []
  4563. try:
  4564. tools_string = self.defaults["tools_ncctools"].split(",")
  4565. ncctools = [eval(a) for a in tools_string if a != '']
  4566. except Exception as e:
  4567. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4568. self.defaults['tools_ncctools'] = ''
  4569. for t in range(len(ncctools)):
  4570. ncctools[t] *= sfactor
  4571. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  4572. elif dim == 'tools_solderpaste_tools':
  4573. sptools = []
  4574. try:
  4575. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4576. sptools = [eval(a) for a in tools_string if a != '']
  4577. except Exception as e:
  4578. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4579. self.defaults['tools_solderpaste_tools'] = ""
  4580. for t in range(len(sptools)):
  4581. sptools[t] *= sfactor
  4582. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  4583. elif dim == 'tools_solderpaste_xy_toolchange':
  4584. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4585. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4586. sp_coords[0] *= sfactor
  4587. sp_coords[1] *= sfactor
  4588. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  4589. elif dim == 'global_gridx' or dim == 'global_gridy':
  4590. if new_units == 'IN':
  4591. val = 0.1
  4592. try:
  4593. val = float(self.defaults[dim]) * sfactor
  4594. except Exception as e:
  4595. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4596. self.defaults[dim] = float('%.6f' % val)
  4597. else:
  4598. val = 0.1
  4599. try:
  4600. val = float(self.defaults[dim]) * sfactor
  4601. except Exception as e:
  4602. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4603. self.defaults[dim] = float('%.4f' % val)
  4604. else:
  4605. val = 0.1
  4606. try:
  4607. val = float(self.defaults[dim]) * sfactor
  4608. except Exception as e:
  4609. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4610. self.defaults[dim] = val
  4611. # The scaling factor depending on choice of units.
  4612. factor = 1/25.4
  4613. if new_units == 'MM':
  4614. factor = 25.4
  4615. # Changing project units. Warn user.
  4616. msgbox = QtWidgets.QMessageBox()
  4617. msgbox.setWindowTitle(_("Toggle Units"))
  4618. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  4619. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4620. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  4621. "properties of all objects to be scaled accordingly.\nContinue?"))
  4622. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4623. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4624. msgbox.setDefaultButton(bt_ok)
  4625. msgbox.exec_()
  4626. response = msgbox.clickedButton()
  4627. if response == bt_ok:
  4628. if no_pref is False:
  4629. self.options_read_form()
  4630. scale_options(factor)
  4631. self.options_write_form()
  4632. self.defaults_read_form()
  4633. scale_defaults(factor)
  4634. self.defaults_write_form(fl_units=new_units)
  4635. # save the defaults to file, some may assume that the conversion is enough and it's not
  4636. self.on_save_button()
  4637. self.should_we_save = True
  4638. # change this only if the workspace is active
  4639. if self.defaults['global_workspace'] is True:
  4640. self.plotcanvas.draw_workspace()
  4641. # adjust the grid values on the main toolbar
  4642. dec = 6 if new_units == 'IN'else 4
  4643. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  4644. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  4645. if not self.ui.grid_gap_link_cb.isChecked():
  4646. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  4647. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  4648. for obj in self.collection.get_list():
  4649. obj.convert_units(new_units)
  4650. # make that the properties stored in the object are also updated
  4651. self.object_changed.emit(obj)
  4652. obj.build_ui()
  4653. current = self.collection.get_active()
  4654. if current is not None:
  4655. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4656. if not isinstance(current, FlatCAMGeometry):
  4657. current.to_form()
  4658. self.plot_all()
  4659. self.inform.emit('[success] %s: %s' %
  4660. (_("Converted units to"), new_units))
  4661. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4662. self.set_screen_units(new_units)
  4663. else:
  4664. # Undo toggling
  4665. self.toggle_units_ignore = True
  4666. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4667. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4668. else:
  4669. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4670. self.toggle_units_ignore = False
  4671. self.inform.emit('[WARNING_NOTCL]%s' %
  4672. _(" Units conversion cancelled."))
  4673. self.options_read_form()
  4674. self.defaults_read_form()
  4675. def on_toggle_units_click(self):
  4676. try:
  4677. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4678. except (TypeError, AttributeError):
  4679. pass
  4680. if self.defaults["units"] == 'MM':
  4681. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4682. else:
  4683. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4684. self.on_toggle_units(no_pref=True)
  4685. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4686. lambda: self.on_toggle_units(no_pref=False))
  4687. def on_fullscreen(self):
  4688. self.report_usage("on_fullscreen()")
  4689. if self.toggle_fscreen is False:
  4690. # self.ui.showFullScreen()
  4691. self.ui.setWindowFlags(self.ui.windowFlags() | Qt.FramelessWindowHint)
  4692. a = self.ui.geometry()
  4693. self.x_pos = a.x()
  4694. self.y_pos = a.y()
  4695. self.width = a.width()
  4696. self.height = a.height()
  4697. # set new geometry to full desktop rect
  4698. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  4699. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  4700. # everything else will not work without this hack. This happen in Windows.
  4701. # https://bugreports.qt.io/browse/QTBUG-41309
  4702. desktop = QtWidgets.QApplication.desktop()
  4703. screen = desktop.screenNumber(QtGui.QCursor.pos())
  4704. rec = desktop.screenGeometry(screen)
  4705. x = rec.x() - 1
  4706. y = rec.y() - 1
  4707. h = rec.height() + 2
  4708. w = rec.width() + 2
  4709. self.ui.setGeometry(x, y, w, h)
  4710. self.ui.show()
  4711. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4712. tb.setVisible(False)
  4713. self.ui.splitter_left.setVisible(False)
  4714. self.toggle_fscreen = True
  4715. else:
  4716. self.ui.setWindowFlags(self.ui.windowFlags() & ~Qt.FramelessWindowHint)
  4717. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  4718. self.ui.showNormal()
  4719. self.restore_toolbar_view()
  4720. self.ui.splitter_left.setVisible(True)
  4721. self.toggle_fscreen = False
  4722. def on_toggle_plotarea(self):
  4723. self.report_usage("on_toggle_plotarea()")
  4724. try:
  4725. name = self.ui.plot_tab_area.widget(0).objectName()
  4726. except AttributeError:
  4727. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4728. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4729. self.ui.plot_tab_area.protectTab(0)
  4730. return
  4731. if name != 'plotarea':
  4732. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4733. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4734. self.ui.plot_tab_area.protectTab(0)
  4735. else:
  4736. self.ui.plot_tab_area.closeTab(0)
  4737. def on_toggle_notebook(self):
  4738. if self.ui.splitter.sizes()[0] == 0:
  4739. self.ui.splitter.setSizes([1, 1])
  4740. else:
  4741. self.ui.splitter.setSizes([0, 1])
  4742. def on_toggle_axis(self):
  4743. self.report_usage("on_toggle_axis()")
  4744. if self.toggle_axis is False:
  4745. if self.is_legacy is False:
  4746. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4747. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4748. self.plotcanvas.redraw()
  4749. else:
  4750. self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  4751. self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  4752. self.plotcanvas.canvas.draw()
  4753. pass
  4754. self.toggle_axis = True
  4755. else:
  4756. if self.is_legacy is False:
  4757. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4758. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4759. self.plotcanvas.redraw()
  4760. else:
  4761. self.plotcanvas.axes.lines[:] = []
  4762. self.plotcanvas.canvas.draw()
  4763. self.toggle_axis = False
  4764. def on_toggle_grid(self):
  4765. self.report_usage("on_toggle_grid()")
  4766. self.ui.grid_snap_btn.trigger()
  4767. def on_options_combo_change(self, sel):
  4768. """
  4769. Called when the combo box to choose between application defaults and
  4770. project option changes value. The corresponding variables are
  4771. copied to the UI.
  4772. :param sel: The option index that was chosen.
  4773. :return: None
  4774. """
  4775. # combo_sel = self.ui.notebook.combo_options.get_active()
  4776. App.log.debug("Options --> %s" % sel)
  4777. # form = [self.defaults_form, self.options_form][sel]
  4778. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  4779. if sel == 0:
  4780. self.gen_form = self.ui.general_defaults_form
  4781. self.ger_form = self.ui.gerber_defaults_form
  4782. self.exc_form = self.ui.excellon_defaults_form
  4783. self.geo_form = self.ui.geometry_defaults_form
  4784. self.cnc_form = self.ui.cncjob_defaults_form
  4785. self.tools_form = self.ui.tools_defaults_form
  4786. self.fa_form = self.ui.util_defaults_form
  4787. elif sel == 1:
  4788. self.gen_form = self.ui.general_options_form
  4789. self.ger_form = self.ui.gerber_options_form
  4790. self.exc_form = self.ui.excellon_options_form
  4791. self.geo_form = self.ui.geometry_options_form
  4792. self.cnc_form = self.ui.cncjob_options_form
  4793. self.tools_form = self.ui.tools_options_form
  4794. self.fa_form = self.ui.util_options_form
  4795. else:
  4796. return
  4797. try:
  4798. self.ui.general_scroll_area.takeWidget()
  4799. except:
  4800. self.log.debug("Nothing to remove")
  4801. self.ui.general_scroll_area.setWidget(self.gen_form)
  4802. self.gen_form.show()
  4803. try:
  4804. self.ui.gerber_scroll_area.takeWidget()
  4805. except:
  4806. self.log.debug("Nothing to remove")
  4807. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  4808. self.ger_form.show()
  4809. try:
  4810. self.ui.excellon_scroll_area.takeWidget()
  4811. except:
  4812. self.log.debug("Nothing to remove")
  4813. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  4814. self.exc_form.show()
  4815. try:
  4816. self.ui.geometry_scroll_area.takeWidget()
  4817. except:
  4818. self.log.debug("Nothing to remove")
  4819. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  4820. self.geo_form.show()
  4821. try:
  4822. self.ui.cncjob_scroll_area.takeWidget()
  4823. except:
  4824. self.log.debug("Nothing to remove")
  4825. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  4826. self.cnc_form.show()
  4827. try:
  4828. self.ui.tools_scroll_area.takeWidget()
  4829. except:
  4830. self.log.debug("Nothing to remove")
  4831. self.ui.tools_scroll_area.setWidget(self.tools_form)
  4832. self.tools_form.show()
  4833. try:
  4834. self.ui.fa_scroll_area.takeWidget()
  4835. except:
  4836. self.log.debug("Nothing to remove")
  4837. self.ui.fa_scroll_area.setWidget(self.fa_form)
  4838. self.fa_form.show()
  4839. self.log.debug("Finished GUI form initialization.")
  4840. # self.options2form()
  4841. def on_excellon_defaults_button(self):
  4842. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  4843. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  4844. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  4845. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  4846. self.defaults_form_fields["excellon_zeros"].set_value('L')
  4847. self.defaults_form_fields["excellon_units"].set_value('INCH')
  4848. log.debug("Excellon app defaults loaded ...")
  4849. def on_excellon_options_button(self):
  4850. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  4851. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  4852. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  4853. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  4854. self.options_form_fields["excellon_zeros"].set_value('L')
  4855. self.options_form_fields["excellon_units"].set_value('INCH')
  4856. log.debug("Excellon options defaults loaded ...")
  4857. def on_update_exc_export(self, state):
  4858. """
  4859. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  4860. if the update_excellon_cb checkbox is checked
  4861. :param state: state of the checkbox whose signals is tied to his slot
  4862. :return:
  4863. """
  4864. if state:
  4865. # first try to disconnect
  4866. try:
  4867. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.\
  4868. disconnect(self.on_excellon_format_changed)
  4869. except TypeError:
  4870. pass
  4871. try:
  4872. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged.\
  4873. disconnect(self.on_excellon_format_changed)
  4874. except TypeError:
  4875. pass
  4876. try:
  4877. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged.\
  4878. disconnect(self.on_excellon_format_changed)
  4879. except TypeError:
  4880. pass
  4881. try:
  4882. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged.\
  4883. disconnect(self.on_excellon_format_changed)
  4884. except TypeError:
  4885. pass
  4886. try:
  4887. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  4888. disconnect(self.on_excellon_zeros_changed)
  4889. except TypeError:
  4890. pass
  4891. try:
  4892. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  4893. disconnect(self.on_excellon_zeros_changed)
  4894. except TypeError:
  4895. pass
  4896. # the connect them
  4897. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.connect(
  4898. self.on_excellon_format_changed)
  4899. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged.connect(
  4900. self.on_excellon_format_changed)
  4901. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged.connect(
  4902. self.on_excellon_format_changed)
  4903. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged.connect(
  4904. self.on_excellon_format_changed)
  4905. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  4906. self.on_excellon_zeros_changed)
  4907. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  4908. self.on_excellon_units_changed)
  4909. else:
  4910. # disconnect the signals
  4911. try:
  4912. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged. \
  4913. disconnect(self.on_excellon_format_changed)
  4914. except TypeError:
  4915. pass
  4916. try:
  4917. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged. \
  4918. disconnect(self.on_excellon_format_changed)
  4919. except TypeError:
  4920. pass
  4921. try:
  4922. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged. \
  4923. disconnect(self.on_excellon_format_changed)
  4924. except TypeError:
  4925. pass
  4926. try:
  4927. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged. \
  4928. disconnect(self.on_excellon_format_changed)
  4929. except TypeError:
  4930. pass
  4931. try:
  4932. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  4933. disconnect(self.on_excellon_zeros_changed)
  4934. except TypeError:
  4935. pass
  4936. try:
  4937. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  4938. disconnect(self.on_excellon_zeros_changed)
  4939. except TypeError:
  4940. pass
  4941. def on_excellon_format_changed(self):
  4942. """
  4943. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  4944. :return: None
  4945. """
  4946. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  4947. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4948. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  4949. )
  4950. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4951. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  4952. )
  4953. else:
  4954. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4955. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  4956. )
  4957. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4958. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  4959. )
  4960. def on_excellon_zeros_changed(self):
  4961. """
  4962. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  4963. :return: None
  4964. """
  4965. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  4966. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  4967. )
  4968. def on_excellon_units_changed(self):
  4969. """
  4970. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  4971. :return: None
  4972. """
  4973. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  4974. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  4975. )
  4976. self.on_excellon_format_changed()
  4977. # Setting plot colors handlers
  4978. def on_pf_color_entry(self):
  4979. self.defaults['global_plot_fill'] = \
  4980. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  4981. self.defaults['global_plot_fill'][7:9]
  4982. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4983. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  4984. def on_pf_color_button(self):
  4985. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  4986. c_dialog = QtWidgets.QColorDialog()
  4987. plot_fill_color = c_dialog.getColor(initial=current_color)
  4988. if plot_fill_color.isValid() is False:
  4989. return
  4990. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4991. "background-color:%s" % str(plot_fill_color.name()))
  4992. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  4993. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  4994. self.defaults['global_plot_fill'] = new_val
  4995. def on_pf_color_spinner(self):
  4996. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  4997. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  4998. self.defaults['global_plot_fill'] = \
  4999. self.defaults['global_plot_fill'][:7] + \
  5000. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5001. self.defaults['global_plot_line'] = \
  5002. self.defaults['global_plot_line'][:7] + \
  5003. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5004. def on_pf_color_slider(self):
  5005. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  5006. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  5007. def on_pl_color_entry(self):
  5008. self.defaults['global_plot_line'] = \
  5009. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  5010. self.defaults['global_plot_line'][7:9]
  5011. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5012. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  5013. def on_pl_color_button(self):
  5014. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  5015. # print(current_color)
  5016. c_dialog = QtWidgets.QColorDialog()
  5017. plot_line_color = c_dialog.getColor(initial=current_color)
  5018. if plot_line_color.isValid() is False:
  5019. return
  5020. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5021. "background-color:%s" % str(plot_line_color.name()))
  5022. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  5023. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  5024. self.defaults['global_plot_line'] = new_val_line
  5025. # Setting selection colors (left - right) handlers
  5026. def on_sf_color_entry(self):
  5027. self.defaults['global_sel_fill'] = \
  5028. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  5029. self.defaults['global_sel_fill'][7:9]
  5030. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5031. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  5032. def on_sf_color_button(self):
  5033. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  5034. c_dialog = QtWidgets.QColorDialog()
  5035. plot_fill_color = c_dialog.getColor(initial=current_color)
  5036. if plot_fill_color.isValid() is False:
  5037. return
  5038. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5039. "background-color:%s" % str(plot_fill_color.name()))
  5040. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  5041. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  5042. self.defaults['global_sel_fill'] = new_val
  5043. def on_sf_color_spinner(self):
  5044. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  5045. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  5046. self.defaults['global_sel_fill'] = \
  5047. self.defaults['global_sel_fill'][:7] + \
  5048. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5049. self.defaults['global_sel_line'] = \
  5050. self.defaults['global_sel_line'][:7] + \
  5051. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5052. def on_sf_color_slider(self):
  5053. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  5054. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  5055. def on_sl_color_entry(self):
  5056. self.defaults['global_sel_line'] = \
  5057. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  5058. self.defaults['global_sel_line'][7:9]
  5059. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5060. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  5061. def on_sl_color_button(self):
  5062. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  5063. c_dialog = QtWidgets.QColorDialog()
  5064. plot_line_color = c_dialog.getColor(initial=current_color)
  5065. if plot_line_color.isValid() is False:
  5066. return
  5067. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5068. "background-color:%s" % str(plot_line_color.name()))
  5069. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  5070. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  5071. self.defaults['global_sel_line'] = new_val_line
  5072. # Setting selection colors (right - left) handlers
  5073. def on_alt_sf_color_entry(self):
  5074. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  5075. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  5076. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5077. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  5078. def on_alt_sf_color_button(self):
  5079. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  5080. c_dialog = QtWidgets.QColorDialog()
  5081. plot_fill_color = c_dialog.getColor(initial=current_color)
  5082. if plot_fill_color.isValid() is False:
  5083. return
  5084. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5085. "background-color:%s" % str(plot_fill_color.name()))
  5086. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  5087. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  5088. self.defaults['global_alt_sel_fill'] = new_val
  5089. def on_alt_sf_color_spinner(self):
  5090. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  5091. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  5092. self.defaults['global_alt_sel_fill'] = \
  5093. self.defaults['global_alt_sel_fill'][:7] + \
  5094. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5095. self.defaults['global_alt_sel_line'] = \
  5096. self.defaults['global_alt_sel_line'][:7] + \
  5097. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5098. def on_alt_sf_color_slider(self):
  5099. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  5100. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  5101. def on_alt_sl_color_entry(self):
  5102. self.defaults['global_alt_sel_line'] = \
  5103. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  5104. self.defaults['global_alt_sel_line'][7:9]
  5105. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5106. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  5107. def on_alt_sl_color_button(self):
  5108. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  5109. c_dialog = QtWidgets.QColorDialog()
  5110. plot_line_color = c_dialog.getColor(initial=current_color)
  5111. if plot_line_color.isValid() is False:
  5112. return
  5113. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5114. "background-color:%s" % str(plot_line_color.name()))
  5115. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  5116. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  5117. self.defaults['global_alt_sel_line'] = new_val_line
  5118. # Setting Editor colors
  5119. def on_draw_color_entry(self):
  5120. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5121. .draw_color_entry.get_value()
  5122. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5123. "background-color:%s" % str(self.defaults['global_draw_color']))
  5124. def on_draw_color_button(self):
  5125. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  5126. c_dialog = QtWidgets.QColorDialog()
  5127. draw_color = c_dialog.getColor(initial=current_color)
  5128. if draw_color.isValid() is False:
  5129. return
  5130. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5131. "background-color:%s" % str(draw_color.name()))
  5132. new_val = str(draw_color.name())
  5133. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  5134. self.defaults['global_draw_color'] = new_val
  5135. def on_sel_draw_color_entry(self):
  5136. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5137. .sel_draw_color_entry.get_value()
  5138. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5139. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  5140. def on_sel_draw_color_button(self):
  5141. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  5142. c_dialog = QtWidgets.QColorDialog()
  5143. sel_draw_color = c_dialog.getColor(initial=current_color)
  5144. if sel_draw_color.isValid() is False:
  5145. return
  5146. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5147. "background-color:%s" % str(sel_draw_color.name()))
  5148. new_val_sel = str(sel_draw_color.name())
  5149. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  5150. self.defaults['global_sel_draw_color'] = new_val_sel
  5151. def on_proj_color_entry(self):
  5152. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  5153. .proj_color_entry.get_value()
  5154. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5155. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  5156. def on_proj_color_button(self):
  5157. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  5158. c_dialog = QtWidgets.QColorDialog()
  5159. proj_color = c_dialog.getColor(initial=current_color)
  5160. if proj_color.isValid() is False:
  5161. return
  5162. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5163. "background-color:%s" % str(proj_color.name()))
  5164. new_val_sel = str(proj_color.name())
  5165. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  5166. self.defaults['global_proj_item_color'] = new_val_sel
  5167. def on_proj_color_dis_entry(self):
  5168. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  5169. .proj_color_dis_entry.get_value()
  5170. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5171. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  5172. def on_proj_color_dis_button(self):
  5173. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  5174. c_dialog = QtWidgets.QColorDialog()
  5175. proj_color = c_dialog.getColor(initial=current_color)
  5176. if proj_color.isValid() is False:
  5177. return
  5178. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5179. "background-color:%s" % str(proj_color.name()))
  5180. new_val_sel = str(proj_color.name())
  5181. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  5182. self.defaults['global_proj_item_dis_color'] = new_val_sel
  5183. def on_annotation_fontcolor_entry(self):
  5184. self.defaults['cncjob_annotation_fontcolor'] = \
  5185. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.get_value()
  5186. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5187. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  5188. def on_annotation_fontcolor_button(self):
  5189. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  5190. c_dialog = QtWidgets.QColorDialog()
  5191. annotation_color = c_dialog.getColor(initial=current_color)
  5192. if annotation_color.isValid() is False:
  5193. return
  5194. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5195. "background-color:%s" % str(annotation_color.name()))
  5196. new_val_sel = str(annotation_color.name())
  5197. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(new_val_sel)
  5198. self.defaults['cncjob_annotation_fontcolor'] = new_val_sel
  5199. def on_film_color_entry(self):
  5200. self.defaults['tools_film_color'] = \
  5201. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  5202. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5203. "background-color:%s" % str(self.defaults['tools_film_color']))
  5204. def on_film_color_button(self):
  5205. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  5206. c_dialog = QtWidgets.QColorDialog()
  5207. film_color = c_dialog.getColor(initial=current_color)
  5208. if film_color.isValid() is False:
  5209. return
  5210. # if new color is different then mark that the Preferences are changed
  5211. if film_color != current_color:
  5212. self.on_preferences_edited()
  5213. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5214. "background-color:%s" % str(film_color.name()))
  5215. new_val_sel = str(film_color.name())
  5216. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  5217. self.defaults['tools_film_color'] = new_val_sel
  5218. def on_splash_changed(self, state):
  5219. settings = QSettings("Open Source", "FlatCAM")
  5220. settings.setValue('splash_screen', 1) if state else settings.setValue('splash_screen', 0)
  5221. # This will write the setting to the platform specific storage.
  5222. del settings
  5223. def on_notebook_tab_rmb_click(self, checked):
  5224. self.ui.notebook.set_detachable(val=checked)
  5225. self.defaults["global_tabs_detachable"] = checked
  5226. self.ui.plot_tab_area.set_detachable(val=checked)
  5227. self.defaults["global_tabs_detachable"] = checked
  5228. def on_deselect_all(self):
  5229. self.collection.set_all_inactive()
  5230. self.delete_selection_shape()
  5231. def on_workspace_modified(self):
  5232. self.save_defaults(silent=True)
  5233. self.plotcanvas.draw_workspace()
  5234. def on_workspace(self):
  5235. self.report_usage("on_workspace()")
  5236. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5237. self.plotcanvas.restore_workspace()
  5238. else:
  5239. self.plotcanvas.delete_workspace()
  5240. self.save_defaults(silent=True)
  5241. def on_workspace_menu(self):
  5242. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5243. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  5244. else:
  5245. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  5246. self.on_workspace()
  5247. def on_layout(self, index=None, lay=None):
  5248. self.report_usage("on_layout()")
  5249. if lay:
  5250. current_layout = lay
  5251. else:
  5252. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  5253. settings = QSettings("Open Source", "FlatCAM")
  5254. settings.setValue('layout', current_layout)
  5255. # This will write the setting to the platform specific storage.
  5256. del settings
  5257. # first remove the toolbars:
  5258. try:
  5259. self.ui.removeToolBar(self.ui.toolbarfile)
  5260. self.ui.removeToolBar(self.ui.toolbargeo)
  5261. self.ui.removeToolBar(self.ui.toolbarview)
  5262. self.ui.removeToolBar(self.ui.toolbarshell)
  5263. self.ui.removeToolBar(self.ui.toolbartools)
  5264. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  5265. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  5266. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  5267. self.ui.removeToolBar(self.ui.snap_toolbar)
  5268. self.ui.removeToolBar(self.ui.toolbarshell)
  5269. except Exception as e:
  5270. pass
  5271. if current_layout == 'standard':
  5272. # ## TOOLBAR INSTALLATION # ##
  5273. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5274. self.ui.toolbarfile.setObjectName('File_TB')
  5275. self.ui.addToolBar(self.ui.toolbarfile)
  5276. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5277. self.ui.toolbargeo.setObjectName('Edit_TB')
  5278. self.ui.addToolBar(self.ui.toolbargeo)
  5279. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5280. self.ui.toolbarview.setObjectName('View_TB')
  5281. self.ui.addToolBar(self.ui.toolbarview)
  5282. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5283. self.ui.toolbarshell.setObjectName('Shell_TB')
  5284. self.ui.addToolBar(self.ui.toolbarshell)
  5285. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5286. self.ui.toolbartools.setObjectName('Tools_TB')
  5287. self.ui.addToolBar(self.ui.toolbartools)
  5288. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5289. # self.ui.exc_edit_toolbar.setVisible(False)
  5290. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5291. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  5292. self.ui.addToolBarBreak()
  5293. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5294. # self.ui.geo_edit_toolbar.setVisible(False)
  5295. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5296. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  5297. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5298. # self.ui.grb_edit_toolbar.setVisible(False)
  5299. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5300. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  5301. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5302. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5303. # self.ui.snap_toolbar.setMaximumHeight(30)
  5304. self.ui.addToolBar(self.ui.snap_toolbar)
  5305. self.ui.corner_snap_btn.setVisible(False)
  5306. self.ui.snap_magnet.setVisible(False)
  5307. elif current_layout == 'compact':
  5308. # ## TOOLBAR INSTALLATION # ##
  5309. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5310. self.ui.toolbarfile.setObjectName('File_TB')
  5311. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  5312. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5313. self.ui.toolbargeo.setObjectName('Edit_TB')
  5314. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  5315. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5316. self.ui.toolbarshell.setObjectName('Shell_TB')
  5317. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  5318. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5319. self.ui.toolbartools.setObjectName('Tools_TB')
  5320. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  5321. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5322. # self.ui.geo_edit_toolbar.setVisible(False)
  5323. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5324. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  5325. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5326. self.ui.toolbarview.setObjectName('View_TB')
  5327. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  5328. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  5329. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5330. # self.ui.grb_edit_toolbar.setVisible(False)
  5331. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5332. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  5333. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5334. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5335. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  5336. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5337. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5338. self.ui.snap_toolbar.setMaximumHeight(30)
  5339. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  5340. self.ui.corner_snap_btn.setVisible(True)
  5341. self.ui.snap_magnet.setVisible(True)
  5342. # add all the actions to the toolbars
  5343. self.ui.populate_toolbars()
  5344. # reconnect all the signals to the toolbar actions
  5345. self.connect_toolbar_signals()
  5346. self.ui.grid_snap_btn.setChecked(True)
  5347. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  5348. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  5349. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  5350. self.ui.grid_gap_link_cb.setChecked(True)
  5351. def on_cnc_custom_parameters(self, signal_text):
  5352. if signal_text == 'Parameters':
  5353. return
  5354. else:
  5355. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  5356. def on_save_button(self):
  5357. log.debug("App.on_save_button() --> Saving preferences to file.")
  5358. self.preferences_changed_flag = False
  5359. self.save_defaults(silent=False)
  5360. # load the defaults so they are updated into the app
  5361. self.load_defaults(filename='current_defaults')
  5362. # Re-fresh project options
  5363. self.on_options_app2project()
  5364. settings = QSettings("Open Source", "FlatCAM")
  5365. # save the notebook font size
  5366. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  5367. settings.setValue('notebook_font_size', fsize)
  5368. # save the axis font size
  5369. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  5370. settings.setValue('axis_font_size', g_fsize)
  5371. # save the textbox font size
  5372. tb_fsize = self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  5373. settings.setValue('textbox_font_size', tb_fsize)
  5374. # This will write the setting to the platform specific storage.
  5375. del settings
  5376. def handlePrint(self):
  5377. self.report_usage("handlePrint()")
  5378. dialog = QtPrintSupport.QPrintDialog()
  5379. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  5380. self.ui.code_editor.document().print_(dialog.printer())
  5381. def handlePreview(self):
  5382. self.report_usage("handlePreview()")
  5383. dialog = QtPrintSupport.QPrintPreviewDialog()
  5384. dialog.paintRequested.connect(self.ui.code_editor.print_)
  5385. dialog.exec_()
  5386. def handleTextChanged(self):
  5387. # enable = not self.ui.code_editor.document().isEmpty()
  5388. # self.ui.buttonPrint.setEnabled(enable)
  5389. # self.ui.buttonPreview.setEnabled(enable)
  5390. pass
  5391. def handleOpen(self, filt=None):
  5392. self.report_usage("handleOpen()")
  5393. if filt:
  5394. _filter_ = filt
  5395. else:
  5396. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  5397. "All Files (*.*)"
  5398. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  5399. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  5400. if path:
  5401. file = QtCore.QFile(path)
  5402. if file.open(QtCore.QIODevice.ReadOnly):
  5403. stream = QtCore.QTextStream(file)
  5404. self.gcode_edited = stream.readAll()
  5405. self.ui.code_editor.setPlainText(self.gcode_edited)
  5406. file.close()
  5407. def handleSaveGCode(self, name=None, filt=None):
  5408. self.report_usage("handleSaveGCode()")
  5409. if filt:
  5410. _filter_ = filt
  5411. else:
  5412. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  5413. "All Files (*.*)"
  5414. if name:
  5415. obj_name = name
  5416. else:
  5417. try:
  5418. obj_name = self.collection.get_active().options['name']
  5419. except AttributeError:
  5420. obj_name = 'file'
  5421. if filt is None:
  5422. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  5423. try:
  5424. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  5425. caption=_("Export G-Code ..."),
  5426. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  5427. filter=_filter_
  5428. )[0])
  5429. except TypeError:
  5430. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  5431. if filename == "":
  5432. self.inform.emit('[WARNING_NOTCL] %s' %
  5433. _("Export Code cancelled."))
  5434. return
  5435. else:
  5436. try:
  5437. my_gcode = self.ui.code_editor.toPlainText()
  5438. with open(filename, 'w') as f:
  5439. for line in my_gcode:
  5440. f.write(line)
  5441. except FileNotFoundError:
  5442. self.inform.emit('[WARNING] %s' %
  5443. _("No such file or directory"))
  5444. return
  5445. except PermissionError:
  5446. self.inform.emit('[WARNING] %s' %
  5447. _("Permission denied, saving not possible.\n"
  5448. "Most likely another app is holding the file open and not accessible."))
  5449. return
  5450. # Just for adding it to the recent files list.
  5451. if self.defaults["global_open_style"] is False:
  5452. self.file_opened.emit("cncjob", filename)
  5453. self.file_saved.emit("cncjob", filename)
  5454. self.inform.emit('%s: %s' % (_("Saved to"), str(filename)))
  5455. def handleFindGCode(self):
  5456. self.report_usage("handleFindGCode()")
  5457. flags = QtGui.QTextDocument.FindCaseSensitively
  5458. text_to_be_found = self.ui.entryFind.get_value()
  5459. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  5460. if r is False:
  5461. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5462. def handleReplaceGCode(self):
  5463. self.report_usage("handleReplaceGCode()")
  5464. old = self.ui.entryFind.get_value()
  5465. new = self.ui.entryReplace.get_value()
  5466. if self.ui.sel_all_cb.isChecked():
  5467. while True:
  5468. cursor = self.ui.code_editor.textCursor()
  5469. cursor.beginEditBlock()
  5470. flags = QtGui.QTextDocument.FindCaseSensitively
  5471. # self.ui.editor is the QPlainTextEdit
  5472. r = self.ui.code_editor.find(str(old), flags)
  5473. if r:
  5474. qc = self.ui.code_editor.textCursor()
  5475. if qc.hasSelection():
  5476. qc.insertText(new)
  5477. else:
  5478. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5479. break
  5480. # Mark end of undo block
  5481. cursor.endEditBlock()
  5482. else:
  5483. cursor = self.ui.code_editor.textCursor()
  5484. cursor.beginEditBlock()
  5485. qc = self.ui.code_editor.textCursor()
  5486. if qc.hasSelection():
  5487. qc.insertText(new)
  5488. # Mark end of undo block
  5489. cursor.endEditBlock()
  5490. def handleCopyAll(self):
  5491. text = self.ui.code_editor.toPlainText()
  5492. self.clipboard.setText(text)
  5493. self.inform.emit(_("Code Editor content copied to clipboard ..."))
  5494. def handleRunCode(self):
  5495. # trying to run a Tcl command without having the Shell open will create some warnings because the Tcl Shell
  5496. # tries to print on a hidden widget, therefore show the dock if hidden
  5497. if self.ui.shell_dock.isHidden():
  5498. self.ui.shell_dock.show()
  5499. self.script_code = deepcopy(self.ui.code_editor.toPlainText())
  5500. # self.shell._sysShell.exec_command(script_code)
  5501. old_line = ''
  5502. for tcl_command_line in self.script_code.splitlines():
  5503. # do not process lines starting with '#' = comment and empty lines
  5504. if not tcl_command_line.startswith('#') and tcl_command_line != '':
  5505. # id FlatCAM is run in Windows then replace all the slashes with
  5506. # the UNIX style slash that TCL understands
  5507. if sys.platform == 'win32':
  5508. if "open" in tcl_command_line:
  5509. tcl_command_line = tcl_command_line.replace('\\', '/')
  5510. if old_line != '':
  5511. new_command = old_line + tcl_command_line + '\n'
  5512. else:
  5513. new_command = tcl_command_line
  5514. # execute the actual Tcl command
  5515. try:
  5516. self.shell.open_proccessing() # Disables input box.
  5517. result = self.tcl.eval(str(new_command))
  5518. if result != 'None':
  5519. self.shell.append_output(result + '\n')
  5520. old_line = ''
  5521. except tk.TclError:
  5522. old_line = old_line + tcl_command_line + '\n'
  5523. except Exception as e:
  5524. log.debug("App.handleRunCode() --> %s" % str(e))
  5525. if old_line != '':
  5526. # it means that the script finished with an error
  5527. result = self.tcl.eval("set errorInfo")
  5528. self.log.error("Exec command Exception: %s" % (result + '\n'))
  5529. self.shell.append_error('ERROR: ' + result + '\n')
  5530. self.shell.close_proccessing()
  5531. def on_tool_add_keypress(self):
  5532. # ## Current application units in Upper Case
  5533. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5534. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5535. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5536. if notebook_widget_name == 'selected_tab':
  5537. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5538. # Tool add works for Geometry only if Advanced is True in Preferences
  5539. if self.defaults["global_app_level"] == 'a':
  5540. tool_add_popup = FCInputDialog(title="New Tool ...",
  5541. text='Enter a Tool Diameter:',
  5542. min=0.0000, max=99.9999, decimals=4)
  5543. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5544. val, ok = tool_add_popup.get_value()
  5545. if ok:
  5546. if float(val) == 0:
  5547. self.inform.emit('[WARNING_NOTCL] %s' %
  5548. _("Please enter a tool diameter with non-zero value, in Float format."))
  5549. return
  5550. self.collection.get_active().on_tool_add(dia=float(val))
  5551. else:
  5552. self.inform.emit('[WARNING_NOTCL] %s...' %
  5553. _("Adding Tool cancelled"))
  5554. else:
  5555. msgbox = QtWidgets.QMessageBox()
  5556. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5557. "Go to Preferences -> General - Show Advanced Options."))
  5558. msgbox.setWindowTitle("Tool adding ...")
  5559. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  5560. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5561. msgbox.setDefaultButton(bt_ok)
  5562. msgbox.exec_()
  5563. # work only if the notebook tab on focus is the Tools_Tab
  5564. if notebook_widget_name == 'tool_tab':
  5565. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5566. tool_add_popup = FCInputDialog(title="New Tool ...",
  5567. text='Enter a Tool Diameter:',
  5568. min=0.0000, max=99.9999, decimals=4)
  5569. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5570. val, ok = tool_add_popup.get_value()
  5571. # and only if the tool is NCC Tool
  5572. if tool_widget == self.ncclear_tool.toolName:
  5573. if ok:
  5574. if float(val) == 0:
  5575. self.inform.emit('[WARNING_NOTCL] %s' %
  5576. _("Please enter a tool diameter with non-zero value, in Float format."))
  5577. return
  5578. self.ncclear_tool.on_tool_add(dia=float(val))
  5579. else:
  5580. self.inform.emit('[WARNING_NOTCL] %s...' %
  5581. _("Adding Tool cancelled"))
  5582. # and only if the tool is Paint Area Tool
  5583. elif tool_widget == self.paint_tool.toolName:
  5584. if ok:
  5585. if float(val) == 0:
  5586. self.inform.emit('[WARNING_NOTCL] %s' %
  5587. _("Please enter a tool diameter with non-zero value, in Float format."))
  5588. return
  5589. self.paint_tool.on_tool_add(dia=float(val))
  5590. else:
  5591. self.inform.emit('[WARNING_NOTCL] %s...' %
  5592. _("Adding Tool cancelled"))
  5593. # and only if the tool is Solder Paste Dispensing Tool
  5594. elif tool_widget == self.paste_tool.toolName:
  5595. if ok:
  5596. if float(val) == 0:
  5597. self.inform.emit('[WARNING_NOTCL] %s' %
  5598. _("Please enter a tool diameter with non-zero value, in Float format."))
  5599. return
  5600. self.paste_tool.on_tool_add(dia=float(val))
  5601. else:
  5602. self.inform.emit('[WARNING_NOTCL] %s...' %
  5603. _("Adding Tool cancelled"))
  5604. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5605. # See description bellow.
  5606. def on_delete_keypress(self):
  5607. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5608. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5609. if notebook_widget_name == 'selected_tab':
  5610. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5611. self.collection.get_active().on_tool_delete()
  5612. # work only if the notebook tab on focus is the Tools_Tab
  5613. elif notebook_widget_name == 'tool_tab':
  5614. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5615. # and only if the tool is NCC Tool
  5616. if tool_widget == self.ncclear_tool.toolName:
  5617. self.ncclear_tool.on_tool_delete()
  5618. # and only if the tool is Paint Tool
  5619. elif tool_widget == self.paint_tool.toolName:
  5620. self.paint_tool.on_tool_delete()
  5621. # and only if the tool is Solder Paste Dispensing Tool
  5622. elif tool_widget == self.paste_tool.toolName:
  5623. self.paste_tool.on_tool_delete()
  5624. else:
  5625. self.on_delete()
  5626. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5627. # some screens you have to be careful where you hover with your mouse.
  5628. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5629. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5630. # Complicated, I know :)
  5631. def on_delete(self):
  5632. """
  5633. Delete the currently selected FlatCAMObjs.
  5634. :return: None
  5635. """
  5636. self.report_usage("on_delete()")
  5637. response = None
  5638. bt_ok = None
  5639. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5640. # a geometry object before we update it.
  5641. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5642. and self.grb_editor.editor_active is False:
  5643. if self.defaults["global_delete_confirmation"] is True:
  5644. msgbox = QtWidgets.QMessageBox()
  5645. msgbox.setWindowTitle(_("Delete objects"))
  5646. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  5647. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5648. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5649. "the selected objects?"))
  5650. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5651. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5652. msgbox.setDefaultButton(bt_ok)
  5653. msgbox.exec_()
  5654. response = msgbox.clickedButton()
  5655. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  5656. if self.collection.get_active():
  5657. self.log.debug("App.on_delete()")
  5658. while self.collection.get_active():
  5659. obj_active = self.collection.get_active()
  5660. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  5661. if isinstance(obj_active, FlatCAMGerber):
  5662. for el in obj_active.mark_shapes:
  5663. obj_active.mark_shapes[el].clear(update=True)
  5664. obj_active.mark_shapes[el].enabled = False
  5665. # obj_active.mark_shapes[el] = None
  5666. del el
  5667. elif isinstance(obj_active, FlatCAMCNCjob):
  5668. try:
  5669. obj_active.annotation.clear(update=True)
  5670. obj_active.annotation.enabled = False
  5671. except AttributeError:
  5672. pass
  5673. self.delete_first_selected()
  5674. self.inform.emit('%s...' %
  5675. _("Object(s) deleted"))
  5676. # make sure that the selection shape is deleted, too
  5677. self.delete_selection_shape()
  5678. else:
  5679. self.inform.emit(_("Failed. No object(s) selected..."))
  5680. else:
  5681. self.inform.emit(_("Save the work in Editor and try again ..."))
  5682. def delete_first_selected(self):
  5683. # Keep this for later
  5684. try:
  5685. sel_obj = self.collection.get_active()
  5686. name = sel_obj.options["name"]
  5687. isPlotted = sel_obj.options["plot"]
  5688. except AttributeError:
  5689. self.log.debug("Nothing selected for deletion")
  5690. return
  5691. if self.is_legacy is True:
  5692. # Remove plot only if the object was plotted otherwise delaxes will fail
  5693. if isPlotted:
  5694. try:
  5695. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  5696. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  5697. except Exception as e:
  5698. log.debug("App.delete_first_selected() --> %s" % str(e))
  5699. self.plotcanvas.auto_adjust_axes()
  5700. # Remove from dictionary
  5701. self.collection.delete_active()
  5702. # Clear form
  5703. self.setup_component_editor()
  5704. self.inform.emit('%s: %s' %
  5705. (_("Object deleted"), name))
  5706. def on_set_origin(self):
  5707. """
  5708. Set the origin to the left mouse click position
  5709. :return: None
  5710. """
  5711. # display the message for the user
  5712. # and ask him to click on the desired position
  5713. self.report_usage("on_set_origin()")
  5714. def origin_replot():
  5715. def worker_task():
  5716. with self.proc_container.new('%s...' % _("Plotting")):
  5717. for obj in self.collection.get_list():
  5718. obj.plot()
  5719. self.plotcanvas.fit_view()
  5720. if self.is_legacy:
  5721. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  5722. else:
  5723. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  5724. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5725. self.inform.emit(_('Click to set the origin ...'))
  5726. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  5727. # first disconnect it as it may have been used by something else
  5728. try:
  5729. self.replot_signal.disconnect()
  5730. except TypeError:
  5731. pass
  5732. self.replot_signal[list].connect(origin_replot)
  5733. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  5734. """
  5735. :param event:
  5736. :param location:
  5737. :param noplot:
  5738. :param use_thread:
  5739. :return:
  5740. """
  5741. noplot_sig = noplot
  5742. def worker_task():
  5743. with self.proc_container.new(_("Setting Origin...")):
  5744. for obj in self.collection.get_list():
  5745. obj.offset((x, y))
  5746. self.object_changed.emit(obj)
  5747. # Update the object bounding box options
  5748. a, b, c, d = obj.bounds()
  5749. obj.options['xmin'] = a
  5750. obj.options['ymin'] = b
  5751. obj.options['xmax'] = c
  5752. obj.options['ymax'] = d
  5753. self.inform.emit('[success] %s...' %
  5754. _('Origin set'))
  5755. if noplot_sig is False:
  5756. self.replot_signal.emit([])
  5757. if location is not None:
  5758. if len(location) != 2:
  5759. self.inform.emit('[ERROR_NOTCL] %s...' %
  5760. _("Origin coordinates specified but incomplete."))
  5761. return 'fail'
  5762. x, y = location
  5763. if use_thread is True:
  5764. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5765. else:
  5766. worker_task()
  5767. self.should_we_save = True
  5768. return
  5769. if event.button == 1:
  5770. if self.is_legacy is False:
  5771. event_pos = event.pos
  5772. else:
  5773. event_pos = (event.xdata, event.ydata)
  5774. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5775. if self.grid_status() == True:
  5776. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5777. else:
  5778. pos = pos_canvas
  5779. x = 0 - pos[0]
  5780. y = 0 - pos[1]
  5781. if use_thread is True:
  5782. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5783. else:
  5784. worker_task()
  5785. self.should_we_save = True
  5786. def on_jump_to(self, custom_location=None, fit_center=True):
  5787. """
  5788. Jump to a location by setting the mouse cursor location
  5789. :return:
  5790. """
  5791. self.report_usage("on_jump_to()")
  5792. # if self.is_legacy is True:
  5793. # self.inform.emit(_("Not available with the current Graphic Engine Legacy(2D)."))
  5794. # return
  5795. if not custom_location:
  5796. dia_box = Dialog_box(title=_("Jump to ..."),
  5797. label=_("Enter the coordinates in format X,Y:"),
  5798. icon=QtGui.QIcon('share/jump_to16.png'))
  5799. if dia_box.ok is True:
  5800. try:
  5801. location = eval(dia_box.location)
  5802. if not isinstance(location, tuple):
  5803. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  5804. return
  5805. except:
  5806. return
  5807. else:
  5808. return
  5809. else:
  5810. location = custom_location
  5811. if fit_center:
  5812. self.plotcanvas.fit_center(loc=location)
  5813. cursor = QtGui.QCursor()
  5814. if self.is_legacy is False:
  5815. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5816. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  5817. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  5818. else:
  5819. # find the canvas origin which is in the top left corner
  5820. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5821. # determine the coordinates for the lowest left point of the canvas
  5822. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  5823. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  5824. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  5825. # canvas) and the point (width, height) is in the top-right location
  5826. loc = self.plotcanvas.axes.transData.transform_point(location)
  5827. cursor.setPos(x0 + loc[0], y0 - loc[1])
  5828. self.inform.emit('[success] %s' %
  5829. _("Done."))
  5830. return location
  5831. def on_copy_object(self):
  5832. self.report_usage("on_copy_object()")
  5833. def initialize(obj_init, app):
  5834. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5835. try:
  5836. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5837. except AttributeError:
  5838. pass
  5839. try:
  5840. obj_init.apertures = deepcopy(obj.apertures)
  5841. except AttributeError:
  5842. pass
  5843. try:
  5844. if obj.tools:
  5845. obj_init.tools = deepcopy(obj.tools)
  5846. except Exception as e:
  5847. log.debug("App.on_copy_object() --> %s" % str(e))
  5848. def initialize_excellon(obj_init, app):
  5849. obj_init.tools = deepcopy(obj.tools)
  5850. # drills are offset, so they need to be deep copied
  5851. obj_init.drills = deepcopy(obj.drills)
  5852. # slots are offset, so they need to be deep copied
  5853. obj_init.slots = deepcopy(obj.slots)
  5854. obj_init.create_geometry()
  5855. for obj in self.collection.get_selected():
  5856. obj_name = obj.options["name"]
  5857. try:
  5858. if isinstance(obj, FlatCAMExcellon):
  5859. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  5860. elif isinstance(obj, FlatCAMGerber):
  5861. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  5862. elif isinstance(obj, FlatCAMGeometry):
  5863. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  5864. except Exception as e:
  5865. return "Operation failed: %s" % str(e)
  5866. def on_copy_object2(self, custom_name):
  5867. def initialize_geometry(obj_init, app):
  5868. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5869. try:
  5870. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5871. except AttributeError:
  5872. pass
  5873. try:
  5874. obj_init.apertures = deepcopy(obj.apertures)
  5875. except AttributeError:
  5876. pass
  5877. try:
  5878. if obj.tools:
  5879. obj_init.tools = deepcopy(obj.tools)
  5880. except Exception as e:
  5881. log.debug("on_copy_object2() --> %s" % str(e))
  5882. def initialize_gerber(obj_init, app):
  5883. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5884. obj_init.apertures = deepcopy(obj.apertures)
  5885. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  5886. def initialize_excellon(obj_init, app):
  5887. obj_init.tools = deepcopy(obj.tools)
  5888. # drills are offset, so they need to be deep copied
  5889. obj_init.drills = deepcopy(obj.drills)
  5890. # slots are offset, so they need to be deep copied
  5891. obj_init.slots = deepcopy(obj.slots)
  5892. obj_init.create_geometry()
  5893. for obj in self.collection.get_selected():
  5894. obj_name = obj.options["name"]
  5895. try:
  5896. if isinstance(obj, FlatCAMExcellon):
  5897. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  5898. elif isinstance(obj, FlatCAMGerber):
  5899. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  5900. elif isinstance(obj, FlatCAMGeometry):
  5901. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  5902. except Exception as e:
  5903. return "Operation failed: %s" % str(e)
  5904. def on_rename_object(self, text):
  5905. self.report_usage("on_rename_object()")
  5906. named_obj = self.collection.get_active()
  5907. for obj in named_obj:
  5908. if obj is list:
  5909. self.on_rename_object(text)
  5910. else:
  5911. try:
  5912. obj.options['name'] = text
  5913. except Exception as e:
  5914. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  5915. def convert_any2geo(self):
  5916. self.report_usage("convert_any2geo()")
  5917. def initialize(obj_init, app):
  5918. obj_init.solid_geometry = obj.solid_geometry
  5919. try:
  5920. obj_init.follow_geometry = obj.follow_geometry
  5921. except AttributeError:
  5922. pass
  5923. try:
  5924. obj_init.apertures = obj.apertures
  5925. except AttributeError:
  5926. pass
  5927. try:
  5928. if obj.tools:
  5929. obj_init.tools = obj.tools
  5930. except AttributeError:
  5931. pass
  5932. def initialize_excellon(obj_init, app):
  5933. # objs = self.collection.get_selected()
  5934. # FlatCAMGeometry.merge(objs, obj)
  5935. solid_geo = []
  5936. for tool in obj.tools:
  5937. for geo in obj.tools[tool]['solid_geometry']:
  5938. solid_geo.append(geo)
  5939. obj_init.solid_geometry = deepcopy(solid_geo)
  5940. if not self.collection.get_selected():
  5941. log.warning("App.convert_any2geo --> No object selected")
  5942. self.inform.emit('[WARNING_NOTCL] %s' %
  5943. _("No object is selected. Select an object and try again."))
  5944. return
  5945. for obj in self.collection.get_selected():
  5946. obj_name = obj.options["name"]
  5947. try:
  5948. if isinstance(obj, FlatCAMExcellon):
  5949. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  5950. else:
  5951. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  5952. except Exception as e:
  5953. return "Operation failed: %s" % str(e)
  5954. def convert_any2gerber(self):
  5955. self.report_usage("convert_any2gerber()")
  5956. def initialize_geometry(obj_init, app):
  5957. apertures = {}
  5958. apid = 0
  5959. apertures[str(apid)] = {}
  5960. apertures[str(apid)]['geometry'] = []
  5961. for obj_orig in obj.solid_geometry:
  5962. new_elem = dict()
  5963. new_elem['solid'] = obj_orig
  5964. new_elem['follow'] = obj_orig.exterior
  5965. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  5966. apertures[str(apid)]['size'] = 0.0
  5967. apertures[str(apid)]['type'] = 'C'
  5968. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5969. obj_init.apertures = deepcopy(apertures)
  5970. def initialize_excellon(obj_init, app):
  5971. apertures = {}
  5972. apid = 10
  5973. for tool in obj.tools:
  5974. apertures[str(apid)] = {}
  5975. apertures[str(apid)]['geometry'] = []
  5976. for geo in obj.tools[tool]['solid_geometry']:
  5977. new_el = dict()
  5978. new_el['solid'] = geo
  5979. new_el['follow'] = geo.exterior
  5980. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  5981. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  5982. apertures[str(apid)]['type'] = 'C'
  5983. apid += 1
  5984. # create solid_geometry
  5985. solid_geometry = []
  5986. for apid in apertures:
  5987. for geo_el in apertures[apid]['geometry']:
  5988. solid_geometry.append(geo_el['solid'])
  5989. solid_geometry = MultiPolygon(solid_geometry)
  5990. solid_geometry = solid_geometry.buffer(0.0000001)
  5991. obj_init.solid_geometry = deepcopy(solid_geometry)
  5992. obj_init.apertures = deepcopy(apertures)
  5993. # clear the working objects (perhaps not necessary due of Python GC)
  5994. apertures.clear()
  5995. if not self.collection.get_selected():
  5996. log.warning("App.convert_any2gerber --> No object selected")
  5997. self.inform.emit('[WARNING_NOTCL] %s' %
  5998. _("No object is selected. Select an object and try again."))
  5999. return
  6000. for obj in self.collection.get_selected():
  6001. obj_name = obj.options["name"]
  6002. try:
  6003. if isinstance(obj, FlatCAMExcellon):
  6004. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  6005. elif isinstance(obj, FlatCAMGeometry):
  6006. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  6007. else:
  6008. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  6009. except Exception as e:
  6010. return "Operation failed: %s" % str(e)
  6011. def abort_all_tasks(self):
  6012. if self.abort_flag is False:
  6013. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  6014. self.abort_flag = True
  6015. def app_is_idle(self):
  6016. if self.abort_flag:
  6017. self.inform.emit('[WARNING_NOTCL] %s' %
  6018. _("The current task was gracefully closed on user request..."))
  6019. self.abort_flag = False
  6020. def on_selectall(self):
  6021. self.report_usage("on_selectall()")
  6022. # delete the possible selection box around a possible selected object
  6023. self.delete_selection_shape()
  6024. for name in self.collection.get_names():
  6025. self.collection.set_active(name)
  6026. curr_sel_obj = self.collection.get_by_name(name)
  6027. # create the selection box around the selected object
  6028. if self.defaults['global_selection_shape'] is True:
  6029. self.draw_selection_shape(curr_sel_obj)
  6030. def on_preferences(self):
  6031. # add the tab if it was closed
  6032. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  6033. # delete the absolute and relative position and messages in the infobar
  6034. self.ui.position_label.setText("")
  6035. self.ui.rel_position_label.setText("")
  6036. # Switch plot_area to preferences page
  6037. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  6038. # self.ui.show()
  6039. # this disconnect() is done so the slot will be connected only once
  6040. try:
  6041. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_preferences_closed)
  6042. except (TypeError, AttributeError):
  6043. pass
  6044. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_preferences_closed)
  6045. # detect changes in the preferences
  6046. for idx in range(self.ui.pref_tab_area.count()):
  6047. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6048. try:
  6049. try:
  6050. tb.textEdited.disconnect(self.on_preferences_edited)
  6051. except (TypeError, AttributeError):
  6052. pass
  6053. tb.textEdited.connect(self.on_preferences_edited)
  6054. except AttributeError:
  6055. pass
  6056. try:
  6057. try:
  6058. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6059. except (TypeError, AttributeError):
  6060. pass
  6061. tb.modificationChanged.connect(self.on_preferences_edited)
  6062. except AttributeError:
  6063. pass
  6064. try:
  6065. try:
  6066. tb.toggled.disconnect(self.on_preferences_edited)
  6067. except (TypeError, AttributeError):
  6068. pass
  6069. tb.toggled.connect(self.on_preferences_edited)
  6070. except AttributeError:
  6071. pass
  6072. try:
  6073. try:
  6074. tb.valueChanged.disconnect(self.on_preferences_edited)
  6075. except (TypeError, AttributeError):
  6076. pass
  6077. tb.valueChanged.connect(self.on_preferences_edited)
  6078. except AttributeError:
  6079. pass
  6080. try:
  6081. try:
  6082. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6083. except (TypeError, AttributeError):
  6084. pass
  6085. tb.currentIndexChanged.connect(self.on_preferences_edited)
  6086. except AttributeError:
  6087. pass
  6088. def on_preferences_edited(self):
  6089. self.inform.emit('[WARNING_NOTCL] %s' %
  6090. _("Preferences edited but not saved."))
  6091. self.preferences_changed_flag = True
  6092. def on_preferences_closed(self):
  6093. # disconnect
  6094. for idx in range(self.ui.pref_tab_area.count()):
  6095. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6096. try:
  6097. tb.textEdited.disconnect(self.on_preferences_edited)
  6098. except (TypeError, AttributeError):
  6099. pass
  6100. try:
  6101. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6102. except (TypeError, AttributeError):
  6103. pass
  6104. try:
  6105. tb.toggled.disconnect(self.on_preferences_edited)
  6106. except (TypeError, AttributeError):
  6107. pass
  6108. try:
  6109. tb.valueChanged.disconnect(self.on_preferences_edited)
  6110. except (TypeError, AttributeError):
  6111. pass
  6112. try:
  6113. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6114. except (TypeError, AttributeError):
  6115. pass
  6116. if self.preferences_changed_flag is True:
  6117. msgbox = QtWidgets.QMessageBox()
  6118. msgbox.setText(_("One or more values are changed.\n"
  6119. "Do you want to save the Preferences?"))
  6120. msgbox.setWindowTitle(_("Save Preferences"))
  6121. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6122. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6123. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6124. msgbox.setDefaultButton(bt_yes)
  6125. msgbox.exec_()
  6126. response = msgbox.clickedButton()
  6127. if response == bt_yes:
  6128. self.on_save_button()
  6129. self.inform.emit('[success] %s' %
  6130. _("Preferences saved."))
  6131. else:
  6132. self.preferences_changed_flag = False
  6133. return
  6134. def on_flipy(self):
  6135. self.report_usage("on_flipy()")
  6136. obj_list = self.collection.get_selected()
  6137. xminlist = []
  6138. yminlist = []
  6139. xmaxlist = []
  6140. ymaxlist = []
  6141. if not obj_list:
  6142. self.inform.emit('[WARNING_NOTCL] %s' %
  6143. _("No object selected to Flip on Y axis."))
  6144. else:
  6145. try:
  6146. # first get a bounding box to fit all
  6147. for obj in obj_list:
  6148. xmin, ymin, xmax, ymax = obj.bounds()
  6149. xminlist.append(xmin)
  6150. yminlist.append(ymin)
  6151. xmaxlist.append(xmax)
  6152. ymaxlist.append(ymax)
  6153. # get the minimum x,y and maximum x,y for all objects selected
  6154. xminimal = min(xminlist)
  6155. yminimal = min(yminlist)
  6156. xmaximal = max(xmaxlist)
  6157. ymaximal = max(ymaxlist)
  6158. px = 0.5 * (xminimal + xmaximal)
  6159. py = 0.5 * (yminimal + ymaximal)
  6160. # execute mirroring
  6161. for obj in obj_list:
  6162. obj.mirror('X', [px, py])
  6163. obj.plot()
  6164. self.object_changed.emit(obj)
  6165. self.inform.emit('[success] %s' %
  6166. _("Flip on Y axis done."))
  6167. except Exception as e:
  6168. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6169. (_("Flip action was not executed."), str(e)))
  6170. return
  6171. def on_flipx(self):
  6172. self.report_usage("on_flipx()")
  6173. obj_list = self.collection.get_selected()
  6174. xminlist = []
  6175. yminlist = []
  6176. xmaxlist = []
  6177. ymaxlist = []
  6178. if not obj_list:
  6179. self.inform.emit('[WARNING_NOTCL] %s' %
  6180. _("No object selected to Flip on X axis."))
  6181. else:
  6182. try:
  6183. # first get a bounding box to fit all
  6184. for obj in obj_list:
  6185. xmin, ymin, xmax, ymax = obj.bounds()
  6186. xminlist.append(xmin)
  6187. yminlist.append(ymin)
  6188. xmaxlist.append(xmax)
  6189. ymaxlist.append(ymax)
  6190. # get the minimum x,y and maximum x,y for all objects selected
  6191. xminimal = min(xminlist)
  6192. yminimal = min(yminlist)
  6193. xmaximal = max(xmaxlist)
  6194. ymaximal = max(ymaxlist)
  6195. px = 0.5 * (xminimal + xmaximal)
  6196. py = 0.5 * (yminimal + ymaximal)
  6197. # execute mirroring
  6198. for obj in obj_list:
  6199. obj.mirror('Y', [px, py])
  6200. obj.plot()
  6201. self.object_changed.emit(obj)
  6202. self.inform.emit('[success] %s' %
  6203. _("Flip on X axis done."))
  6204. except Exception as e:
  6205. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6206. (_("Flip action was not executed."), str(e)))
  6207. return
  6208. def on_rotate(self, silent=False, preset=None):
  6209. self.report_usage("on_rotate()")
  6210. obj_list = self.collection.get_selected()
  6211. xminlist = []
  6212. yminlist = []
  6213. xmaxlist = []
  6214. ymaxlist = []
  6215. if not obj_list:
  6216. self.inform.emit('[WARNING_NOTCL] %s' %
  6217. _("No object selected to Rotate."))
  6218. else:
  6219. if silent is False:
  6220. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6221. min=-360, max=360, decimals=4,
  6222. init_val=float(self.defaults['tools_transform_rotate']))
  6223. num, ok = rotatebox.get_value()
  6224. else:
  6225. num = preset
  6226. ok = True
  6227. if ok:
  6228. try:
  6229. # first get a bounding box to fit all
  6230. for obj in obj_list:
  6231. xmin, ymin, xmax, ymax = obj.bounds()
  6232. xminlist.append(xmin)
  6233. yminlist.append(ymin)
  6234. xmaxlist.append(xmax)
  6235. ymaxlist.append(ymax)
  6236. # get the minimum x,y and maximum x,y for all objects selected
  6237. xminimal = min(xminlist)
  6238. yminimal = min(yminlist)
  6239. xmaximal = max(xmaxlist)
  6240. ymaximal = max(ymaxlist)
  6241. px = 0.5 * (xminimal + xmaximal)
  6242. py = 0.5 * (yminimal + ymaximal)
  6243. for sel_obj in obj_list:
  6244. sel_obj.rotate(-float(num), point=(px, py))
  6245. sel_obj.plot()
  6246. self.object_changed.emit(sel_obj)
  6247. self.inform.emit('[success] %s' %
  6248. _("Rotation done."))
  6249. except Exception as e:
  6250. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6251. (_("Rotation movement was not executed."), str(e)))
  6252. return
  6253. def on_skewx(self):
  6254. self.report_usage("on_skewx()")
  6255. obj_list = self.collection.get_selected()
  6256. xminlist = []
  6257. yminlist = []
  6258. if not obj_list:
  6259. self.inform.emit('[WARNING_NOTCL] %s' %
  6260. _("No object selected to Skew/Shear on X axis."))
  6261. else:
  6262. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6263. min=-360, max=360, decimals=4,
  6264. init_val=float(self.defaults['tools_transform_skew_x']))
  6265. num, ok = skewxbox.get_value()
  6266. if ok:
  6267. # first get a bounding box to fit all
  6268. for obj in obj_list:
  6269. xmin, ymin, xmax, ymax = obj.bounds()
  6270. xminlist.append(xmin)
  6271. yminlist.append(ymin)
  6272. # get the minimum x,y and maximum x,y for all objects selected
  6273. xminimal = min(xminlist)
  6274. yminimal = min(yminlist)
  6275. for obj in obj_list:
  6276. obj.skew(num, 0, point=(xminimal, yminimal))
  6277. obj.plot()
  6278. self.object_changed.emit(obj)
  6279. self.inform.emit('[success] %s' %
  6280. _("Skew on X axis done."))
  6281. def on_skewy(self):
  6282. self.report_usage("on_skewy()")
  6283. obj_list = self.collection.get_selected()
  6284. xminlist = []
  6285. yminlist = []
  6286. if not obj_list:
  6287. self.inform.emit('[WARNING_NOTCL] %s' %
  6288. _("No object selected to Skew/Shear on Y axis."))
  6289. else:
  6290. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6291. min=-360, max=360, decimals=4,
  6292. init_val=float(self.defaults['tools_transform_skew_y']))
  6293. num, ok = skewybox.get_value()
  6294. if ok:
  6295. # first get a bounding box to fit all
  6296. for obj in obj_list:
  6297. xmin, ymin, xmax, ymax = obj.bounds()
  6298. xminlist.append(xmin)
  6299. yminlist.append(ymin)
  6300. # get the minimum x,y and maximum x,y for all objects selected
  6301. xminimal = min(xminlist)
  6302. yminimal = min(yminlist)
  6303. for obj in obj_list:
  6304. obj.skew(0, num, point=(xminimal, yminimal))
  6305. obj.plot()
  6306. self.object_changed.emit(obj)
  6307. self.inform.emit('[success] %s' %
  6308. _("Skew on Y axis done."))
  6309. def on_plots_updated(self):
  6310. """
  6311. Callback used to report when the plots have changed.
  6312. Adjust axes and zooms to fit.
  6313. :return: None
  6314. """
  6315. if self.is_legacy is False:
  6316. self.plotcanvas.update() # TODO: Need update canvas?
  6317. else:
  6318. self.plotcanvas.auto_adjust_axes()
  6319. self.on_zoom_fit(None)
  6320. self.collection.update_view()
  6321. # self.inform.emit(_("Plots updated ..."))
  6322. # TODO: Rework toolbar 'clear', 'replot' functions
  6323. def on_toolbar_replot(self):
  6324. """
  6325. Callback for toolbar button. Re-plots all objects.
  6326. :return: None
  6327. """
  6328. self.report_usage("on_toolbar_replot")
  6329. self.log.debug("on_toolbar_replot()")
  6330. try:
  6331. self.collection.get_active().read_form()
  6332. except AttributeError:
  6333. self.log.debug("on_toolbar_replot(): AttributeError")
  6334. pass
  6335. self.plot_all()
  6336. def on_row_activated(self, index):
  6337. if index.isValid():
  6338. if index.internalPointer().parent_item != self.collection.root_item:
  6339. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6340. self.collection.on_item_activated(index)
  6341. def grid_status(self):
  6342. if self.ui.grid_snap_btn.isChecked():
  6343. return True
  6344. else:
  6345. return False
  6346. def populate_cmenu_grids(self):
  6347. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6348. self.ui.cmenu_gridmenu.clear()
  6349. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  6350. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  6351. grid_toggle.setCheckable(True)
  6352. if self.grid_status() == True:
  6353. grid_toggle.setChecked(True)
  6354. else:
  6355. grid_toggle.setChecked(False)
  6356. self.ui.cmenu_gridmenu.addSeparator()
  6357. for grid in sorted_list:
  6358. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  6359. action.triggered.connect(self.set_grid)
  6360. self.ui.cmenu_gridmenu.addSeparator()
  6361. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  6362. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  6363. grid_add.triggered.connect(self.on_grid_add)
  6364. grid_delete.triggered.connect(self.on_grid_delete)
  6365. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  6366. def set_grid(self):
  6367. self.ui.grid_gap_x_entry.setText(self.sender().text())
  6368. self.ui.grid_gap_y_entry.setText(self.sender().text())
  6369. def on_grid_add(self):
  6370. # ## Current application units in lower Case
  6371. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6372. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  6373. text=_('Enter a Grid Value:'),
  6374. min=0.0000, max=99.9999, decimals=4)
  6375. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  6376. val, ok = grid_add_popup.get_value()
  6377. if ok:
  6378. if float(val) == 0:
  6379. self.inform.emit('[WARNING_NOTCL] %s' %
  6380. _("Please enter a grid value with non-zero value, in Float format."))
  6381. return
  6382. else:
  6383. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  6384. self.defaults["global_grid_context_menu"][str(units)].append(val)
  6385. self.inform.emit('[success] %s...' %
  6386. _("New Grid added"))
  6387. else:
  6388. self.inform.emit('[WARNING_NOTCL] %s...' %
  6389. _("Grid already exists"))
  6390. else:
  6391. self.inform.emit('[WARNING_NOTCL] %s...' %
  6392. _("Adding New Grid cancelled"))
  6393. def on_grid_delete(self):
  6394. # ## Current application units in lower Case
  6395. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6396. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  6397. text='Enter a Grid Value:',
  6398. min=0.0000, max=99.9999, decimals=4)
  6399. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  6400. val, ok = grid_del_popup.get_value()
  6401. if ok:
  6402. if float(val) == 0:
  6403. self.inform.emit('[WARNING_NOTCL] %s' %
  6404. _("Please enter a grid value with non-zero value, in Float format."))
  6405. return
  6406. else:
  6407. try:
  6408. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  6409. except ValueError:
  6410. self.inform.emit('[ERROR_NOTCL]%s...' %
  6411. _(" Grid Value does not exist"))
  6412. return
  6413. self.inform.emit('[success] %s...' %
  6414. _("Grid Value deleted"))
  6415. else:
  6416. self.inform.emit('[WARNING_NOTCL] %s...' %
  6417. _("Delete Grid value cancelled"))
  6418. def on_shortcut_list(self):
  6419. self.report_usage("on_shortcut_list()")
  6420. # add the tab if it was closed
  6421. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  6422. # delete the absolute and relative position and messages in the infobar
  6423. self.ui.position_label.setText("")
  6424. self.ui.rel_position_label.setText("")
  6425. # Switch plot_area to preferences page
  6426. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  6427. # self.ui.show()
  6428. def on_select_tab(self, name):
  6429. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  6430. if self.ui.splitter.sizes()[0] == 0:
  6431. self.ui.splitter.setSizes([1, 1])
  6432. else:
  6433. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  6434. self.ui.splitter.setSizes([0, 1])
  6435. if name == 'project':
  6436. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6437. elif name == 'selected':
  6438. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6439. elif name == 'tool':
  6440. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  6441. def on_copy_name(self):
  6442. self.report_usage("on_copy_name()")
  6443. obj = self.collection.get_active()
  6444. try:
  6445. name = obj.options["name"]
  6446. except AttributeError:
  6447. log.debug("on_copy_name() --> No object selected to copy it's name")
  6448. self.inform.emit('[WARNING_NOTCL]%s' %
  6449. _(" No object selected to copy it's name"))
  6450. return
  6451. self.clipboard.setText(name)
  6452. self.inform.emit(_("Name copied on clipboard ..."))
  6453. def on_mouse_click_over_plot(self, event):
  6454. """
  6455. Default actions are:
  6456. :param event: Contains information about the event, like which button
  6457. was clicked, the pixel coordinates and the axes coordinates.
  6458. :return: None
  6459. """
  6460. self.pos = []
  6461. if self.is_legacy is False:
  6462. event_pos = event.pos
  6463. if self.defaults["global_pan_button"] == '2':
  6464. pan_button = 2
  6465. else:
  6466. pan_button = 3
  6467. # Set the mouse button for panning
  6468. self.plotcanvas.view.camera.pan_button_setting = pan_button
  6469. else:
  6470. event_pos = (event.xdata, event.ydata)
  6471. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6472. if self.defaults["global_pan_button"] == '2':
  6473. pan_button = 3
  6474. else:
  6475. pan_button = 2
  6476. # So it can receive key presses
  6477. self.plotcanvas.native.setFocus()
  6478. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6479. if self.grid_status() == True:
  6480. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  6481. else:
  6482. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  6483. try:
  6484. modifiers = QtWidgets.QApplication.keyboardModifiers()
  6485. if event.button == 1:
  6486. # Reset here the relative coordinates so there is a new reference on the click position
  6487. if self.rel_point1 is None:
  6488. self.rel_point1 = self.pos
  6489. else:
  6490. self.rel_point2 = copy(self.rel_point1)
  6491. self.rel_point1 = self.pos
  6492. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  6493. if modifiers == QtCore.Qt.ShiftModifier:
  6494. # do not auto open the Project Tab
  6495. self.click_noproject = True
  6496. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  6497. self.inform.emit('[success] %s' %
  6498. _("Coordinates copied to clipboard."))
  6499. return
  6500. self.on_mouse_move_over_plot(event, origin_click=True)
  6501. except Exception as e:
  6502. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  6503. def on_double_click_over_plot(self, event):
  6504. if event.button == 1:
  6505. self.doubleclick = True
  6506. def on_mouse_move_over_plot(self, event, origin_click=None):
  6507. """
  6508. Callback for the mouse motion event over the plot.
  6509. :param event: Contains information about the event.
  6510. :param origin_click
  6511. :return: None
  6512. """
  6513. if self.is_legacy is False:
  6514. event_pos = event.pos
  6515. if self.defaults["global_pan_button"] == '2':
  6516. pan_button = 2
  6517. else:
  6518. pan_button = 3
  6519. event_is_dragging = event.is_dragging
  6520. else:
  6521. event_pos = (event.xdata, event.ydata)
  6522. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6523. if self.defaults["global_pan_button"] == '2':
  6524. pan_button = 3
  6525. else:
  6526. pan_button = 2
  6527. event_is_dragging = self.plotcanvas.is_dragging
  6528. # So it can receive key presses
  6529. self.plotcanvas.native.setFocus()
  6530. self.pos_jump = event_pos
  6531. self.ui.popMenu.mouse_is_panning = False
  6532. if not origin_click:
  6533. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  6534. if event.button == pan_button and event_is_dragging == 1:
  6535. self.ui.popMenu.mouse_is_panning = True
  6536. return
  6537. if self.rel_point1 is not None:
  6538. try: # May fail in case mouse not within axes
  6539. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6540. if self.grid_status() == True:
  6541. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6542. # Update cursor
  6543. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  6544. symbol='++', edge_color='black', size=20)
  6545. else:
  6546. pos = (pos_canvas[0], pos_canvas[1])
  6547. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6548. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  6549. dx = pos[0] - float(self.rel_point1[0])
  6550. dy = pos[1] - float(self.rel_point1[1])
  6551. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6552. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6553. self.mouse = [pos[0], pos[1]]
  6554. # if the mouse is moved and the LMB is clicked then the action is a selection
  6555. if event_is_dragging == 1 and event.button == 1:
  6556. self.delete_selection_shape()
  6557. if dx < 0:
  6558. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  6559. face_color=self.defaults['global_alt_sel_fill'])
  6560. self.selection_type = False
  6561. elif dx > 0:
  6562. self.draw_moving_selection_shape(self.pos, pos)
  6563. self.selection_type = True
  6564. else:
  6565. self.selection_type = None
  6566. # hover effect - enabled in Preferences -> General -> GUI Settings
  6567. if self.defaults['global_hover']:
  6568. for obj in self.collection.get_list():
  6569. try:
  6570. # select the object(s) only if it is enabled (plotted)
  6571. if obj.options['plot']:
  6572. if obj not in self.collection.get_selected():
  6573. poly_obj = Polygon(
  6574. [(obj.options['xmin'], obj.options['ymin']),
  6575. (obj.options['xmax'], obj.options['ymin']),
  6576. (obj.options['xmax'], obj.options['ymax']),
  6577. (obj.options['xmin'], obj.options['ymax'])]
  6578. )
  6579. if Point(pos).within(poly_obj):
  6580. if obj.isHovering is False:
  6581. obj.isHovering = True
  6582. obj.notHovering = True
  6583. # create the selection box around the selected object
  6584. self.draw_hover_shape(obj, color='#d1e0e0FF')
  6585. else:
  6586. if obj.notHovering is True:
  6587. obj.notHovering = False
  6588. obj.isHovering = False
  6589. self.delete_hover_shape()
  6590. except:
  6591. # the Exception here will happen if we try to select on screen and we have an
  6592. # newly (and empty) just created Geometry or Excellon object that do not have the
  6593. # xmin, xmax, ymin, ymax options.
  6594. # In this case poly_obj creation (see above) will fail
  6595. pass
  6596. except:
  6597. self.ui.position_label.setText("")
  6598. self.ui.rel_position_label.setText("")
  6599. self.mouse = None
  6600. def on_mouse_click_release_over_plot(self, event):
  6601. """
  6602. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  6603. and has been registered in ''self.__init__()''.
  6604. :param event: contains information about the event.
  6605. :return:
  6606. """
  6607. pos = 0, 0
  6608. if self.is_legacy is False:
  6609. event_pos = event.pos
  6610. right_button = 2
  6611. else:
  6612. event_pos = (event.xdata, event.ydata)
  6613. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6614. right_button = 3
  6615. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6616. if self.grid_status() == True:
  6617. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6618. else:
  6619. pos = (pos_canvas[0], pos_canvas[1])
  6620. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  6621. # canvas menu
  6622. if event.button == right_button: # right click
  6623. if self.ui.popMenu.mouse_is_panning is False:
  6624. self.cursor = QtGui.QCursor()
  6625. self.populate_cmenu_grids()
  6626. self.ui.popMenu.popup(self.cursor.pos())
  6627. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  6628. # selection and then select a type of selection ("enclosing" or "touching")
  6629. try:
  6630. if event.button == 1: # left click
  6631. if self.doubleclick is True:
  6632. self.doubleclick = False
  6633. if self.collection.get_selected():
  6634. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6635. if self.ui.splitter.sizes()[0] == 0:
  6636. self.ui.splitter.setSizes([1, 1])
  6637. # delete the selection shape(S) as it may be in the way
  6638. self.delete_selection_shape()
  6639. self.delete_hover_shape()
  6640. else:
  6641. if self.selection_type is not None:
  6642. self.selection_area_handler(self.pos, pos, self.selection_type)
  6643. self.selection_type = None
  6644. else:
  6645. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  6646. if key_modifier == QtCore.Qt.ShiftModifier:
  6647. mod_key = 'Shift'
  6648. elif key_modifier == QtCore.Qt.ControlModifier:
  6649. mod_key = 'Control'
  6650. else:
  6651. mod_key = None
  6652. if mod_key == self.defaults["global_mselect_key"]:
  6653. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  6654. # deselect, and if it's not selected then it will be selected
  6655. # If there is no active command (self.command_active is None) then we check if we clicked
  6656. # on a object by checking the bounding limits against mouse click position
  6657. if self.command_active is None:
  6658. self.select_objects(key='CTRL')
  6659. self.delete_hover_shape()
  6660. else:
  6661. # If there is no active command (self.command_active is None) then we check if we clicked
  6662. # on a object by checking the bounding limits against mouse click position
  6663. if self.command_active is None:
  6664. self.select_objects()
  6665. self.delete_hover_shape()
  6666. except Exception as e:
  6667. log.warning("Error: %s" % str(e))
  6668. return
  6669. def selection_area_handler(self, start_pos, end_pos, sel_type):
  6670. """
  6671. :param start_pos: mouse position when the selection LMB click was done
  6672. :param end_pos: mouse position when the left mouse button is released
  6673. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  6674. :return:
  6675. """
  6676. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  6677. self.delete_selection_shape()
  6678. for obj in self.collection.get_list():
  6679. try:
  6680. # select the object(s) only if it is enabled (plotted)
  6681. if obj.options['plot']:
  6682. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  6683. (obj.options['xmax'], obj.options['ymin']),
  6684. (obj.options['xmax'], obj.options['ymax']),
  6685. (obj.options['xmin'], obj.options['ymax'])])
  6686. if sel_type is True:
  6687. if poly_obj.within(poly_selection):
  6688. # create the selection box around the selected object
  6689. if self.defaults['global_selection_shape'] is True:
  6690. self.draw_selection_shape(obj)
  6691. self.collection.set_active(obj.options['name'])
  6692. else:
  6693. if poly_selection.intersects(poly_obj):
  6694. # create the selection box around the selected object
  6695. if self.defaults['global_selection_shape'] is True:
  6696. self.draw_selection_shape(obj)
  6697. self.collection.set_active(obj.options['name'])
  6698. except Exception as e:
  6699. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  6700. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  6701. # In this case poly_obj creation (see above) will fail
  6702. log.debug("App.selection_area_handler() --> %s" % str(e))
  6703. def select_objects(self, key=None):
  6704. # list where we store the overlapped objects under our mouse left click position
  6705. objects_under_the_click_list = []
  6706. # Populate the list with the overlapped objects on the click position
  6707. curr_x, curr_y = self.pos
  6708. for obj in self.all_objects_list:
  6709. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  6710. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  6711. if obj.options['name'] not in objects_under_the_click_list:
  6712. if obj.options['plot']:
  6713. # add objects to the objects_under_the_click list only if the object is plotted
  6714. # (active and not disabled)
  6715. objects_under_the_click_list.append(obj.options['name'])
  6716. try:
  6717. # If there is no element in the overlapped objects list then make everyone inactive
  6718. # because we selected "nothing"
  6719. if not objects_under_the_click_list:
  6720. self.collection.set_all_inactive()
  6721. # delete the possible selection box around a possible selected object
  6722. self.delete_selection_shape()
  6723. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  6724. # only when working on App
  6725. if self.call_source == 'app':
  6726. if self.click_noproject is False:
  6727. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6728. else:
  6729. # restore auto open the Project Tab
  6730. self.click_noproject = False
  6731. # delete any text in the status bar, implicitly the last object name that was selected
  6732. self.inform.emit("")
  6733. else:
  6734. self.call_source = 'app'
  6735. else:
  6736. # case when there is only an object under the click and we toggle it
  6737. if len(objects_under_the_click_list) == 1:
  6738. if self.collection.get_active() is None:
  6739. self.collection.set_active(objects_under_the_click_list[0])
  6740. # create the selection box around the selected object
  6741. curr_sel_obj = self.collection.get_active()
  6742. if self.defaults['global_selection_shape'] is True:
  6743. self.draw_selection_shape(curr_sel_obj)
  6744. # self.inform.emit('[selected] %s: %s selected' %
  6745. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6746. if curr_sel_obj.kind == 'gerber':
  6747. self.inform.emit(
  6748. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6749. color='green', name=str(curr_sel_obj.options['name'])))
  6750. elif curr_sel_obj.kind == 'excellon':
  6751. self.inform.emit(
  6752. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6753. color='brown', name=str(curr_sel_obj.options['name'])))
  6754. elif curr_sel_obj.kind == 'cncjob':
  6755. self.inform.emit(
  6756. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6757. color='blue', name=str(curr_sel_obj.options['name'])))
  6758. elif curr_sel_obj.kind == 'geometry':
  6759. self.inform.emit(
  6760. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6761. color='red', name=str(curr_sel_obj.options['name'])))
  6762. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  6763. self.collection.set_all_inactive()
  6764. self.delete_selection_shape()
  6765. self.collection.set_active(objects_under_the_click_list[0])
  6766. # create the selection box around the selected object
  6767. curr_sel_obj = self.collection.get_active()
  6768. if self.defaults['global_selection_shape'] is True:
  6769. self.draw_selection_shape(curr_sel_obj)
  6770. # self.inform.emit('[selected] %s: %s selected' %
  6771. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6772. if curr_sel_obj.kind == 'gerber':
  6773. self.inform.emit(
  6774. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6775. color='green', name=str(curr_sel_obj.options['name'])))
  6776. elif curr_sel_obj.kind == 'excellon':
  6777. self.inform.emit(
  6778. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6779. color='brown', name=str(curr_sel_obj.options['name'])))
  6780. elif curr_sel_obj.kind == 'cncjob':
  6781. self.inform.emit(
  6782. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6783. color='blue', name=str(curr_sel_obj.options['name'])))
  6784. elif curr_sel_obj.kind == 'geometry':
  6785. self.inform.emit(
  6786. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6787. color='red', name=str(curr_sel_obj.options['name'])))
  6788. else:
  6789. self.collection.set_all_inactive()
  6790. self.delete_selection_shape()
  6791. if self.call_source == 'app':
  6792. # delete any text in the status bar, implicitly the last object name that was selected
  6793. self.inform.emit("")
  6794. else:
  6795. self.call_source = 'app'
  6796. else:
  6797. # If there is no selected object
  6798. # make active the first element of the overlapped objects list
  6799. if self.collection.get_active() is None:
  6800. self.collection.set_active(objects_under_the_click_list[0])
  6801. name_sel_obj = self.collection.get_active().options['name']
  6802. # In case that there is a selected object but it is not in the overlapped object list
  6803. # make that object inactive and activate the first element in the overlapped object list
  6804. if name_sel_obj not in objects_under_the_click_list:
  6805. self.collection.set_inactive(name_sel_obj)
  6806. name_sel_obj = objects_under_the_click_list[0]
  6807. self.collection.set_active(name_sel_obj)
  6808. else:
  6809. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  6810. self.collection.set_all_inactive()
  6811. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  6812. len(objects_under_the_click_list)])
  6813. curr_sel_obj = self.collection.get_active()
  6814. # delete the possible selection box around a possible selected object
  6815. self.delete_selection_shape()
  6816. # create the selection box around the selected object
  6817. if self.defaults['global_selection_shape'] is True:
  6818. self.draw_selection_shape(curr_sel_obj)
  6819. # self.inform.emit('[selected] %s: %s selected' %
  6820. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6821. if curr_sel_obj.kind == 'gerber':
  6822. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6823. color='green', name=str(curr_sel_obj.options['name'])))
  6824. elif curr_sel_obj.kind == 'excellon':
  6825. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6826. color='brown', name=str(curr_sel_obj.options['name'])))
  6827. elif curr_sel_obj.kind == 'cncjob':
  6828. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6829. color='blue', name=str(curr_sel_obj.options['name'])))
  6830. elif curr_sel_obj.kind == 'geometry':
  6831. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6832. color='red', name=str(curr_sel_obj.options['name'])))
  6833. # for obj in self.collection.get_list():
  6834. # obj.plot()
  6835. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  6836. # TODO: on selected objects change the object colors and do not draw the selection box
  6837. # self.plotcanvas.update() # this updates the canvas
  6838. except Exception as e:
  6839. log.error("[ERROR] Something went bad. %s" % str(e))
  6840. return
  6841. def delete_hover_shape(self):
  6842. self.hover_shapes.clear()
  6843. self.hover_shapes.redraw()
  6844. def draw_hover_shape(self, sel_obj, color=None):
  6845. """
  6846. :param sel_obj: the object for which the hover shape must be drawn
  6847. :return:
  6848. """
  6849. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6850. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6851. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6852. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6853. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  6854. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6855. hover_rect = hover_rect.buffer(-0.1)
  6856. hover_rect = hover_rect.buffer(0.2)
  6857. else:
  6858. hover_rect = hover_rect.buffer(-0.00393)
  6859. hover_rect = hover_rect.buffer(0.00787)
  6860. # if color:
  6861. # face = Color(color)
  6862. # face.alpha = 0.2
  6863. # outline = Color(color, alpha=0.8)
  6864. # else:
  6865. # face = Color(self.defaults['global_sel_fill'])
  6866. # face.alpha = 0.2
  6867. # outline = self.defaults['global_sel_line']
  6868. if color:
  6869. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  6870. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  6871. else:
  6872. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  6873. outline = self.defaults['global_sel_line']
  6874. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  6875. if self.is_legacy is True:
  6876. self.hover_shapes.redraw()
  6877. def delete_selection_shape(self):
  6878. self.move_tool.sel_shapes.clear()
  6879. self.move_tool.sel_shapes.redraw()
  6880. def draw_selection_shape(self, sel_obj, color=None):
  6881. """
  6882. :param sel_obj: the object for which the selection shape must be drawn
  6883. :return:
  6884. """
  6885. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6886. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6887. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6888. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6889. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6890. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6891. sel_rect = sel_rect.buffer(-0.1)
  6892. sel_rect = sel_rect.buffer(0.2)
  6893. else:
  6894. sel_rect = sel_rect.buffer(-0.00393)
  6895. sel_rect = sel_rect.buffer(0.00787)
  6896. # if color:
  6897. # face = Color(color, alpha=0.2)
  6898. # outline = Color(color, alpha=0.8)
  6899. # else:
  6900. # face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  6901. # outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  6902. if color:
  6903. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  6904. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  6905. else:
  6906. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  6907. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  6908. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  6909. color=outline,
  6910. face_color=face,
  6911. update=True,
  6912. layer=0,
  6913. tolerance=None))
  6914. if self.is_legacy is True:
  6915. self.move_tool.sel_shapes.redraw()
  6916. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  6917. """
  6918. :param old_coords: old coordinates
  6919. :param coords: new coordinates
  6920. :return:
  6921. """
  6922. if 'color' in kwargs:
  6923. color = kwargs['color']
  6924. else:
  6925. color = self.defaults['global_sel_line']
  6926. if 'face_color' in kwargs:
  6927. face_color = kwargs['face_color']
  6928. else:
  6929. face_color = self.defaults['global_sel_fill']
  6930. if 'face_alpha' in kwargs:
  6931. face_alpha = kwargs['face_alpha']
  6932. else:
  6933. face_alpha = 0.3
  6934. x0, y0 = old_coords
  6935. x1, y1 = coords
  6936. pt1 = (x0, y0)
  6937. pt2 = (x1, y0)
  6938. pt3 = (x1, y1)
  6939. pt4 = (x0, y1)
  6940. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6941. # color_t = Color(face_color)
  6942. # color_t.alpha = face_alpha
  6943. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  6944. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  6945. layer=0, tolerance=None)
  6946. if self.is_legacy is True:
  6947. self.move_tool.sel_shapes.redraw()
  6948. def on_file_new_click(self):
  6949. if self.collection.get_list() and self.should_we_save:
  6950. msgbox = QtWidgets.QMessageBox()
  6951. # msgbox.setText("<B>Save changes ...</B>")
  6952. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  6953. "Creating a New project will delete them.\n"
  6954. "Do you want to Save the project?"))
  6955. msgbox.setWindowTitle(_("Save changes"))
  6956. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6957. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6958. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6959. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6960. msgbox.setDefaultButton(bt_yes)
  6961. msgbox.exec_()
  6962. response = msgbox.clickedButton()
  6963. if response == bt_yes:
  6964. self.on_file_saveprojectas()
  6965. elif response == bt_cancel:
  6966. return
  6967. elif response == bt_no:
  6968. self.on_file_new()
  6969. else:
  6970. self.on_file_new()
  6971. self.inform.emit('[success] %s...' %
  6972. _("New Project created"))
  6973. def on_file_new(self, cli=None):
  6974. """
  6975. Callback for menu item File->New. Returns the application to its
  6976. startup state. This method is thread-safe.
  6977. :return: None
  6978. """
  6979. self.report_usage("on_file_new")
  6980. # Remove everything from memory
  6981. App.log.debug("on_file_new()")
  6982. if self.call_source != 'app':
  6983. self.editor2object(cleanup=True)
  6984. # ## EDITOR section
  6985. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  6986. self.exc_editor = FlatCAMExcEditor(self)
  6987. self.grb_editor = FlatCAMGrbEditor(self)
  6988. # Clear pool
  6989. self.clear_pool()
  6990. for obj in self.collection.get_list():
  6991. # delete shapes left drawn from mark shape_collections, if any
  6992. if isinstance(obj, FlatCAMGerber):
  6993. try:
  6994. obj.mark_shapes.enabled = False
  6995. obj.mark_shapes.clear(update=True)
  6996. except AttributeError:
  6997. pass
  6998. # also delete annotation shapes, if any
  6999. elif isinstance(obj, FlatCAMCNCjob):
  7000. try:
  7001. obj.annotation.enabled = False
  7002. obj.annotation.clear(update=True)
  7003. except AttributeError:
  7004. pass
  7005. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7006. self.init_tcl()
  7007. self.delete_selection_shape()
  7008. self.collection.delete_all()
  7009. self.setup_component_editor()
  7010. # Clear project filename
  7011. self.project_filename = None
  7012. # Load the application defaults
  7013. self.load_defaults(filename='current_defaults')
  7014. # Re-fresh project options
  7015. self.on_options_app2project()
  7016. # Init Tools
  7017. self.init_tools()
  7018. if cli is None:
  7019. # Close any Tabs opened in the Plot Tab Area section
  7020. for index in range(self.ui.plot_tab_area.count()):
  7021. self.ui.plot_tab_area.closeTab(index)
  7022. # for whatever reason previous command does not close the last tab so I do it manually
  7023. self.ui.plot_tab_area.closeTab(0)
  7024. # # And then add again the Plot Area
  7025. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  7026. self.ui.plot_tab_area.protectTab(0)
  7027. # take the focus of the Notebook on Project Tab.
  7028. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7029. self.set_ui_title(name=_("New Project - Not saved"))
  7030. def obj_properties(self):
  7031. self.report_usage("obj_properties()")
  7032. self.properties_tool.run(toggle=False)
  7033. def on_project_context_save(self):
  7034. obj = self.collection.get_active()
  7035. if type(obj) == FlatCAMGeometry:
  7036. self.on_file_exportdxf()
  7037. elif type(obj) == FlatCAMExcellon:
  7038. self.on_file_saveexcellon()
  7039. elif type(obj) == FlatCAMCNCjob:
  7040. obj.on_exportgcode_button_click()
  7041. elif type(obj) == FlatCAMGerber:
  7042. self.on_file_savegerber()
  7043. def obj_move(self):
  7044. self.report_usage("obj_move()")
  7045. self.move_tool.run(toggle=False)
  7046. def on_fileopengerber(self, checked=None, name=None):
  7047. """
  7048. File menu callback for opening a Gerber.
  7049. :return: None
  7050. """
  7051. self.report_usage("on_fileopengerber")
  7052. App.log.debug("on_fileopengerber()")
  7053. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  7054. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  7055. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  7056. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  7057. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  7058. "*.mil);;" \
  7059. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  7060. "Allegro Files (*.art);;" \
  7061. "Mentor Files (*.pho *.gdo);;" \
  7062. "All Files (*.*)"
  7063. if name is None:
  7064. try:
  7065. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  7066. directory=self.get_last_folder(),
  7067. filter=_filter_)
  7068. except TypeError:
  7069. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  7070. filenames = [str(filename) for filename in filenames]
  7071. else:
  7072. filenames = [name]
  7073. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7074. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7075. _("Opening Gerber file.")),
  7076. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7077. color=QtGui.QColor("gray"))
  7078. if len(filenames) == 0:
  7079. self.inform.emit('[WARNING_NOTCL] %s' %
  7080. _("Open Gerber cancelled."))
  7081. else:
  7082. for filename in filenames:
  7083. if filename != '':
  7084. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  7085. def on_fileopenexcellon(self, checked=None, name=None):
  7086. """
  7087. File menu callback for opening an Excellon file.
  7088. :return: None
  7089. """
  7090. self.report_usage("on_fileopenexcellon")
  7091. App.log.debug("on_fileopenexcellon()")
  7092. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  7093. "All Files (*.*)"
  7094. if name is None:
  7095. try:
  7096. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  7097. directory=self.get_last_folder(),
  7098. filter=_filter_)
  7099. except TypeError:
  7100. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  7101. filenames = [str(filename) for filename in filenames]
  7102. else:
  7103. filenames = [str(name)]
  7104. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7105. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7106. _("Opening Excellon file.")),
  7107. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7108. color=QtGui.QColor("gray"))
  7109. if len(filenames) == 0:
  7110. self.inform.emit('[WARNING_NOTCL]%s' %
  7111. _(" Open Excellon cancelled."))
  7112. else:
  7113. for filename in filenames:
  7114. if filename != '':
  7115. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  7116. def on_fileopengcode(self, checked=None, name=None):
  7117. """
  7118. File menu call back for opening gcode.
  7119. :return: None
  7120. """
  7121. self.report_usage("on_fileopengcode")
  7122. App.log.debug("on_fileopengcode()")
  7123. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  7124. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  7125. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  7126. "All Files (*.*)"
  7127. if name is None:
  7128. try:
  7129. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  7130. directory=self.get_last_folder(),
  7131. filter=_filter_)
  7132. except TypeError:
  7133. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  7134. filenames = [str(filename) for filename in filenames]
  7135. else:
  7136. filenames = [name]
  7137. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7138. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7139. _("Opening G-Code file.")),
  7140. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7141. color=QtGui.QColor("gray"))
  7142. if len(filenames) == 0:
  7143. self.inform.emit('[WARNING_NOTCL] %s' %
  7144. _("Open G-Code cancelled."))
  7145. else:
  7146. for filename in filenames:
  7147. if filename != '':
  7148. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename]})
  7149. def on_file_openproject(self, checked=None):
  7150. """
  7151. File menu callback for opening a project.
  7152. :return: None
  7153. """
  7154. self.report_usage("on_file_openproject")
  7155. App.log.debug("on_file_openproject()")
  7156. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  7157. try:
  7158. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  7159. directory=self.get_last_folder(), filter=_filter_)
  7160. except TypeError:
  7161. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  7162. # The Qt methods above will return a QString which can cause problems later.
  7163. # So far json.dump() will fail to serialize it.
  7164. # TODO: Improve the serialization methods and remove this fix.
  7165. filename = str(filename)
  7166. if filename == "":
  7167. self.inform.emit('[WARNING_NOTCL] %s' %
  7168. _("Open Project cancelled."))
  7169. else:
  7170. # self.worker_task.emit({'fcn': self.open_project,
  7171. # 'params': [filename]})
  7172. # The above was failing because open_project() is not
  7173. # thread safe. The new_project()
  7174. self.open_project(filename)
  7175. def on_file_openconfig(self, checked=None):
  7176. """
  7177. File menu callback for opening a config file.
  7178. :return: None
  7179. """
  7180. self.report_usage("on_file_openconfig")
  7181. App.log.debug("on_file_openconfig()")
  7182. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  7183. try:
  7184. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7185. directory=self.data_path, filter=_filter_)
  7186. except TypeError:
  7187. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7188. filter=_filter_)
  7189. if filename == "":
  7190. self.inform.emit('[WARNING_NOTCL] %s' %
  7191. _("Open Config cancelled."))
  7192. else:
  7193. self.open_config_file(filename)
  7194. def on_file_exportsvg(self):
  7195. """
  7196. Callback for menu item File->Export SVG.
  7197. :return: None
  7198. """
  7199. self.report_usage("on_file_exportsvg")
  7200. App.log.debug("on_file_exportsvg()")
  7201. obj = self.collection.get_active()
  7202. if obj is None:
  7203. self.inform.emit('[WARNING_NOTCL] %s' %
  7204. _("No object selected."))
  7205. msg = _("Please Select a Geometry object to export")
  7206. msgbox = QtWidgets.QMessageBox()
  7207. msgbox.setInformativeText(msg)
  7208. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7209. msgbox.setDefaultButton(bt_ok)
  7210. msgbox.exec_()
  7211. return
  7212. # Check for more compatible types and add as required
  7213. if (not isinstance(obj, FlatCAMGeometry)
  7214. and not isinstance(obj, FlatCAMGerber)
  7215. and not isinstance(obj, FlatCAMCNCjob)
  7216. and not isinstance(obj, FlatCAMExcellon)):
  7217. msg = '[ERROR_NOTCL] %s' % \
  7218. _("Only Geometry, Gerber and CNCJob objects can be used.")
  7219. msgbox = QtWidgets.QMessageBox()
  7220. msgbox.setInformativeText(msg)
  7221. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7222. msgbox.setDefaultButton(bt_ok)
  7223. msgbox.exec_()
  7224. return
  7225. name = obj.options["name"]
  7226. _filter = "SVG File (*.svg);;All Files (*.*)"
  7227. try:
  7228. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7229. caption=_("Export SVG"),
  7230. directory=self.get_last_save_folder() + '/' + str(name),
  7231. filter=_filter)
  7232. except TypeError:
  7233. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  7234. filename = str(filename)
  7235. if filename == "":
  7236. self.inform.emit('[WARNING_NOTCL]%s' %
  7237. _(" Export SVG cancelled."))
  7238. return
  7239. else:
  7240. self.export_svg(name, filename)
  7241. if self.defaults["global_open_style"] is False:
  7242. self.file_opened.emit("SVG", filename)
  7243. self.file_saved.emit("SVG", filename)
  7244. def on_file_exportpng(self):
  7245. self.report_usage("on_file_exportpng")
  7246. App.log.debug("on_file_exportpng()")
  7247. self.date = str(datetime.today()).rpartition('.')[0]
  7248. self.date = ''.join(c for c in self.date if c not in ':-')
  7249. self.date = self.date.replace(' ', '_')
  7250. image = _screenshot()
  7251. data = np.asarray(image)
  7252. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  7253. self.inform.emit('[[WARNING_NOTCL]] %s' %
  7254. _('Data must be a 3D array with last dimension 3 or 4'))
  7255. return
  7256. filter_ = "PNG File (*.png);;All Files (*.*)"
  7257. try:
  7258. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7259. caption=_("Export PNG Image"),
  7260. directory=self.get_last_save_folder() + '/png_' + self.date,
  7261. filter=filter_)
  7262. except TypeError:
  7263. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  7264. filename = str(filename)
  7265. if filename == "":
  7266. self.inform.emit(_("Export PNG cancelled."))
  7267. return
  7268. else:
  7269. write_png(filename, data)
  7270. if self.defaults["global_open_style"] is False:
  7271. self.file_opened.emit("png", filename)
  7272. self.file_saved.emit("png", filename)
  7273. def on_file_savegerber(self):
  7274. """
  7275. Callback for menu item in Project context menu.
  7276. :return: None
  7277. """
  7278. self.report_usage("on_file_savegerber")
  7279. App.log.debug("on_file_savegerber()")
  7280. obj = self.collection.get_active()
  7281. if obj is None:
  7282. self.inform.emit('[WARNING_NOTCL] %s' %
  7283. _("No object selected. Please select an Gerber object to export."))
  7284. return
  7285. # Check for more compatible types and add as required
  7286. if not isinstance(obj, FlatCAMGerber):
  7287. self.inform.emit('[ERROR_NOTCL] %s' %
  7288. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7289. return
  7290. name = self.collection.get_active().options["name"]
  7291. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  7292. try:
  7293. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7294. caption="Save Gerber source file",
  7295. directory=self.get_last_save_folder() + '/' + name,
  7296. filter=_filter)
  7297. except TypeError:
  7298. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  7299. filename = str(filename)
  7300. if filename == "":
  7301. self.inform.emit('[WARNING_NOTCL] %s' %
  7302. _("Save Gerber source file cancelled."))
  7303. return
  7304. else:
  7305. self.save_source_file(name, filename)
  7306. if self.defaults["global_open_style"] is False:
  7307. self.file_opened.emit("Gerber", filename)
  7308. self.file_saved.emit("Gerber", filename)
  7309. def on_file_saveexcellon(self):
  7310. """
  7311. Callback for menu item in project context menu.
  7312. :return: None
  7313. """
  7314. self.report_usage("on_file_saveexcellon")
  7315. App.log.debug("on_file_saveexcellon()")
  7316. obj = self.collection.get_active()
  7317. if obj is None:
  7318. self.inform.emit('[WARNING_NOTCL] %s' %
  7319. _("No object selected. Please select an Excellon object to export."))
  7320. return
  7321. # Check for more compatible types and add as required
  7322. if not isinstance(obj, FlatCAMExcellon):
  7323. self.inform.emit('[ERROR_NOTCL] %s' %
  7324. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7325. return
  7326. name = self.collection.get_active().options["name"]
  7327. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7328. try:
  7329. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7330. caption=_("Save Excellon source file"),
  7331. directory=self.get_last_save_folder() + '/' + name,
  7332. filter=_filter)
  7333. except TypeError:
  7334. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  7335. filename = str(filename)
  7336. if filename == "":
  7337. self.inform.emit('[WARNING_NOTCL] %s' %
  7338. _("Saving Excellon source file cancelled."))
  7339. return
  7340. else:
  7341. self.save_source_file(name, filename)
  7342. if self.defaults["global_open_style"] is False:
  7343. self.file_opened.emit("Excellon", filename)
  7344. self.file_saved.emit("Excellon", filename)
  7345. def on_file_exportexcellon(self):
  7346. """
  7347. Callback for menu item File->Export->Excellon.
  7348. :return: None
  7349. """
  7350. self.report_usage("on_file_exportexcellon")
  7351. App.log.debug("on_file_exportexcellon()")
  7352. obj = self.collection.get_active()
  7353. if obj is None:
  7354. self.inform.emit('[WARNING_NOTCL] %s' %
  7355. _("No object selected. Please Select an Excellon object to export."))
  7356. return
  7357. # Check for more compatible types and add as required
  7358. if not isinstance(obj, FlatCAMExcellon):
  7359. self.inform.emit('[ERROR_NOTCL] %s' %
  7360. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7361. return
  7362. name = self.collection.get_active().options["name"]
  7363. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7364. try:
  7365. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7366. caption=_("Export Excellon"),
  7367. directory=self.get_last_save_folder() + '/' + name,
  7368. filter=_filter)
  7369. except TypeError:
  7370. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  7371. filename = str(filename)
  7372. if filename == "":
  7373. self.inform.emit('[WARNING_NOTCL] %s' %
  7374. _("Export Excellon cancelled."))
  7375. return
  7376. else:
  7377. self.export_excellon(name, filename)
  7378. if self.defaults["global_open_style"] is False:
  7379. self.file_opened.emit("Excellon", filename)
  7380. self.file_saved.emit("Excellon", filename)
  7381. def on_file_exportgerber(self):
  7382. """
  7383. Callback for menu item File->Export->Gerber.
  7384. :return: None
  7385. """
  7386. self.report_usage("on_file_exportgerber")
  7387. App.log.debug("on_file_exportgerber()")
  7388. obj = self.collection.get_active()
  7389. if obj is None:
  7390. self.inform.emit('[WARNING_NOTCL] %s' %
  7391. _("No object selected. Please Select an Gerber object to export."))
  7392. return
  7393. # Check for more compatible types and add as required
  7394. if not isinstance(obj, FlatCAMGerber):
  7395. self.inform.emit('[ERROR_NOTCL] %s' %
  7396. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7397. return
  7398. name = self.collection.get_active().options["name"]
  7399. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  7400. try:
  7401. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7402. caption=_("Export Gerber"),
  7403. directory=self.get_last_save_folder() + '/' + name,
  7404. filter=_filter_)
  7405. except TypeError:
  7406. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  7407. filename = str(filename)
  7408. if filename == "":
  7409. self.inform.emit('[WARNING_NOTCL] %s' %
  7410. _("Export Gerber cancelled."))
  7411. return
  7412. else:
  7413. self.export_gerber(name, filename)
  7414. if self.defaults["global_open_style"] is False:
  7415. self.file_opened.emit("Gerber", filename)
  7416. self.file_saved.emit("Gerber", filename)
  7417. def on_file_exportdxf(self):
  7418. """
  7419. Callback for menu item File->Export DXF.
  7420. :return: None
  7421. """
  7422. self.report_usage("on_file_exportdxf")
  7423. App.log.debug("on_file_exportdxf()")
  7424. obj = self.collection.get_active()
  7425. if obj is None:
  7426. self.inform.emit('[WARNING_NOTCL] %s' %
  7427. _("No object selected."))
  7428. msg = _("Please Select a Geometry object to export")
  7429. msgbox = QtWidgets.QMessageBox()
  7430. msgbox.setInformativeText(msg)
  7431. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7432. msgbox.setDefaultButton(bt_ok)
  7433. msgbox.exec_()
  7434. return
  7435. # Check for more compatible types and add as required
  7436. if not isinstance(obj, FlatCAMGeometry):
  7437. msg = '[ERROR_NOTCL] %s' % \
  7438. _("Only Geometry objects can be used.")
  7439. msgbox = QtWidgets.QMessageBox()
  7440. msgbox.setInformativeText(msg)
  7441. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7442. msgbox.setDefaultButton(bt_ok)
  7443. msgbox.exec_()
  7444. return
  7445. name = self.collection.get_active().options["name"]
  7446. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7447. try:
  7448. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7449. caption=_("Export DXF"),
  7450. directory=self.get_last_save_folder() + '/' + name,
  7451. filter=_filter_)
  7452. except TypeError:
  7453. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  7454. filter=_filter_)
  7455. filename = str(filename)
  7456. if filename == "":
  7457. self.inform.emit('[WARNING_NOTCL] %s' %
  7458. _("Export DXF cancelled."))
  7459. return
  7460. else:
  7461. self.export_dxf(name, filename)
  7462. if self.defaults["global_open_style"] is False:
  7463. self.file_opened.emit("DXF", filename)
  7464. self.file_saved.emit("DXF", filename)
  7465. def on_file_importsvg(self, type_of_obj):
  7466. """
  7467. Callback for menu item File->Import SVG.
  7468. :param type_of_obj: to import the SVG as Geometry or as Gerber
  7469. :type type_of_obj: str
  7470. :return: None
  7471. """
  7472. self.report_usage("on_file_importsvg")
  7473. App.log.debug("on_file_importsvg()")
  7474. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  7475. try:
  7476. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7477. directory=self.get_last_folder(), filter=_filter_)
  7478. except TypeError:
  7479. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7480. filter=_filter_)
  7481. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7482. type_of_obj = "geometry"
  7483. filenames = [str(filename) for filename in filenames]
  7484. if len(filenames) == 0:
  7485. self.inform.emit('[WARNING_NOTCL] %s' %
  7486. _("Open SVG cancelled."))
  7487. else:
  7488. for filename in filenames:
  7489. if filename != '':
  7490. self.worker_task.emit({'fcn': self.import_svg,
  7491. 'params': [filename, type_of_obj]})
  7492. def on_file_importdxf(self, type_of_obj):
  7493. """
  7494. Callback for menu item File->Import DXF.
  7495. :param type_of_obj: to import the DXF as Geometry or as Gerber
  7496. :type type_of_obj: str
  7497. :return: None
  7498. """
  7499. self.report_usage("on_file_importdxf")
  7500. App.log.debug("on_file_importdxf()")
  7501. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7502. try:
  7503. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7504. directory=self.get_last_folder(),
  7505. filter=_filter_)
  7506. except TypeError:
  7507. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7508. filter=_filter_)
  7509. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7510. type_of_obj = "geometry"
  7511. filenames = [str(filename) for filename in filenames]
  7512. if len(filenames) == 0:
  7513. self.inform.emit('[WARNING_NOTCL] %s' %
  7514. _("Open DXF cancelled."))
  7515. else:
  7516. for filename in filenames:
  7517. if filename != '':
  7518. self.worker_task.emit({'fcn': self.import_dxf,
  7519. 'params': [filename, type_of_obj]})
  7520. # ###############################################################################################################
  7521. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  7522. # ###############################################################################################################
  7523. def init_code_editor(self, name):
  7524. # Signals section
  7525. # Disconnect the old signals
  7526. try:
  7527. self.ui.buttonOpen.clicked.disconnect()
  7528. except TypeError:
  7529. pass
  7530. try:
  7531. self.ui.buttonSave.clicked.disconnect()
  7532. except TypeError:
  7533. pass
  7534. # add the tab if it was closed
  7535. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, '%s' % name)
  7536. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  7537. # delete the absolute and relative position and messages in the infobar
  7538. self.ui.position_label.setText("")
  7539. self.ui.rel_position_label.setText("")
  7540. # first clear previous text in text editor (if any)
  7541. self.ui.code_editor.clear()
  7542. self.ui.code_editor.setReadOnly(False)
  7543. self.toggle_codeeditor = True
  7544. self.ui.code_editor.completer_enable = False
  7545. self.ui.buttonRun.hide()
  7546. # make sure to keep a reference to the code editor
  7547. self.reference_code_editor = self.ui.code_editor
  7548. # Switch plot_area to CNCJob tab
  7549. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  7550. def on_view_source(self):
  7551. self.inform.emit('%s' %
  7552. _("Viewing the source code of the selected object."))
  7553. self.proc_container.view.set_busy(_("Loading..."))
  7554. try:
  7555. obj = self.collection.get_active()
  7556. except Exception as e:
  7557. log.debug("App.on_view_source() --> %s" % str(e))
  7558. self.inform.emit('[WARNING_NOTCL] %s' %
  7559. _("Select an Gerber or Excellon file to view it's source file."))
  7560. return 'fail'
  7561. if obj.kind == 'gerber':
  7562. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  7563. elif obj.kind == 'excellon':
  7564. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  7565. elif obj.kind == 'cncjob':
  7566. "GCode Files (*.NC);;All Files (*.*)"
  7567. else:
  7568. flt = "All Files (*.*)"
  7569. self.init_code_editor(name=_("Source Editor"))
  7570. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  7571. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  7572. # then append the text from GCode to the text editor
  7573. if obj.kind == 'cncjob':
  7574. try:
  7575. file = obj.export_gcode(
  7576. preamble=self.defaults["cncjob_prepend"],
  7577. postamble=self.defaults["cncjob_append"],
  7578. to_file=True)
  7579. if file == 'fail':
  7580. return 'fail'
  7581. except AttributeError:
  7582. self.inform.emit('[WARNING_NOTCL] %s' %
  7583. _("There is no selected object for which to see it's source file code."))
  7584. return 'fail'
  7585. else:
  7586. try:
  7587. file = StringIO(obj.source_file)
  7588. except AttributeError:
  7589. self.inform.emit('[WARNING_NOTCL] %s' %
  7590. _("There is no selected object for which to see it's source file code."))
  7591. return 'fail'
  7592. self.ui.cncjob_frame.hide()
  7593. try:
  7594. for line in file:
  7595. QtWidgets.QApplication.processEvents()
  7596. proc_line = str(line).strip('\n')
  7597. self.ui.code_editor.append(proc_line)
  7598. except Exception as e:
  7599. log.debug('App.on_view_source() -->%s' % str(e))
  7600. self.inform.emit('[ERROR] %s: %s' %
  7601. (_('Failed to load the source code for the selected object'), str(e)))
  7602. return
  7603. self.handleTextChanged()
  7604. self.ui.cncjob_frame.show()
  7605. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7606. self.proc_container.view.set_idle()
  7607. # self.ui.show()
  7608. def on_toggle_code_editor(self):
  7609. self.report_usage("on_toggle_code_editor()")
  7610. if self.toggle_codeeditor is False:
  7611. self.init_code_editor(name=_("Code Editor"))
  7612. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  7613. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  7614. else:
  7615. for idx in range(self.ui.plot_tab_area.count()):
  7616. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  7617. self.ui.plot_tab_area.closeTab(idx)
  7618. break
  7619. self.toggle_codeeditor = False
  7620. def on_filenewscript(self, silent=False):
  7621. """
  7622. Will create a new script file and open it in the Code Editor
  7623. :param silent: if True will not display status messages
  7624. :return: None
  7625. """
  7626. if silent is False:
  7627. self.inform.emit('[success] %s' %
  7628. _("New TCL script file created in Code Editor."))
  7629. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  7630. self.init_code_editor(name=_("Script Editor"))
  7631. self.ui.code_editor.completer_enable = True
  7632. self.ui.code_editor.append(_(
  7633. "#\n"
  7634. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  7635. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  7636. "#\n\n"
  7637. "# FlatCAM commands list:\n"
  7638. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, ClearCopper,\n"
  7639. "# Cncjob, Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, GetNames,\n"
  7640. "# GetSys, ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillDrills,\n"
  7641. "# MillSlots, Mirror, New, NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"
  7642. "# Options, Paint, Panelize, Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, SubtractPoly,\n"
  7643. "# SubtractRectangle, Version, WriteGCode\n"
  7644. "#\n\n"
  7645. ))
  7646. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  7647. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  7648. self.ui.buttonRun.show()
  7649. try:
  7650. self.ui.buttonRun.clicked.disconnect(self.handleRunCode)
  7651. except TypeError:
  7652. pass
  7653. self.ui.buttonRun.clicked.connect(self.handleRunCode)
  7654. self.handleTextChanged()
  7655. self.ui.code_editor.show()
  7656. def on_fileopenscript(self, name=None, silent=False):
  7657. """
  7658. Will open a Tcl script file into the Code Editor
  7659. :param silent: if True will not display status messages
  7660. :param name: name of a Tcl script file to open
  7661. :return:
  7662. """
  7663. if name:
  7664. filename = name
  7665. else:
  7666. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7667. try:
  7668. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  7669. directory=self.get_last_folder(), filter=_filter_)
  7670. except TypeError:
  7671. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  7672. # The Qt methods above will return a QString which can cause problems later.
  7673. # So far json.dump() will fail to serialize it.
  7674. # TODO: Improve the serialization methods and remove this fix.
  7675. filename = str(filename)
  7676. if filename == "":
  7677. if silent is False:
  7678. self.inform.emit('[WARNING_NOTCL] %s' %
  7679. _("Open TCL script cancelled."))
  7680. else:
  7681. self.on_filenewscript()
  7682. try:
  7683. with open(filename, "r") as opened_script:
  7684. try:
  7685. for line in opened_script:
  7686. proc_line = str(line).strip('\n')
  7687. self.ui.code_editor.append(proc_line)
  7688. except Exception as e:
  7689. log.debug('App.on_fileopenscript() -->%s' % str(e))
  7690. if silent is False:
  7691. self.inform.emit('[ERROR] %s %s' %
  7692. ('App.on_fileopenscript() -->', str(e)))
  7693. return
  7694. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7695. self.handleTextChanged()
  7696. if silent is False:
  7697. self.inform.emit('[success] %s' %
  7698. _("TCL script file opened in Code Editor."))
  7699. # self.ui.show()
  7700. except Exception as e:
  7701. log.debug("App.on_fileopenscript() -> %s" % str(e))
  7702. def on_filerunscript(self, name=None, silent=False):
  7703. """
  7704. File menu callback for loading and running a TCL script.
  7705. :param silent: if True will not display status messages
  7706. :param name: name of a Tcl script file to be run by FlatCAM
  7707. :return: None
  7708. """
  7709. self.report_usage("on_filerunscript")
  7710. App.log.debug("on_file_runscript()")
  7711. if name:
  7712. filename = name
  7713. if self.cmd_line_headless != 1:
  7714. self.splash.showMessage('%s: %ssec\n%s' %
  7715. (_("Canvas initialization started.\n"
  7716. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7717. _("Executing FlatCAMScript file.")
  7718. ),
  7719. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7720. color=QtGui.QColor("gray"))
  7721. else:
  7722. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7723. try:
  7724. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  7725. directory=self.get_last_folder(), filter=_filter_)
  7726. except TypeError:
  7727. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  7728. # The Qt methods above will return a QString which can cause problems later.
  7729. # So far json.dump() will fail to serialize it.
  7730. # TODO: Improve the serialization methods and remove this fix.
  7731. filename = str(filename)
  7732. if filename == "":
  7733. if silent is False:
  7734. self.inform.emit('[WARNING_NOTCL] %s' %
  7735. _("Run TCL script cancelled."))
  7736. else:
  7737. if self.cmd_line_headless != 1:
  7738. if self.ui.shell_dock.isHidden():
  7739. self.ui.shell_dock.show()
  7740. try:
  7741. with open(filename, "r") as tcl_script:
  7742. cmd_line_shellfile_content = tcl_script.read()
  7743. if self.cmd_line_headless != 1:
  7744. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  7745. else:
  7746. self.shell._sysShell.exec_command(cmd_line_shellfile_content, no_echo=True)
  7747. if silent is False:
  7748. self.inform.emit('[success] %s' %
  7749. _("TCL script file opened in Code Editor and executed."))
  7750. except Exception as e:
  7751. log.debug("App.on_filerunscript() -> %s" % str(e))
  7752. sys.exit(2)
  7753. def on_file_saveproject(self, silent=False):
  7754. """
  7755. Callback for menu item File->Save Project. Saves the project to
  7756. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7757. if set to None. The project is saved by calling ``self.save_project()``.
  7758. :param silent: if True will not display status messages
  7759. :return: None
  7760. """
  7761. self.report_usage("on_file_saveproject")
  7762. if self.project_filename is None:
  7763. self.on_file_saveprojectas()
  7764. else:
  7765. self.worker_task.emit({'fcn': self.save_project,
  7766. 'params': [self.project_filename, silent]})
  7767. if self.defaults["global_open_style"] is False:
  7768. self.file_opened.emit("project", self.project_filename)
  7769. self.file_saved.emit("project", self.project_filename)
  7770. self.set_ui_title(name=self.project_filename)
  7771. self.should_we_save = False
  7772. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7773. """
  7774. Callback for menu item File->Save Project As... Opens a file
  7775. chooser and saves the project to the given file via
  7776. ``self.save_project()``.
  7777. :param make_copy if to be create a copy of the project; boolean
  7778. :param use_thread: if to be run in a separate thread; boolean
  7779. :param quit_action: if to be followed by quiting the application; boolean
  7780. :return: None
  7781. """
  7782. self.report_usage("on_file_saveprojectas")
  7783. self.date = str(datetime.today()).rpartition('.')[0]
  7784. self.date = ''.join(c for c in self.date if c not in ':-')
  7785. self.date = self.date.replace(' ', '_')
  7786. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  7787. try:
  7788. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7789. caption=_("Save Project As ..."),
  7790. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  7791. filter=filter_)
  7792. except TypeError:
  7793. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  7794. filename = str(filename)
  7795. if filename == '':
  7796. self.inform.emit('[WARNING_NOTCL] %s' %
  7797. _("Save Project cancelled."))
  7798. return
  7799. try:
  7800. f = open(filename, 'r')
  7801. f.close()
  7802. except IOError:
  7803. pass
  7804. if use_thread is True:
  7805. self.worker_task.emit({'fcn': self.save_project,
  7806. 'params': [filename, quit_action]})
  7807. else:
  7808. self.save_project(filename, quit_action)
  7809. # self.save_project(filename)
  7810. if self.defaults["global_open_style"] is False:
  7811. self.file_opened.emit("project", filename)
  7812. self.file_saved.emit("project", filename)
  7813. if not make_copy:
  7814. self.project_filename = filename
  7815. self.set_ui_title(name=self.project_filename)
  7816. self.should_we_save = False
  7817. def export_svg(self, obj_name, filename, scale_factor=0.00):
  7818. """
  7819. Exports a Geometry Object to an SVG file.
  7820. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7821. :param filename: Path to the SVG file to save to.
  7822. :param scale_factor: factor by which to change/scale the thickness of the features
  7823. :return:
  7824. """
  7825. self.report_usage("export_svg()")
  7826. if filename is None:
  7827. filename = self.defaults["global_last_save_folder"]
  7828. self.log.debug("export_svg()")
  7829. try:
  7830. obj = self.collection.get_by_name(str(obj_name))
  7831. except:
  7832. # TODO: The return behavior has not been established... should raise exception?
  7833. return "Could not retrieve object: %s" % obj_name
  7834. with self.proc_container.new(_("Exporting SVG")) as proc:
  7835. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7836. # Determine bounding area for svg export
  7837. bounds = obj.bounds()
  7838. size = obj.size()
  7839. # Convert everything to strings for use in the xml doc
  7840. svgwidth = str(size[0])
  7841. svgheight = str(size[1])
  7842. minx = str(bounds[0])
  7843. miny = str(bounds[1] - size[1])
  7844. uom = obj.units.lower()
  7845. # Add a SVG Header and footer to the svg output from shapely
  7846. # The transform flips the Y Axis so that everything renders
  7847. # properly within svg apps such as inkscape
  7848. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7849. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7850. svg_header += 'width="' + svgwidth + uom + '" '
  7851. svg_header += 'height="' + svgheight + uom + '" '
  7852. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7853. svg_header += '<g transform="scale(1,-1)">'
  7854. svg_footer = '</g> </svg>'
  7855. svg_elem = svg_header + exported_svg + svg_footer
  7856. # Parse the xml through a xml parser just to add line feeds
  7857. # and to make it look more pretty for the output
  7858. svgcode = parse_xml_string(svg_elem)
  7859. try:
  7860. with open(filename, 'w') as fp:
  7861. fp.write(svgcode.toprettyxml())
  7862. except PermissionError:
  7863. self.inform.emit('[WARNING] %s' %
  7864. _("Permission denied, saving not possible.\n"
  7865. "Most likely another app is holding the file open and not accessible."))
  7866. return 'fail'
  7867. if self.defaults["global_open_style"] is False:
  7868. self.file_opened.emit("SVG", filename)
  7869. self.file_saved.emit("SVG", filename)
  7870. self.inform.emit('[success] %s: %s' %
  7871. (_("SVG file exported to"), filename))
  7872. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  7873. """
  7874. Exports a Geometry Object to an SVG file in negative.
  7875. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7876. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  7877. :param filename: Path to the SVG file to save to.
  7878. :param boundary: thickness of a black border to surround all the features
  7879. :param scale_factor: factor by which to change/scale the thickness of the features
  7880. :param use_thread: if to be run in a separate thread; boolean
  7881. :return:
  7882. """
  7883. self.report_usage("export_negative()")
  7884. if filename is None:
  7885. filename = self.defaults["global_last_save_folder"]
  7886. self.log.debug("export_svg() negative")
  7887. try:
  7888. obj = self.collection.get_by_name(str(obj_name))
  7889. except:
  7890. # TODO: The return behavior has not been established... should raise exception?
  7891. return "Could not retrieve object: %s" % obj_name
  7892. try:
  7893. box = self.collection.get_by_name(str(box_name))
  7894. except:
  7895. # TODO: The return behavior has not been established... should raise exception?
  7896. return "Could not retrieve object: %s" % box_name
  7897. if box is None:
  7898. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  7899. (_("No object Box. Using instead"), obj))
  7900. box = obj
  7901. def make_negative_film():
  7902. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7903. # Determine bounding area for svg export
  7904. bounds = box.bounds()
  7905. size = box.size()
  7906. uom = obj.units.lower()
  7907. # Convert everything to strings for use in the xml doc
  7908. svgwidth = str(size[0] + (2 * boundary))
  7909. svgheight = str(size[1] + (2 * boundary))
  7910. minx = str(bounds[0] - boundary)
  7911. miny = str(bounds[1] + boundary + size[1])
  7912. miny_rect = str(bounds[1] - boundary)
  7913. # Add a SVG Header and footer to the svg output from shapely
  7914. # The transform flips the Y Axis so that everything renders
  7915. # properly within svg apps such as inkscape
  7916. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7917. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7918. svg_header += 'width="' + svgwidth + uom + '" '
  7919. svg_header += 'height="' + svgheight + uom + '" '
  7920. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7921. svg_header += '>'
  7922. svg_header += '<g transform="scale(1,-1)">'
  7923. svg_footer = '</g> </svg>'
  7924. # Change the attributes of the exported SVG
  7925. # We don't need stroke-width - wrong, we do when we have lines with certain width
  7926. # We set opacity to maximum
  7927. # We set the color to WHITE
  7928. root = ET.fromstring(exported_svg)
  7929. for child in root:
  7930. child.set('fill', '#FFFFFF')
  7931. child.set('opacity', '1.0')
  7932. child.set('stroke', '#FFFFFF')
  7933. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  7934. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  7935. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  7936. first_svg_elem_tag = 'rect'
  7937. first_svg_elem_attribs = {
  7938. 'x': minx,
  7939. 'y': miny_rect,
  7940. 'width': svgwidth,
  7941. 'height': svgheight,
  7942. 'id': 'neg_rect',
  7943. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  7944. }
  7945. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  7946. exported_svg = ET.tostring(root)
  7947. svg_elem = svg_header + str(exported_svg) + svg_footer
  7948. # Parse the xml through a xml parser just to add line feeds
  7949. # and to make it look more pretty for the output
  7950. doc = parse_xml_string(svg_elem)
  7951. try:
  7952. with open(filename, 'w') as fp:
  7953. fp.write(doc.toprettyxml())
  7954. except PermissionError:
  7955. self.inform.emit('[WARNING] %s' %
  7956. _("Permission denied, saving not possible.\n"
  7957. "Most likely another app is holding the file open and not accessible."))
  7958. return 'fail'
  7959. if self.defaults["global_open_style"] is False:
  7960. self.file_opened.emit("SVG", filename)
  7961. self.file_saved.emit("SVG", filename)
  7962. self.inform.emit('[success] %s: %s' %
  7963. (_("SVG file exported to"), filename))
  7964. if use_thread is True:
  7965. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  7966. def job_thread_film(app_obj):
  7967. try:
  7968. make_negative_film()
  7969. except Exception as e:
  7970. proc.done()
  7971. return
  7972. proc.done()
  7973. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  7974. else:
  7975. make_negative_film()
  7976. def export_svg_positive(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  7977. """
  7978. Exports a Geometry Object to an SVG file in positive black.
  7979. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7980. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  7981. :param filename: Path to the SVG file to save to.
  7982. :param scale_factor: factor by which to change/scale the thickness of the features
  7983. :param use_thread: if to be run in a separate thread; boolean
  7984. :return:
  7985. """
  7986. self.report_usage("export_svg_positive()")
  7987. if filename is None:
  7988. filename = self.defaults["global_last_save_folder"]
  7989. self.log.debug("export_svg() black")
  7990. try:
  7991. obj = self.collection.get_by_name(str(obj_name))
  7992. except:
  7993. # TODO: The return behavior has not been established... should raise exception?
  7994. return "Could not retrieve object: %s" % obj_name
  7995. try:
  7996. box = self.collection.get_by_name(str(box_name))
  7997. except:
  7998. # TODO: The return behavior has not been established... should raise exception?
  7999. return "Could not retrieve object: %s" % box_name
  8000. if box is None:
  8001. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  8002. (_("No object Box. Using instead"), obj))
  8003. box = obj
  8004. def make_positive_film():
  8005. exported_svg = obj.export_svg(scale_factor=scale_factor)
  8006. self.progress.emit(40)
  8007. # Change the attributes of the exported SVG
  8008. # We don't need stroke-width
  8009. # We set opacity to maximum
  8010. # We set the colour to WHITE
  8011. root = ET.fromstring(exported_svg)
  8012. for child in root:
  8013. child.set('fill', str(self.defaults['tools_film_color']))
  8014. child.set('opacity', '1.0')
  8015. child.set('stroke', str(self.defaults['tools_film_color']))
  8016. exported_svg = ET.tostring(root)
  8017. # Determine bounding area for svg export
  8018. bounds = box.bounds()
  8019. size = box.size()
  8020. # This contain the measure units
  8021. uom = obj.units.lower()
  8022. # Define a boundary around SVG of about 1.0mm (~39mils)
  8023. if uom in "mm":
  8024. boundary = 1.0
  8025. else:
  8026. boundary = 0.0393701
  8027. self.progress.emit(80)
  8028. # Convert everything to strings for use in the xml doc
  8029. svgwidth = str(size[0] + (2 * boundary))
  8030. svgheight = str(size[1] + (2 * boundary))
  8031. minx = str(bounds[0] - boundary)
  8032. miny = str(bounds[1] + boundary + size[1])
  8033. self.log.debug(minx)
  8034. self.log.debug(miny)
  8035. # Add a SVG Header and footer to the svg output from shapely
  8036. # The transform flips the Y Axis so that everything renders
  8037. # properly within svg apps such as inkscape
  8038. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8039. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8040. svg_header += 'width="' + svgwidth + uom + '" '
  8041. svg_header += 'height="' + svgheight + uom + '" '
  8042. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  8043. svg_header += '>'
  8044. svg_header += '<g transform="scale(1,-1)">'
  8045. svg_footer = '</g> </svg>'
  8046. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  8047. self.progress.emit(90)
  8048. # Parse the xml through a xml parser just to add line feeds
  8049. # and to make it look more pretty for the output
  8050. doc = parse_xml_string(svg_elem)
  8051. try:
  8052. with open(filename, 'w') as fp:
  8053. fp.write(doc.toprettyxml())
  8054. except PermissionError:
  8055. self.inform.emit('[WARNING] %s' %
  8056. _("Permission denied, saving not possible.\n"
  8057. "Most likely another app is holding the file open and not accessible."))
  8058. return 'fail'
  8059. self.progress.emit(100)
  8060. if self.defaults["global_open_style"] is False:
  8061. self.file_opened.emit("SVG", filename)
  8062. self.file_saved.emit("SVG", filename)
  8063. self.inform.emit('[success] %s: %s' %
  8064. (_("SVG file exported to"), filename))
  8065. if use_thread is True:
  8066. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  8067. def job_thread_film(app_obj):
  8068. try:
  8069. make_positive_film()
  8070. except Exception as e:
  8071. proc.done()
  8072. return
  8073. proc.done()
  8074. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  8075. else:
  8076. make_positive_film()
  8077. def save_source_file(self, obj_name, filename, use_thread=True):
  8078. """
  8079. Exports a FlatCAM Object to an Gerber/Excellon file.
  8080. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8081. :param filename: Path to the Gerber file to save to.
  8082. :param use_thread: if to be run in a separate thread
  8083. :return:
  8084. """
  8085. self.report_usage("save source file()")
  8086. if filename is None:
  8087. filename = self.defaults["global_last_save_folder"]
  8088. self.log.debug("save source file()")
  8089. obj = self.collection.get_by_name(obj_name)
  8090. file_string = StringIO(obj.source_file)
  8091. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8092. try:
  8093. with open(filename, 'w') as file:
  8094. file.writelines('G04*\n')
  8095. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8096. (obj.kind.upper(), str(self.version), str(self.version_date)))
  8097. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8098. file.writelines('G04 Created on : %s*\n' % time_string)
  8099. for line in file_string:
  8100. file.writelines(line)
  8101. except PermissionError:
  8102. self.inform.emit('[WARNING] %s' %
  8103. _("Permission denied, saving not possible.\n"
  8104. "Most likely another app is holding the file open and not accessible."))
  8105. return 'fail'
  8106. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  8107. """
  8108. Exports a Excellon Object to an Excellon file.
  8109. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  8110. :param filename: Path to the Excellon file to save to.
  8111. :param use_thread: if to be run in a separate thread
  8112. :return:
  8113. """
  8114. self.report_usage("export_excellon()")
  8115. if filename is None:
  8116. filename = self.defaults["global_last_save_folder"]
  8117. self.log.debug("export_excellon()")
  8118. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  8119. self.defaults["excellon_exp_decimals"]
  8120. )
  8121. units = ''
  8122. if local_use is None:
  8123. try:
  8124. obj = self.collection.get_by_name(str(obj_name))
  8125. except:
  8126. # TODO: The return behavior has not been established... should raise exception?
  8127. return "Could not retrieve object: %s" % obj_name
  8128. else:
  8129. obj = local_use
  8130. # updated units
  8131. eunits = self.defaults["excellon_exp_units"]
  8132. ewhole = self.defaults["excellon_exp_integer"]
  8133. efract = self.defaults["excellon_exp_decimals"]
  8134. ezeros = self.defaults["excellon_exp_zeros"]
  8135. eformat = self.defaults["excellon_exp_format"]
  8136. slot_type = self.defaults["excellon_exp_slot_type"]
  8137. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8138. if fc_units == 'MM':
  8139. factor = 1 if eunits == 'METRIC' else 0.03937
  8140. else:
  8141. factor = 25.4 if eunits == 'METRIC' else 1
  8142. def make_excellon():
  8143. try:
  8144. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8145. header = 'M48\n'
  8146. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  8147. (str(self.version), str(self.version_date))
  8148. header += ';Filename: %s' % str(obj_name) + '\n'
  8149. header += ';Created on : %s' % time_str + '\n'
  8150. if eformat == 'dec':
  8151. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  8152. header += eunits + '\n'
  8153. for tool in obj.tools:
  8154. if eunits == 'METRIC':
  8155. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8156. tool=str(tool),
  8157. dec=2)
  8158. else:
  8159. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8160. tool=str(tool),
  8161. dec=4)
  8162. else:
  8163. if ezeros == 'LZ':
  8164. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8165. form='ndec', e_zeros='LZ', factor=factor,
  8166. slot_type=slot_type)
  8167. header += '%s,%s\n' % (eunits, 'LZ')
  8168. header += format_exc
  8169. for tool in obj.tools:
  8170. if eunits == 'METRIC':
  8171. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8172. tool=str(tool),
  8173. dec=2)
  8174. else:
  8175. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8176. tool=str(tool),
  8177. dec=4)
  8178. else:
  8179. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8180. form='ndec', e_zeros='TZ', factor=factor,
  8181. slot_type=slot_type)
  8182. header += '%s,%s\n' % (eunits, 'TZ')
  8183. header += format_exc
  8184. for tool in obj.tools:
  8185. if eunits == 'METRIC':
  8186. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8187. tool=str(tool),
  8188. dec=2)
  8189. else:
  8190. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8191. tool=str(tool),
  8192. dec=4)
  8193. header += '%\n'
  8194. footer = 'M30\n'
  8195. exported_excellon = header
  8196. exported_excellon += excellon_code
  8197. exported_excellon += footer
  8198. if local_use is None:
  8199. try:
  8200. with open(filename, 'w') as fp:
  8201. fp.write(exported_excellon)
  8202. except PermissionError:
  8203. self.inform.emit('[WARNING] %s' %
  8204. _("Permission denied, saving not possible.\n"
  8205. "Most likely another app is holding the file open and not accessible."))
  8206. return 'fail'
  8207. if self.defaults["global_open_style"] is False:
  8208. self.file_opened.emit("Excellon", filename)
  8209. self.file_saved.emit("Excellon", filename)
  8210. self.inform.emit('[success] %s: %s' %
  8211. (_("Excellon file exported to"), filename))
  8212. else:
  8213. return exported_excellon
  8214. except Exception as e:
  8215. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  8216. return 'fail'
  8217. if use_thread is True:
  8218. with self.proc_container.new(_("Exporting Excellon")) as proc:
  8219. def job_thread_exc(app_obj):
  8220. ret = make_excellon()
  8221. if ret == 'fail':
  8222. self.inform.emit('[ERROR_NOTCL] %s' %
  8223. _('Could not export Excellon file.'))
  8224. return
  8225. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8226. else:
  8227. ret = make_excellon()
  8228. if ret == 'fail':
  8229. self.inform.emit('[ERROR_NOTCL] %s' %
  8230. _('Could not export Excellon file.'))
  8231. return 'fail'
  8232. if local_use is not None:
  8233. return ret
  8234. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  8235. """
  8236. Exports a Gerber Object to an Gerber file.
  8237. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  8238. :param filename: Path to the Gerber file to save to.
  8239. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8240. When not None, the value will be the actual Gerber object for which to create the Gerber code
  8241. :param use_thread: if to be run in a separate thread
  8242. :return:
  8243. """
  8244. self.report_usage("export_gerber()")
  8245. if filename is None:
  8246. filename = self.defaults["global_last_save_folder"]
  8247. self.log.debug("export_gerber()")
  8248. if local_use is None:
  8249. try:
  8250. obj = self.collection.get_by_name(str(obj_name))
  8251. except:
  8252. # TODO: The return behavior has not been established... should raise exception?
  8253. return "Could not retrieve object: %s" % obj_name
  8254. else:
  8255. obj = local_use
  8256. # updated units
  8257. gunits = self.defaults["gerber_exp_units"]
  8258. gwhole = self.defaults["gerber_exp_integer"]
  8259. gfract = self.defaults["gerber_exp_decimals"]
  8260. gzeros = self.defaults["gerber_exp_zeros"]
  8261. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8262. if fc_units == 'MM':
  8263. factor = 1 if gunits == 'MM' else 0.03937
  8264. else:
  8265. factor = 25.4 if gunits == 'MM' else 1
  8266. def make_gerber():
  8267. try:
  8268. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8269. header = 'G04*\n'
  8270. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  8271. (str(self.version), str(self.version_date))
  8272. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  8273. header += 'G04 Created on : %s*' % time_str + '\n'
  8274. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  8275. header += "%MO{units}*%\n".format(units=gunits)
  8276. for apid in obj.apertures:
  8277. if obj.apertures[apid]['type'] == 'C':
  8278. header += "%ADD{apid}{type},{size}*%\n".format(
  8279. apid=str(apid),
  8280. type='C',
  8281. size=(factor * obj.apertures[apid]['size'])
  8282. )
  8283. elif obj.apertures[apid]['type'] == 'R':
  8284. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8285. apid=str(apid),
  8286. type='R',
  8287. width=(factor * obj.apertures[apid]['width']),
  8288. height=(factor * obj.apertures[apid]['height'])
  8289. )
  8290. elif obj.apertures[apid]['type'] == 'O':
  8291. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8292. apid=str(apid),
  8293. type='O',
  8294. width=(factor * obj.apertures[apid]['width']),
  8295. height=(factor * obj.apertures[apid]['height'])
  8296. )
  8297. header += '\n'
  8298. # obsolete units but some software may need it
  8299. if gunits == 'IN':
  8300. header += 'G70*\n'
  8301. else:
  8302. header += 'G71*\n'
  8303. # Absolute Mode
  8304. header += 'G90*\n'
  8305. header += 'G01*\n'
  8306. # positive polarity
  8307. header += '%LPD*%\n'
  8308. footer = 'M02*\n'
  8309. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8310. exported_gerber = header
  8311. exported_gerber += gerber_code
  8312. exported_gerber += footer
  8313. if local_use is None:
  8314. try:
  8315. with open(filename, 'w') as fp:
  8316. fp.write(exported_gerber)
  8317. except PermissionError:
  8318. self.inform.emit('[WARNING] %s' %
  8319. _("Permission denied, saving not possible.\n"
  8320. "Most likely another app is holding the file open and not accessible."))
  8321. return 'fail'
  8322. if self.defaults["global_open_style"] is False:
  8323. self.file_opened.emit("Gerber", filename)
  8324. self.file_saved.emit("Gerber", filename)
  8325. self.inform.emit('[success] %s: %s' %
  8326. (_("Gerber file exported to"), filename))
  8327. else:
  8328. return exported_gerber
  8329. except Exception as e:
  8330. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8331. return 'fail'
  8332. if use_thread is True:
  8333. with self.proc_container.new(_("Exporting Gerber")) as proc:
  8334. def job_thread_grb(app_obj):
  8335. ret = make_gerber()
  8336. if ret == 'fail':
  8337. self.inform.emit('[ERROR_NOTCL] %s' %
  8338. _('Could not export Gerber file.'))
  8339. return
  8340. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8341. else:
  8342. ret = make_gerber()
  8343. if ret == 'fail':
  8344. self.inform.emit('[ERROR_NOTCL] %s' %
  8345. _('Could not export Gerber file.'))
  8346. return 'fail'
  8347. if local_use is not None:
  8348. return ret
  8349. def export_dxf(self, obj_name, filename, use_thread=True):
  8350. """
  8351. Exports a Geometry Object to an DXF file.
  8352. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8353. :param filename: Path to the DXF file to save to.
  8354. :param use_thread: if to be run in a separate thread
  8355. :return:
  8356. """
  8357. self.report_usage("export_dxf()")
  8358. if filename is None:
  8359. filename = self.defaults["global_last_save_folder"]
  8360. self.log.debug("export_dxf()")
  8361. format_exc = ''
  8362. units = ''
  8363. try:
  8364. obj = self.collection.get_by_name(str(obj_name))
  8365. except:
  8366. # TODO: The return behavior has not been established... should raise exception?
  8367. return "Could not retrieve object: %s" % obj_name
  8368. # updated units
  8369. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8370. if units == 'IN' or units == 'INCH':
  8371. units = 'INCH'
  8372. elif units == 'MM' or units == 'METIRC':
  8373. units ='METRIC'
  8374. def make_dxf():
  8375. try:
  8376. dxf_code = obj.export_dxf()
  8377. dxf_code.saveas(filename)
  8378. if self.defaults["global_open_style"] is False:
  8379. self.file_opened.emit("DXF", filename)
  8380. self.file_saved.emit("DXF", filename)
  8381. self.inform.emit('[success] %s: %s' %
  8382. (_("DXF file exported to"), filename))
  8383. except:
  8384. return 'fail'
  8385. if use_thread is True:
  8386. with self.proc_container.new(_("Exporting DXF")) as proc:
  8387. def job_thread_exc(app_obj):
  8388. ret = make_dxf()
  8389. if ret == 'fail':
  8390. app_obj.inform.emit('[WARNING_NOTCL] %s' %
  8391. _('Could not export DXF file.'))
  8392. return
  8393. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8394. else:
  8395. ret = make_dxf()
  8396. if ret == 'fail':
  8397. self.inform.emit('[WARNING_NOTCL] %s' %
  8398. _('Could not export DXF file.'))
  8399. return
  8400. def import_svg(self, filename, geo_type='geometry', outname=None):
  8401. """
  8402. Adds a new Geometry Object to the projects and populates
  8403. it with shapes extracted from the SVG file.
  8404. :param filename: Path to the SVG file.
  8405. :param outname:
  8406. :return:
  8407. """
  8408. self.report_usage("import_svg()")
  8409. obj_type = ""
  8410. if geo_type is None or geo_type == "geometry":
  8411. obj_type = "geometry"
  8412. elif geo_type == "gerber":
  8413. obj_type = geo_type
  8414. else:
  8415. self.inform.emit('[ERROR_NOTCL] %s' %
  8416. _("Not supported type is picked as parameter. "
  8417. "Only Geometry and Gerber are supported"))
  8418. return
  8419. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8420. def obj_init(geo_obj, app_obj):
  8421. geo_obj.import_svg(filename, obj_type, units=units)
  8422. geo_obj.multigeo = False
  8423. with self.proc_container.new(_("Importing SVG")) as proc:
  8424. # Object name
  8425. name = outname or filename.split('/')[-1].split('\\')[-1]
  8426. self.new_object(obj_type, name, obj_init, autoselected=False)
  8427. self.progress.emit(20)
  8428. # Register recent file
  8429. self.file_opened.emit("svg", filename)
  8430. # GUI feedback
  8431. self.inform.emit('[success] %s: %s' %
  8432. (_("Opened"), filename))
  8433. self.progress.emit(100)
  8434. def import_dxf(self, filename, geo_type='geometry', outname=None):
  8435. """
  8436. Adds a new Geometry Object to the projects and populates
  8437. it with shapes extracted from the DXF file.
  8438. :param filename: Path to the DXF file.
  8439. :param outname:
  8440. :type putname: str
  8441. :return:
  8442. """
  8443. self.report_usage("import_dxf()")
  8444. obj_type = ""
  8445. if geo_type is None or geo_type == "geometry":
  8446. obj_type = "geometry"
  8447. elif geo_type == "gerber":
  8448. obj_type = geo_type
  8449. else:
  8450. self.inform.emit('[ERROR_NOTCL] %s' %
  8451. _("Not supported type is picked as parameter. "
  8452. "Only Geometry and Gerber are supported"))
  8453. return
  8454. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8455. def obj_init(geo_obj, app_obj):
  8456. geo_obj.import_dxf(filename, obj_type, units=units)
  8457. geo_obj.multigeo = False
  8458. with self.proc_container.new(_("Importing DXF")) as proc:
  8459. # Object name
  8460. name = outname or filename.split('/')[-1].split('\\')[-1]
  8461. self.new_object(obj_type, name, obj_init, autoselected=False)
  8462. self.progress.emit(20)
  8463. # Register recent file
  8464. self.file_opened.emit("dxf", filename)
  8465. # GUI feedback
  8466. self.inform.emit('[success] %s: %s' %
  8467. (_("Opened"), filename))
  8468. self.progress.emit(100)
  8469. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  8470. """
  8471. Adds a new Geometry Object to the projects and populates
  8472. it with shapes extracted from the SVG file.
  8473. :param filename: Path to the SVG file.
  8474. :param o_type: type of FlatCAM objeect
  8475. :param dpi: dot per inch
  8476. :param mode: black or color
  8477. :param mask: dictate the level of detail
  8478. :param outname: name for the resulting file
  8479. :return:
  8480. """
  8481. self.report_usage("import_image()")
  8482. if o_type is None or o_type == "geometry":
  8483. obj_type = "geometry"
  8484. elif o_type == "gerber":
  8485. obj_type = o_type
  8486. else:
  8487. self.inform.emit('[ERROR_NOTCL] %s' %
  8488. _("Not supported type is picked as parameter. "
  8489. "Only Geometry and Gerber are supported"))
  8490. return
  8491. def obj_init(geo_obj, app_obj):
  8492. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  8493. geo_obj.multigeo = False
  8494. with self.proc_container.new(_("Importing Image")) as proc:
  8495. # Object name
  8496. name = outname or filename.split('/')[-1].split('\\')[-1]
  8497. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  8498. self.new_object(obj_type, name, obj_init)
  8499. self.progress.emit(20)
  8500. # Register recent file
  8501. self.file_opened.emit("image", filename)
  8502. # GUI feedback
  8503. self.inform.emit('[success] %s: %s' %
  8504. (_("Opened"), filename))
  8505. self.progress.emit(100)
  8506. def open_gerber(self, filename, outname=None):
  8507. """
  8508. Opens a Gerber file, parses it and creates a new object for
  8509. it in the program. Thread-safe.
  8510. :param outname: Name of the resulting object. None causes the
  8511. name to be that of the file.
  8512. :param filename: Gerber file filename
  8513. :type filename: str
  8514. :param follow: If true, the parser will not create polygons, just lines
  8515. following the gerber path.
  8516. :type follow: bool
  8517. :return: None
  8518. """
  8519. # How the object should be initialized
  8520. def obj_init(gerber_obj, app_obj):
  8521. assert isinstance(gerber_obj, FlatCAMGerber), \
  8522. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  8523. # Opening the file happens here
  8524. self.progress.emit(30)
  8525. try:
  8526. gerber_obj.parse_file(filename)
  8527. except IOError:
  8528. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8529. (_("Failed to open file"), filename))
  8530. app_obj.progress.emit(0)
  8531. return "fail"
  8532. except ParseError as err:
  8533. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' %
  8534. (_("Failed to parse file"), filename, str(err)))
  8535. app_obj.progress.emit(0)
  8536. self.log.error(str(err))
  8537. return "fail"
  8538. except Exception as e:
  8539. log.debug("App.open_gerber() --> %s" % str(e))
  8540. msg = '[ERROR] %s' % \
  8541. _("An internal error has occurred. See shell.\n")
  8542. msg += traceback.format_exc()
  8543. app_obj.inform.emit(msg)
  8544. return "fail"
  8545. if gerber_obj.is_empty():
  8546. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  8547. # self.collection.set_active(gerber_obj.options["name"])
  8548. # self.collection.delete_active()
  8549. self.inform.emit('[ERROR_NOTCL] %s' %
  8550. _("Object is not Gerber file or empty. Aborting object creation."))
  8551. return "fail"
  8552. # Further parsing
  8553. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  8554. App.log.debug("open_gerber()")
  8555. with self.proc_container.new(_("Opening Gerber")) as proc:
  8556. self.progress.emit(10)
  8557. # Object name
  8558. name = outname or filename.split('/')[-1].split('\\')[-1]
  8559. # # ## Object creation # ##
  8560. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  8561. if ret == 'fail':
  8562. self.inform.emit('[ERROR_NOTCL]%s' %
  8563. _(' Open Gerber failed. Probable not a Gerber file.'))
  8564. return
  8565. # Register recent file
  8566. self.file_opened.emit("gerber", filename)
  8567. self.progress.emit(100)
  8568. # GUI feedback
  8569. self.inform.emit('[success] %s: %s' %
  8570. (_("Opened"), filename))
  8571. def open_excellon(self, filename, outname=None, plot=True):
  8572. """
  8573. Opens an Excellon file, parses it and creates a new object for
  8574. it in the program. Thread-safe.
  8575. :param outname: Name of the resulting object. None causes the
  8576. name to be that of the file.
  8577. :param filename: Excellon file filename
  8578. :type filename: str
  8579. :return: None
  8580. """
  8581. App.log.debug("open_excellon()")
  8582. # How the object should be initialized
  8583. def obj_init(excellon_obj, app_obj):
  8584. # self.progress.emit(20)
  8585. try:
  8586. ret = excellon_obj.parse_file(filename=filename)
  8587. if ret == "fail":
  8588. log.debug("Excellon parsing failed.")
  8589. self.inform.emit('[ERROR_NOTCL] %s' %
  8590. _("This is not Excellon file."))
  8591. return "fail"
  8592. except IOError:
  8593. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8594. (_("Cannot open file"), filename))
  8595. log.debug("Could not open Excellon object.")
  8596. self.progress.emit(0) # TODO: self and app_bjj mixed
  8597. return "fail"
  8598. except:
  8599. msg = '[ERROR_NOTCL] %s' % \
  8600. _("An internal error has occurred. See shell.\n")
  8601. msg += traceback.format_exc()
  8602. app_obj.inform.emit(msg)
  8603. return "fail"
  8604. ret = excellon_obj.create_geometry()
  8605. if ret == 'fail':
  8606. log.debug("Could not create geometry for Excellon object.")
  8607. return "fail"
  8608. for tool in excellon_obj.tools:
  8609. if excellon_obj.tools[tool]['solid_geometry']:
  8610. return
  8611. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8612. (_("No geometry found in file"), filename))
  8613. return "fail"
  8614. with self.proc_container.new(_("Opening Excellon.")):
  8615. # Object name
  8616. name = outname or filename.split('/')[-1].split('\\')[-1]
  8617. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8618. if ret_val == 'fail':
  8619. self.inform.emit('[ERROR_NOTCL] %s' %
  8620. _('Open Excellon file failed. Probable not an Excellon file.'))
  8621. return
  8622. # Register recent file
  8623. self.file_opened.emit("excellon", filename)
  8624. # GUI feedback
  8625. self.inform.emit('[success] %s: %s' %
  8626. (_("Opened"), filename))
  8627. def open_gcode(self, filename, outname=None, plot=True):
  8628. """
  8629. Opens a G-gcode file, parses it and creates a new object for
  8630. it in the program. Thread-safe.
  8631. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8632. :param filename: G-code file filename
  8633. :type filename: str
  8634. :return: None
  8635. """
  8636. App.log.debug("open_gcode()")
  8637. # How the object should be initialized
  8638. def obj_init(job_obj, app_obj_):
  8639. """
  8640. :param job_obj: the resulting object
  8641. :type app_obj_: App
  8642. """
  8643. assert isinstance(app_obj_, App), \
  8644. "Initializer expected App, got %s" % type(app_obj_)
  8645. self.progress.emit(10)
  8646. try:
  8647. f = open(filename)
  8648. gcode = f.read()
  8649. f.close()
  8650. except IOError:
  8651. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  8652. (_("Failed to open"), filename))
  8653. self.progress.emit(0)
  8654. return "fail"
  8655. job_obj.gcode = gcode
  8656. self.progress.emit(20)
  8657. ret = job_obj.gcode_parse()
  8658. if ret == "fail":
  8659. self.inform.emit('[ERROR_NOTCL] %s' %
  8660. _("This is not GCODE"))
  8661. return "fail"
  8662. self.progress.emit(60)
  8663. job_obj.create_geometry()
  8664. with self.proc_container.new(_("Opening G-Code.")):
  8665. # Object name
  8666. name = outname or filename.split('/')[-1].split('\\')[-1]
  8667. # New object creation and file processing
  8668. ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8669. if ret == 'fail':
  8670. self.inform.emit('[ERROR_NOTCL] %s' %
  8671. _("Failed to create CNCJob Object. Probable not a GCode file.\n "
  8672. "Attempting to create a FlatCAM CNCJob Object from "
  8673. "G-Code file failed during processing"))
  8674. return "fail"
  8675. # Register recent file
  8676. self.file_opened.emit("cncjob", filename)
  8677. # GUI feedback
  8678. self.inform.emit('[success] %s: %s' %
  8679. (_("Opened"), filename))
  8680. self.progress.emit(100)
  8681. def open_config_file(self, filename, run_from_arg=None):
  8682. """
  8683. Loads a config file from the specified file.
  8684. :param filename: Name of the file from which to load.
  8685. :type filename: str
  8686. :return: None
  8687. """
  8688. App.log.debug("Opening config file: " + filename)
  8689. if run_from_arg:
  8690. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8691. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8692. _("Opening FlatCAM Config file.")),
  8693. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8694. color=QtGui.QColor("gray"))
  8695. # add the tab if it was closed
  8696. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  8697. # first clear previous text in text editor (if any)
  8698. self.ui.code_editor.clear()
  8699. # Switch plot_area to CNCJob tab
  8700. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  8701. try:
  8702. if filename:
  8703. f = QtCore.QFile(filename)
  8704. if f.open(QtCore.QIODevice.ReadOnly):
  8705. stream = QtCore.QTextStream(f)
  8706. gcode_edited = stream.readAll()
  8707. self.ui.code_editor.setPlainText(gcode_edited)
  8708. f.close()
  8709. except IOError:
  8710. App.log.error("Failed to open config file: %s" % filename)
  8711. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8712. (_("Failed to open config file"), filename))
  8713. return
  8714. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  8715. """
  8716. Loads a project from the specified file.
  8717. 1) Loads and parses file
  8718. 2) Registers the file as recently opened.
  8719. 3) Calls on_file_new()
  8720. 4) Updates options
  8721. 5) Calls new_object() with the object's from_dict() as init method.
  8722. 6) Calls plot_all() if plot=True
  8723. :param filename: Name of the file from which to load.
  8724. :type filename: str
  8725. :param run_from_arg: True if run for arguments
  8726. :param plot: If True plot all objects in the project
  8727. :param cli: run from command line
  8728. :return: None
  8729. """
  8730. App.log.debug("Opening project: " + filename)
  8731. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8732. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8733. if cli is None:
  8734. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8735. if run_from_arg:
  8736. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8737. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8738. _("Opening FlatCAM Project file.")),
  8739. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8740. color=QtGui.QColor("gray"))
  8741. # Open and parse an uncompressed Project file
  8742. try:
  8743. f = open(filename, 'r')
  8744. except IOError:
  8745. App.log.error("Failed to open project file: %s" % filename)
  8746. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8747. (_("Failed to open project file"), filename))
  8748. return
  8749. try:
  8750. d = json.load(f, object_hook=dict2obj)
  8751. except Exception as e:
  8752. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8753. (filename, str(e)))
  8754. f.close()
  8755. # Open and parse a compressed Project file
  8756. try:
  8757. with lzma.open(filename) as f:
  8758. file_content = f.read().decode('utf-8')
  8759. d = json.loads(file_content, object_hook=dict2obj)
  8760. except Exception as e:
  8761. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8762. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8763. (_("Failed to open project file"), filename))
  8764. return
  8765. # Clear the current project
  8766. # # NOT THREAD SAFE # ##
  8767. if run_from_arg is True:
  8768. pass
  8769. elif cli is True:
  8770. self.delete_selection_shape()
  8771. else:
  8772. self.on_file_new()
  8773. # Project options
  8774. self.options.update(d['options'])
  8775. self.project_filename = filename
  8776. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8777. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8778. if cli is None:
  8779. self.set_screen_units(self.options["units"])
  8780. # Re create objects
  8781. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8782. for obj in d['objs']:
  8783. def obj_init(obj_inst, app_inst):
  8784. obj_inst.from_dict(obj)
  8785. App.log.debug("Recreating from opened project an %s object: %s" %
  8786. (obj['kind'].capitalize(), obj['options']['name']))
  8787. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8788. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8789. if cli is None:
  8790. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8791. obj['kind'].upper(),
  8792. obj['options']['name']
  8793. )
  8794. )
  8795. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  8796. self.inform.emit('[success] %s: %s' %
  8797. (_("Project loaded from"), filename))
  8798. self.should_we_save = False
  8799. self.file_opened.emit("project", filename)
  8800. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8801. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8802. if cli is None:
  8803. self.set_ui_title(name=self.project_filename)
  8804. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8805. def propagate_defaults(self, silent=False):
  8806. """
  8807. This method is used to set default values in classes. It's
  8808. an alternative to project options but allows the use
  8809. of values invisible to the user.
  8810. :return: None
  8811. """
  8812. if silent is False:
  8813. self.log.debug("propagate_defaults()")
  8814. # Which objects to update the given parameters.
  8815. routes = {
  8816. "global_zdownrate": CNCjob,
  8817. "excellon_zeros": Excellon,
  8818. "excellon_format_upper_in": Excellon,
  8819. "excellon_format_lower_in": Excellon,
  8820. "excellon_format_upper_mm": Excellon,
  8821. "excellon_format_lower_mm": Excellon,
  8822. "excellon_units": Excellon,
  8823. "gerber_use_buffer_for_union": Gerber,
  8824. "geometry_multidepth": Geometry
  8825. }
  8826. for param in routes:
  8827. if param in routes[param].defaults:
  8828. try:
  8829. routes[param].defaults[param] = self.defaults[param]
  8830. if silent is False:
  8831. self.log.debug(" " + param + " OK")
  8832. except KeyError:
  8833. if silent is False:
  8834. self.log.debug(" ERROR: " + param + " not in defaults.")
  8835. else:
  8836. # Try extracting the name:
  8837. # classname_param here is param in the object
  8838. if param.find(routes[param].__name__.lower() + "_") == 0:
  8839. p = param[len(routes[param].__name__) + 1:]
  8840. if p in routes[param].defaults:
  8841. routes[param].defaults[p] = self.defaults[param]
  8842. if silent is False:
  8843. self.log.debug(" " + param + " OK!")
  8844. def plot_all(self, zoom=True):
  8845. """
  8846. Re-generates all plots from all objects.
  8847. :return: None
  8848. """
  8849. self.log.debug("Plot_all()")
  8850. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  8851. for obj in self.collection.get_list():
  8852. def worker_task(obj):
  8853. with self.proc_container.new("Plotting"):
  8854. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8855. if zoom:
  8856. self.object_plotted.emit(obj)
  8857. # Send to worker
  8858. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  8859. def register_folder(self, filename):
  8860. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8861. def register_save_folder(self, filename):
  8862. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8863. def set_progress_bar(self, percentage, text=""):
  8864. self.ui.progress_bar.setValue(int(percentage))
  8865. def setup_shell(self):
  8866. """
  8867. Creates shell functions. Runs once at startup.
  8868. :return: None
  8869. """
  8870. self.log.debug("setup_shell()")
  8871. def shelp(p=None):
  8872. if not p:
  8873. return _("Available commands:\n") + \
  8874. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  8875. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  8876. if p not in commands:
  8877. return "Unknown command: %s" % p
  8878. return commands[p]["help"]
  8879. # --- Migrated to new architecture ---
  8880. # def options(name):
  8881. # ops = self.collection.get_by_name(str(name)).options
  8882. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  8883. def h(*args):
  8884. """
  8885. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  8886. and standalone parameters into list.
  8887. """
  8888. kwa = {}
  8889. a = []
  8890. n = len(args)
  8891. name = None
  8892. for i in range(n):
  8893. match = re.search(r'^-([a-zA-Z].*)', args[i])
  8894. if match:
  8895. assert name is None
  8896. name = match.group(1)
  8897. continue
  8898. if name is None:
  8899. a.append(args[i])
  8900. else:
  8901. kwa[name] = args[i]
  8902. name = None
  8903. return a, kwa
  8904. @contextmanager
  8905. def wait_signal(signal, timeout=10000):
  8906. """
  8907. Block loop until signal emitted, timeout (ms) elapses
  8908. or unhandled exception happens in a thread.
  8909. :param timeout: time after which the loop is exited
  8910. :param signal: Signal to wait for.
  8911. """
  8912. loop = QtCore.QEventLoop()
  8913. # Normal termination
  8914. signal.connect(loop.quit)
  8915. # Termination by exception in thread
  8916. self.thread_exception.connect(loop.quit)
  8917. status = {'timed_out': False}
  8918. def report_quit():
  8919. status['timed_out'] = True
  8920. loop.quit()
  8921. yield
  8922. # Temporarily change how exceptions are managed.
  8923. oeh = sys.excepthook
  8924. ex = []
  8925. def except_hook(type_, value, traceback_):
  8926. ex.append(value)
  8927. oeh(type_, value, traceback_)
  8928. sys.excepthook = except_hook
  8929. # Terminate on timeout
  8930. if timeout is not None:
  8931. QtCore.QTimer.singleShot(timeout, report_quit)
  8932. # # ## Block ## ##
  8933. loop.exec_()
  8934. # Restore exception management
  8935. sys.excepthook = oeh
  8936. if ex:
  8937. self.raiseTclError(str(ex[0]))
  8938. if status['timed_out']:
  8939. raise Exception('Timed out!')
  8940. def make_docs():
  8941. output = ''
  8942. import collections
  8943. od = collections.OrderedDict(sorted(commands.items()))
  8944. for cmd_, val in od.items():
  8945. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  8946. t = val['help']
  8947. usage_i = t.find('>')
  8948. if usage_i < 0:
  8949. expl = t
  8950. output += expl + '\n\n'
  8951. continue
  8952. expl = t[:usage_i - 1]
  8953. output += expl + '\n\n'
  8954. end_usage_i = t[usage_i:].find('\n')
  8955. if end_usage_i < 0:
  8956. end_usage_i = len(t[usage_i:])
  8957. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  8958. else:
  8959. extras = t[usage_i+end_usage_i+1:]
  8960. parts = [s.strip() for s in extras.split('\n')]
  8961. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  8962. for p in parts:
  8963. output += ' ' + p + '\n\n'
  8964. return output
  8965. '''
  8966. Howto implement TCL shell commands:
  8967. All parameters passed to command should be possible to set as None and test it afterwards.
  8968. This is because we need to see error caused in tcl,
  8969. if None value as default parameter is not allowed TCL will return empty error.
  8970. Use:
  8971. def mycommand(name=None,...):
  8972. Test it like this:
  8973. if name is None:
  8974. self.raise_tcl_error('Argument name is missing.')
  8975. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  8976. otherwise we will miss it and processing will silently continue.
  8977. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  8978. which is catched in exec_command and displayed in TCL shell console with red background.
  8979. Error in console is displayed with TCL trace.
  8980. This behavior works only within main thread,
  8981. errors with promissed tasks can be catched and detected only with log.
  8982. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  8983. TCL shell.
  8984. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  8985. '''
  8986. commands = {
  8987. 'help': {
  8988. 'fcn': shelp,
  8989. 'help': _("Shows list of commands.")
  8990. },
  8991. }
  8992. # Import/overwrite tcl commands as objects of TclCommand descendants
  8993. # This modifies the variable 'commands'.
  8994. tclCommands.register_all_commands(self, commands)
  8995. # Add commands to the tcl interpreter
  8996. for cmd in commands:
  8997. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  8998. # Make the tcl puts function return instead of print to stdout
  8999. self.tcl.eval('''
  9000. rename puts original_puts
  9001. proc puts {args} {
  9002. if {[llength $args] == 1} {
  9003. return "[lindex $args 0]"
  9004. } else {
  9005. eval original_puts $args
  9006. }
  9007. }
  9008. ''')
  9009. def setup_recent_items(self):
  9010. # TODO: Move this to constructor
  9011. icons = {
  9012. "gerber": "share/flatcam_icon16.png",
  9013. "excellon": "share/drill16.png",
  9014. 'geometry': "share/geometry16.png",
  9015. "cncjob": "share/cnc16.png",
  9016. "project": "share/project16.png",
  9017. "svg": "share/geometry16.png",
  9018. "dxf": "share/dxf16.png",
  9019. "pdf": "share/pdf32.png",
  9020. "image": "share/image16.png"
  9021. }
  9022. openers = {
  9023. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  9024. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  9025. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  9026. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  9027. 'project': self.open_project,
  9028. 'svg': self.import_svg,
  9029. 'dxf': self.import_dxf,
  9030. 'image': self.import_image,
  9031. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  9032. }
  9033. # Open recent file for files
  9034. try:
  9035. f = open(self.data_path + '/recent.json')
  9036. except IOError:
  9037. App.log.error("Failed to load recent item list.")
  9038. self.inform.emit('[ERROR_NOTCL] %s' %
  9039. _("Failed to load recent item list."))
  9040. return
  9041. try:
  9042. self.recent = json.load(f)
  9043. except json.scanner.JSONDecodeError:
  9044. App.log.error("Failed to parse recent item list.")
  9045. self.inform.emit('[ERROR_NOTCL] %s' %
  9046. _("Failed to parse recent item list."))
  9047. f.close()
  9048. return
  9049. f.close()
  9050. # Open recent file for projects
  9051. try:
  9052. fp = open(self.data_path + '/recent_projects.json')
  9053. except IOError:
  9054. App.log.error("Failed to load recent project item list.")
  9055. self.inform.emit('[ERROR_NOTCL] %s' %
  9056. _("Failed to load recent projects item list."))
  9057. return
  9058. try:
  9059. self.recent_projects = json.load(fp)
  9060. except json.scanner.JSONDecodeError:
  9061. App.log.error("Failed to parse recent project item list.")
  9062. self.inform.emit('[ERROR_NOTCL] %s' %
  9063. _("Failed to parse recent project item list."))
  9064. fp.close()
  9065. return
  9066. fp.close()
  9067. # Closure needed to create callbacks in a loop.
  9068. # Otherwise late binding occurs.
  9069. def make_callback(func, fname):
  9070. def opener():
  9071. func(fname)
  9072. return opener
  9073. def reset_recent_files():
  9074. # Reset menu
  9075. self.ui.recent.clear()
  9076. self.recent = []
  9077. try:
  9078. f = open(self.data_path + '/recent.json', 'w')
  9079. except IOError:
  9080. App.log.error("Failed to open recent items file for writing.")
  9081. return
  9082. json.dump(self.recent, f)
  9083. def reset_recent_projects():
  9084. # Reset menu
  9085. self.ui.recent_projects.clear()
  9086. self.recent_projects = []
  9087. try:
  9088. fp = open(self.data_path + '/recent_projects.json', 'w')
  9089. except IOError:
  9090. App.log.error("Failed to open recent projects items file for writing.")
  9091. return
  9092. json.dump(self.recent, fp)
  9093. # Reset menu
  9094. self.ui.recent.clear()
  9095. self.ui.recent_projects.clear()
  9096. # Create menu items for projects
  9097. for recent in self.recent_projects:
  9098. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9099. if recent['kind'] == 'project':
  9100. try:
  9101. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9102. # Attach callback
  9103. o = make_callback(openers[recent["kind"]], recent['filename'])
  9104. action.triggered.connect(o)
  9105. self.ui.recent_projects.addAction(action)
  9106. except KeyError:
  9107. App.log.error("Unsupported file type: %s" % recent["kind"])
  9108. # Last action in Recent Files menu is one that Clear the content
  9109. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  9110. clear_action_proj.triggered.connect(reset_recent_projects)
  9111. self.ui.recent_projects.addSeparator()
  9112. self.ui.recent_projects.addAction(clear_action_proj)
  9113. # Create menu items for files
  9114. for recent in self.recent:
  9115. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9116. if recent['kind'] != 'project':
  9117. try:
  9118. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9119. # Attach callback
  9120. o = make_callback(openers[recent["kind"]], recent['filename'])
  9121. action.triggered.connect(o)
  9122. self.ui.recent.addAction(action)
  9123. except KeyError:
  9124. App.log.error("Unsupported file type: %s" % recent["kind"])
  9125. # Last action in Recent Files menu is one that Clear the content
  9126. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  9127. clear_action.triggered.connect(reset_recent_files)
  9128. self.ui.recent.addSeparator()
  9129. self.ui.recent.addAction(clear_action)
  9130. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  9131. # self.ui.menufilerecent.set_submenu(recent_menu)
  9132. # recent_menu.show_all()
  9133. # self.ui.recent.show()
  9134. self.log.debug("Recent items list has been populated.")
  9135. def setup_component_editor(self):
  9136. # label = QtWidgets.QLabel("Choose an item from Project")
  9137. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  9138. sel_title = QtWidgets.QTextEdit(
  9139. _('<b>Shortcut Key List</b>'))
  9140. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  9141. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  9142. settings = QSettings("Open Source", "FlatCAM")
  9143. if settings.contains("notebook_font_size"):
  9144. fsize = settings.value('notebook_font_size', type=int)
  9145. else:
  9146. fsize = 12
  9147. tsize = fsize + int(fsize / 2)
  9148. # selected_text = (_('''
  9149. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  9150. #
  9151. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  9152. # The normal flow when working in FlatCAM is the following:</span></p>
  9153. #
  9154. # <ol>
  9155. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  9156. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  9157. # even dragging and dropping the files on the GUI.<br />
  9158. # <br />
  9159. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  9160. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  9161. # &nbsp;</li>
  9162. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  9163. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  9164. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  9165. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  9166. # <br />
  9167. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  9168. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  9169. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  9170. # it even if it was out of focus.<br />
  9171. # <br />
  9172. # You can change the parameters in this screen and the flow direction is like this:<br />
  9173. # <br />
  9174. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  9175. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  9176. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  9177. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  9178. # </ol>
  9179. #
  9180. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  9181. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  9182. # <strong>F3</strong>.</span></p>
  9183. #
  9184. # ''').format(fsize=fsize, tsize=tsize))
  9185. selected_text = '''
  9186. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  9187. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  9188. {s1}</span></p>
  9189. <ol>
  9190. <li><span style="font-size:{fsize}px">{s2}<br />
  9191. <br />
  9192. {s3}</span><br />
  9193. &nbsp;</li>
  9194. <li><span style="font-size:{fsize}px">{s4}<br />
  9195. &nbsp;</li>
  9196. <br />
  9197. <li><span style="font-size:{fsize}px">{s5}<br />
  9198. &nbsp;</li>
  9199. <br />
  9200. <li><span style="font-size:{fsize}px">{s6}<br />
  9201. <br />
  9202. {s7}</span></li>
  9203. </ol>
  9204. <p><span style="font-size:{fsize}px">{s8}</span></p>
  9205. '''.format(
  9206. title=_("Selected Tab - Choose an Item from Project Tab"),
  9207. subtitle=_("Details"),
  9208. s1=_("The normal flow when working in FlatCAM is the following:"),
  9209. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  9210. "using either the toolbars, key shortcuts or even dragging and dropping the "
  9211. "files on the GUI."),
  9212. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  9213. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  9214. "actions offered within the app."),
  9215. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  9216. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  9217. "SELECTED TAB will be updated with the object properties according to its kind: "
  9218. "Gerber, Excellon, Geometry or CNCJob object."),
  9219. s5=_("If the selection of the object is done on the canvas by single click instead, "
  9220. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  9221. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  9222. "the SELECTED TAB and populate it even if it was out of focus."),
  9223. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  9224. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  9225. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  9226. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  9227. "(again, done in SELECTED TAB) --> Save GCode."),
  9228. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  9229. "or through its own key shortcut: <b>F3</b>."),
  9230. tsize=tsize,
  9231. fsize=fsize
  9232. )
  9233. sel_title.setText(selected_text)
  9234. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  9235. self.ui.selected_scroll_area.setWidget(sel_title)
  9236. def setup_obj_classes(self):
  9237. """
  9238. Sets up application specifics on the FlatCAMObj class.
  9239. :return: None
  9240. """
  9241. FlatCAMObj.app = self
  9242. ObjectCollection.app = self
  9243. Gerber.app = self
  9244. Excellon.app = self
  9245. Geometry.app = self
  9246. CNCjob.app = self
  9247. FCProcess.app = self
  9248. FCProcessContainer.app = self
  9249. def version_check(self):
  9250. """
  9251. Checks for the latest version of the program. Alerts the
  9252. user if theirs is outdated. This method is meant to be run
  9253. in a separate thread.
  9254. :return: None
  9255. """
  9256. self.log.debug("version_check()")
  9257. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  9258. full_url = App.version_url + \
  9259. "?s=" + str(self.defaults['global_serial']) + \
  9260. "&v=" + str(self.version) + \
  9261. "&os=" + str(self.os) + \
  9262. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  9263. else:
  9264. # no_stats dict; just so it won't break things on website
  9265. no_ststs_dict = {}
  9266. no_ststs_dict["global_ststs"] = {}
  9267. full_url = App.version_url + \
  9268. "?s=" + str(self.defaults['global_serial']) + \
  9269. "&v=" + str(self.version) + \
  9270. "&os=" + str(self.os) + \
  9271. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  9272. App.log.debug("Checking for updates @ %s" % full_url)
  9273. # ## Get the data
  9274. try:
  9275. f = urllib.request.urlopen(full_url)
  9276. except:
  9277. # App.log.warning("Failed checking for latest version. Could not connect.")
  9278. self.log.warning("Failed checking for latest version. Could not connect.")
  9279. self.inform.emit('[WARNING_NOTCL] %s' %
  9280. _("Failed checking for latest version. Could not connect."))
  9281. return
  9282. try:
  9283. data = json.load(f)
  9284. except Exception as e:
  9285. App.log.error("Could not parse information about latest version.")
  9286. self.inform.emit('[ERROR_NOTCL] %s' %
  9287. _("Could not parse information about latest version."))
  9288. App.log.debug("json.load(): %s" % str(e))
  9289. f.close()
  9290. return
  9291. f.close()
  9292. # ## Latest version?
  9293. if self.version >= data["version"]:
  9294. App.log.debug("FlatCAM is up to date!")
  9295. self.inform.emit('[success] %s' %
  9296. _("FlatCAM is up to date!"))
  9297. return
  9298. App.log.debug("Newer version available.")
  9299. self.message.emit(
  9300. _("Newer Version Available"),
  9301. _("There is a newer version of FlatCAM available for download:\n\n") +
  9302. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  9303. _("info")
  9304. )
  9305. def on_plotcanvas_setup(self, container=None):
  9306. """
  9307. This is doing the setup for the plot area (VisPy canvas)
  9308. :param container: widget where to install the canvas
  9309. :return: None
  9310. """
  9311. if container:
  9312. plot_container = container
  9313. else:
  9314. plot_container = self.ui.right_layout
  9315. if self.is_legacy is False:
  9316. self.plotcanvas = PlotCanvas(plot_container, self)
  9317. else:
  9318. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  9319. # So it can receive key presses
  9320. self.plotcanvas.native.setFocus()
  9321. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  9322. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  9323. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  9324. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_double_click_over_plot)
  9325. # Keys over plot enabled
  9326. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  9327. self.app_cursor = self.plotcanvas.new_cursor()
  9328. if self.ui.grid_snap_btn.isChecked():
  9329. self.app_cursor.enabled = True
  9330. else:
  9331. self.app_cursor.enabled = False
  9332. if self.is_legacy is False:
  9333. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  9334. else:
  9335. # will use the default Matplotlib axes
  9336. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  9337. def on_zoom_fit(self, event):
  9338. """
  9339. Callback for zoom-out request. This can be either from the corresponding
  9340. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  9341. with axes limits from the geometry bounds of all objects.
  9342. :param event: Ignored.
  9343. :return: None
  9344. """
  9345. if self.is_legacy is False:
  9346. self.plotcanvas.fit_view()
  9347. else:
  9348. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  9349. width = xmax - xmin
  9350. height = ymax - ymin
  9351. xmin -= 0.05 * width
  9352. xmax += 0.05 * width
  9353. ymin -= 0.05 * height
  9354. ymax += 0.05 * height
  9355. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  9356. def on_zoom_in(self):
  9357. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  9358. def on_zoom_out(self):
  9359. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  9360. def disable_all_plots(self):
  9361. self.report_usage("disable_all_plots()")
  9362. self.disable_plots(self.collection.get_list())
  9363. self.inform.emit('[success] %s' %
  9364. _("All plots disabled."))
  9365. def disable_other_plots(self):
  9366. self.report_usage("disable_other_plots()")
  9367. self.disable_plots(self.collection.get_non_selected())
  9368. self.inform.emit('[success] %s' %
  9369. _("All non selected plots disabled."))
  9370. def enable_all_plots(self):
  9371. self.report_usage("enable_all_plots()")
  9372. self.enable_plots(self.collection.get_list())
  9373. self.inform.emit('[success] %s' %
  9374. _("All plots enabled."))
  9375. def on_enable_sel_plots(self):
  9376. log.debug("App.on_enable_sel_plot()")
  9377. object_list = self.collection.get_selected()
  9378. self.enable_plots(objects=object_list)
  9379. self.inform.emit('[success] %s' %
  9380. _("Selected plots enabled..."))
  9381. def on_disable_sel_plots(self):
  9382. log.debug("App.on_disable_sel_plot()")
  9383. # self.inform.emit(_("Disabling plots ..."))
  9384. object_list = self.collection.get_selected()
  9385. self.disable_plots(objects=object_list)
  9386. self.inform.emit('[success] %s' %
  9387. _("Selected plots disabled..."))
  9388. def enable_plots(self, objects):
  9389. """
  9390. Disables plots
  9391. :param objects: list of Objects to be enabled
  9392. :return:
  9393. """
  9394. log.debug("Enabling plots ...")
  9395. # self.inform.emit(_("Working ..."))
  9396. for obj in objects:
  9397. if obj.options['plot'] is False:
  9398. obj.options.set_change_callback(lambda x: None)
  9399. obj.options['plot'] = True
  9400. obj.options.set_change_callback(obj.on_options_change)
  9401. def worker_task(objects):
  9402. with self.proc_container.new(_("Enabling plots ...")):
  9403. for obj in objects:
  9404. # obj.options['plot'] = True
  9405. if isinstance(obj, FlatCAMCNCjob):
  9406. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  9407. else:
  9408. obj.plot(visible=True)
  9409. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9410. # self.plots_updated.emit()
  9411. def disable_plots(self, objects):
  9412. """
  9413. Disables plots
  9414. :param objects: list of Objects to be disabled
  9415. :return:
  9416. """
  9417. # if no objects selected then do nothing
  9418. if not self.collection.get_selected():
  9419. return
  9420. log.debug("Disabling plots ...")
  9421. # self.inform.emit(_("Working ..."))
  9422. for obj in objects:
  9423. if obj.options['plot'] is True:
  9424. obj.options.set_change_callback(lambda x: None)
  9425. obj.options['plot'] = False
  9426. obj.options.set_change_callback(obj.on_options_change)
  9427. try:
  9428. self.delete_selection_shape()
  9429. except Exception as e:
  9430. log.debug("App.disable_plots() --> %s" % str(e))
  9431. # self.plots_updated.emit()
  9432. def worker_task(objects):
  9433. with self.proc_container.new(_("Disabling plots ...")):
  9434. for obj in objects:
  9435. # obj.options['plot'] = True
  9436. if isinstance(obj, FlatCAMCNCjob):
  9437. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  9438. else:
  9439. obj.plot(visible=False)
  9440. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9441. def toggle_plots(self, objects):
  9442. """
  9443. Toggle plots visibility
  9444. :param objects: list of Objects for which to be toggled the visibility
  9445. :return:
  9446. """
  9447. # if no objects selected then do nothing
  9448. if not self.collection.get_selected():
  9449. return
  9450. log.debug("Toggling plots ...")
  9451. self.inform.emit(_("Working ..."))
  9452. for obj in objects:
  9453. if obj.options['plot'] is False:
  9454. obj.options['plot'] = True
  9455. else:
  9456. obj.options['plot'] = False
  9457. self.plots_updated.emit()
  9458. def clear_plots(self):
  9459. objects = self.collection.get_list()
  9460. for obj in objects:
  9461. obj.clear(obj == objects[-1])
  9462. # Clear pool to free memory
  9463. self.clear_pool()
  9464. def generate_cnc_job(self, objects):
  9465. self.report_usage("generate_cnc_job()")
  9466. # for obj in objects:
  9467. # obj.generatecncjob()
  9468. for obj in objects:
  9469. obj.on_generatecnc_button_click()
  9470. def save_project(self, filename, quit_action=False, silent=False):
  9471. """
  9472. Saves the current project to the specified file.
  9473. :param filename: Name of the file in which to save.
  9474. :type filename: str
  9475. :param quit_action: if the project saving will be followed by an app quit; boolean
  9476. :param silent: if True will not display status messages
  9477. :return: None
  9478. """
  9479. self.log.debug("save_project()")
  9480. self.save_in_progress = True
  9481. with self.proc_container.new(_("Saving FlatCAM Project")):
  9482. # Capture the latest changes
  9483. # Current object
  9484. try:
  9485. self.collection.get_active().read_form()
  9486. except:
  9487. self.log.debug("There was no active object")
  9488. pass
  9489. # Project options
  9490. self.options_read_form()
  9491. # Serialize the whole project
  9492. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  9493. "options": self.options,
  9494. "version": self.version}
  9495. if self.defaults["global_save_compressed"] is True:
  9496. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  9497. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  9498. # # Write
  9499. f.write(g)
  9500. self.inform.emit('[success] %s: %s' %
  9501. (_("Project saved to"), filename))
  9502. else:
  9503. # Open file
  9504. try:
  9505. f = open(filename, 'w')
  9506. except IOError:
  9507. App.log.error("Failed to open file for saving: %s", filename)
  9508. return
  9509. # Write
  9510. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  9511. f.close()
  9512. # verification of the saved project
  9513. # Open and parse
  9514. try:
  9515. saved_f = open(filename, 'r')
  9516. except IOError:
  9517. if silent is False:
  9518. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9519. (_("Failed to verify project file"), filename, _("Retry to save it."))
  9520. )
  9521. return
  9522. try:
  9523. saved_d = json.load(saved_f, object_hook=dict2obj)
  9524. except:
  9525. if silent is False:
  9526. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9527. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9528. )
  9529. f.close()
  9530. return
  9531. saved_f.close()
  9532. if silent is False:
  9533. if 'version' in saved_d:
  9534. self.inform.emit('[success] %s: %s' %
  9535. (_("Project saved to"), filename))
  9536. else:
  9537. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9538. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9539. )
  9540. settings = QSettings("Open Source", "FlatCAM")
  9541. lock_state = self.ui.lock_action.isChecked()
  9542. settings.setValue('toolbar_lock', lock_state)
  9543. # This will write the setting to the platform specific storage.
  9544. del settings
  9545. # if quit:
  9546. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  9547. # t.start()
  9548. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  9549. def start_delayed_quit(self, delay, filename, should_quit=None):
  9550. """
  9551. :param delay: period of checking if project file size is more than zero; in seconds
  9552. :param filename: the name of the project file to be checked periodically for size more than zero
  9553. :param should_quit: if the task finished will be followed by an app quit; boolean
  9554. :return:
  9555. """
  9556. to_quit = should_quit
  9557. self.save_timer = QtCore.QTimer()
  9558. self.save_timer.setInterval(delay)
  9559. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  9560. self.save_timer.start()
  9561. def check_project_file_size(self, filename, should_quit=None):
  9562. """
  9563. :param filename: the name of the project file to be checked periodically for size more than zero
  9564. :param should_quit: will quit the app if True; boolean
  9565. :return:
  9566. """
  9567. try:
  9568. if os.stat(filename).st_size > 0:
  9569. self.save_in_progress = False
  9570. self.save_timer.stop()
  9571. if should_quit:
  9572. self.app_quit.emit()
  9573. except Exception as e:
  9574. traceback.print_exc()
  9575. def on_options_app2project(self):
  9576. """
  9577. Callback for Options->Transfer Options->App=>Project. Copies options
  9578. from application defaults to project defaults.
  9579. :return: None
  9580. """
  9581. self.report_usage("on_options_app2project")
  9582. self.defaults_read_form()
  9583. self.options.update(self.defaults)
  9584. self.options_write_form()
  9585. def on_options_project2app(self):
  9586. """
  9587. Callback for Options->Transfer Options->Project=>App. Copies options
  9588. from project defaults to application defaults.
  9589. :return: None
  9590. """
  9591. self.report_usage("on_options_project2app")
  9592. self.options_read_form()
  9593. self.defaults.update(self.options)
  9594. self.defaults_write_form()
  9595. def on_options_project2object(self):
  9596. """
  9597. Callback for Options->Transfer Options->Project=>Object. Copies options
  9598. from project defaults to the currently selected object.
  9599. :return: None
  9600. """
  9601. self.report_usage("on_options_project2object")
  9602. self.options_read_form()
  9603. obj = self.collection.get_active()
  9604. if obj is None:
  9605. self.inform.emit('[WARNING_NOTCL] %s' %
  9606. _("No object selected."))
  9607. return
  9608. for option in self.options:
  9609. if option.find(obj.kind + "_") == 0:
  9610. oname = option[len(obj.kind) + 1:]
  9611. obj.options[oname] = self.options[option]
  9612. obj.to_form() # Update UI
  9613. def on_options_object2project(self):
  9614. """
  9615. Callback for Options->Transfer Options->Object=>Project. Copies options
  9616. from the currently selected object to project defaults.
  9617. :return: None
  9618. """
  9619. self.report_usage("on_options_object2project")
  9620. obj = self.collection.get_active()
  9621. if obj is None:
  9622. self.inform.emit('[WARNING_NOTCL] %s' %
  9623. _("No object selected."))
  9624. return
  9625. obj.read_form()
  9626. for option in obj.options:
  9627. if option in ['name']: # TODO: Handle this better...
  9628. continue
  9629. self.options[obj.kind + "_" + option] = obj.options[option]
  9630. self.options_write_form()
  9631. def on_options_object2app(self):
  9632. """
  9633. Callback for Options->Transfer Options->Object=>App. Copies options
  9634. from the currently selected object to application defaults.
  9635. :return: None
  9636. """
  9637. self.report_usage("on_options_object2app")
  9638. obj = self.collection.get_active()
  9639. if obj is None:
  9640. self.inform.emit('[WARNING_NOTCL] %s' %
  9641. _("No object selected."))
  9642. return
  9643. obj.read_form()
  9644. for option in obj.options:
  9645. if option in ['name']: # TODO: Handle this better...
  9646. continue
  9647. self.defaults[obj.kind + "_" + option] = obj.options[option]
  9648. self.defaults_write_form()
  9649. def on_options_app2object(self):
  9650. """
  9651. Callback for Options->Transfer Options->App=>Object. Copies options
  9652. from application defaults to the currently selected object.
  9653. :return: None
  9654. """
  9655. self.report_usage("on_options_app2object")
  9656. self.defaults_read_form()
  9657. obj = self.collection.get_active()
  9658. if obj is None:
  9659. self.inform.emit('[WARNING_NOTCL] %s' %
  9660. _("No object selected."))
  9661. return
  9662. for option in self.defaults:
  9663. if option.find(obj.kind + "_") == 0:
  9664. oname = option[len(obj.kind) + 1:]
  9665. obj.options[oname] = self.defaults[option]
  9666. obj.to_form() # Update UI
  9667. class ArgsThread(QtCore.QObject):
  9668. open_signal = pyqtSignal(list)
  9669. start = pyqtSignal()
  9670. if sys.platform == 'win32':
  9671. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  9672. else:
  9673. address = ('/tmp/testipc', 'AF_UNIX')
  9674. def __init__(self):
  9675. super(ArgsThread, self).__init__()
  9676. self.start.connect(self.run)
  9677. def my_loop(self, address):
  9678. try:
  9679. listener = Listener(*address)
  9680. while True:
  9681. conn = listener.accept()
  9682. self.serve(conn)
  9683. except socket.error as e:
  9684. conn = Client(*address)
  9685. conn.send(sys.argv)
  9686. conn.send('close')
  9687. # close the current instance only if there are args
  9688. if len(sys.argv) > 1:
  9689. sys.exit()
  9690. def serve(self, conn):
  9691. while True:
  9692. msg = conn.recv()
  9693. if msg == 'close':
  9694. break
  9695. self.open_signal.emit(msg)
  9696. conn.close()
  9697. # the decorator is a must; without it this technique will not work unless the start signal is connected
  9698. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  9699. @pyqtSlot()
  9700. def run(self):
  9701. self.my_loop(self.address)
  9702. class GracefulException(Exception):
  9703. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  9704. def __init__(self):
  9705. super().__init__()
  9706. def __str__(self):
  9707. return ('\n\n%s' % _("The user requested a graceful exit of the current task."))
  9708. # end of file