FlatCAMApp.py 545 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ###########################################################
  8. import urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import webbrowser
  12. import getopt
  13. import random
  14. import simplejson as json
  15. import lzma
  16. import threading
  17. import shutil
  18. import stat
  19. from stat import S_IREAD, S_IRGRP, S_IROTH
  20. import subprocess
  21. import ctypes
  22. import tkinter as tk
  23. from PyQt5 import QtPrintSupport
  24. from contextlib import contextmanager
  25. import gc
  26. from xml.dom.minidom import parseString as parse_xml_string
  27. from multiprocessing.connection import Listener, Client
  28. from multiprocessing import Pool, cpu_count
  29. import socket
  30. from array import array
  31. import vispy.scene as scene
  32. # #######################################
  33. # # Imports part of FlatCAM ##
  34. # #######################################
  35. from ObjectCollection import *
  36. from FlatCAMObj import *
  37. from camlib import to_dict, dict2obj, ET, ParseError
  38. from flatcamGUI.PlotCanvas import *
  39. from flatcamGUI.PlotCanvasLegacy import *
  40. from flatcamGUI.FlatCAMGUI import *
  41. from FlatCAMCommon import LoudDict, BookmarkManager, ToolsDB
  42. from FlatCAMPostProc import load_postprocessors
  43. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  44. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  45. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  46. from flatcamEditors.FlatCAMTextEditor import TextEditor
  47. from FlatCAMProcess import *
  48. from FlatCAMWorkerStack import WorkerStack
  49. # from flatcamGUI.VisPyVisuals import Color
  50. from vispy.gloo.util import _screenshot
  51. from vispy.io import write_png
  52. from flatcamTools import *
  53. import tclCommands
  54. import gettext
  55. import FlatCAMTranslation as fcTranslate
  56. import builtins
  57. if sys.platform == 'win32':
  58. import winreg
  59. fcTranslate.apply_language('strings')
  60. if '_' not in builtins.__dict__:
  61. _ = gettext.gettext
  62. class App(QtCore.QObject):
  63. # ########################################
  64. # # App ###
  65. # ########################################
  66. """
  67. The main application class. The constructor starts the GUI.
  68. """
  69. # Get Cmd Line Options
  70. cmd_line_shellfile = ''
  71. cmd_line_shellvar = ''
  72. cmd_line_headless = None
  73. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  74. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  75. "FlatCam.py --headless=1"
  76. try:
  77. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  78. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  79. "shellvar=",
  80. "headless=",
  81. "multiprocessing-fork="])
  82. except getopt.GetoptError:
  83. print(cmd_line_help)
  84. sys.exit(2)
  85. for opt, arg in cmd_line_options:
  86. if opt == '-h':
  87. print(cmd_line_help)
  88. sys.exit()
  89. elif opt == '--shellfile':
  90. cmd_line_shellfile = arg
  91. elif opt == '--shellvar':
  92. cmd_line_shellvar = arg
  93. elif opt == '--headless':
  94. try:
  95. cmd_line_headless = eval(arg)
  96. except NameError:
  97. pass
  98. # ## Logging ###
  99. log = logging.getLogger('base')
  100. log.setLevel(logging.DEBUG)
  101. # log.setLevel(logging.WARNING)
  102. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  103. handler = logging.StreamHandler()
  104. handler.setFormatter(formatter)
  105. log.addHandler(handler)
  106. # ##########################################################################
  107. # ################## Version and VERSION DATE ##############################
  108. # ##########################################################################
  109. version = 8.99
  110. version_date = "2019/12/7"
  111. beta = True
  112. engine = '3D'
  113. # current date now
  114. date = str(datetime.today()).rpartition('.')[0]
  115. date = ''.join(c for c in date if c not in ':-')
  116. date = date.replace(' ', '_')
  117. # URL for update checks and statistics
  118. version_url = "http://flatcam.org/version"
  119. # App URL
  120. app_url = "http://flatcam.org"
  121. # Manual URL
  122. manual_url = "http://flatcam.org/manual/index.html"
  123. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  124. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  125. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  126. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  127. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  128. # this variable will hold the project status
  129. # if True it will mean that the project was modified and not saved
  130. should_we_save = False
  131. # flag is True if saving action has been triggered
  132. save_in_progress = False
  133. # ###########################################################################
  134. # ############################# Signals ################################
  135. # ###########################################################################
  136. # Inform the user
  137. # Handled by:
  138. # * App.info() --> Print on the status bar
  139. inform = QtCore.pyqtSignal(str)
  140. app_quit = QtCore.pyqtSignal()
  141. # General purpose background task
  142. worker_task = QtCore.pyqtSignal(dict)
  143. # File opened
  144. # Handled by:
  145. # * register_folder()
  146. # * register_recent()
  147. # Note: Setting the parameters to unicode does not seem
  148. # to have an effect. Then are received as Qstring
  149. # anyway.
  150. # File type and filename
  151. file_opened = QtCore.pyqtSignal(str, str)
  152. # File type and filename
  153. file_saved = QtCore.pyqtSignal(str, str)
  154. # Percentage of progress
  155. progress = QtCore.pyqtSignal(int)
  156. plots_updated = QtCore.pyqtSignal()
  157. # Emitted by new_object() and passes the new object as argument, plot flag.
  158. # on_object_created() adds the object to the collection, plots on appropriate flag
  159. # and emits new_object_available.
  160. object_created = QtCore.pyqtSignal(object, bool, bool)
  161. # Emitted when a object has been changed (like scaled, mirrored)
  162. object_changed = QtCore.pyqtSignal(object)
  163. # Emitted after object has been plotted.
  164. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  165. object_plotted = QtCore.pyqtSignal(object)
  166. # Emitted when a new object has been added or deleted from/to the collection
  167. object_status_changed = QtCore.pyqtSignal(object, str, str)
  168. message = QtCore.pyqtSignal(str, str, str)
  169. # Emmited when shell command is finished(one command only)
  170. shell_command_finished = QtCore.pyqtSignal(object)
  171. # Emitted when multiprocess pool has been recreated
  172. pool_recreated = QtCore.pyqtSignal(object)
  173. # Emitted when an unhandled exception happens
  174. # in the worker task.
  175. thread_exception = QtCore.pyqtSignal(object)
  176. # used to signal that there are arguments for the app
  177. args_at_startup = QtCore.pyqtSignal(list)
  178. # a reusable signal to replot a list of objects
  179. # should be disconnected after use so it can be reused
  180. replot_signal = pyqtSignal(list)
  181. def __init__(self, user_defaults=True):
  182. """
  183. Starts the application.
  184. :return: app
  185. :rtype: App
  186. """
  187. App.log.info("FlatCAM Starting...")
  188. self.main_thread = QtWidgets.QApplication.instance().thread()
  189. # ############################################################################
  190. # # ################# OS-specific ############################################
  191. # ############################################################################
  192. portable = False
  193. # Folder for user settings.
  194. if sys.platform == 'win32':
  195. # #########################################################################
  196. # Setup the listening thread for another instance launching with args #####
  197. # #########################################################################
  198. # make sure the thread is stored by using a self. otherwise it's garbage collected
  199. self.th = QtCore.QThread()
  200. self.th.start(priority=QtCore.QThread.LowestPriority)
  201. self.new_launch = ArgsThread()
  202. self.new_launch.open_signal[list].connect(self.on_startup_args)
  203. self.new_launch.moveToThread(self.th)
  204. self.new_launch.start.emit()
  205. from win32com.shell import shell, shellcon
  206. if platform.architecture()[0] == '32bit':
  207. App.log.debug("Win32!")
  208. else:
  209. App.log.debug("Win64!")
  210. # #########################################################################
  211. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  212. # #########################################################################
  213. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  214. try:
  215. with open(config_file, 'r'):
  216. pass
  217. except FileNotFoundError:
  218. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  219. try:
  220. with open(config_file, 'r') as f:
  221. try:
  222. for line in f:
  223. param = str(line).replace('\n', '').rpartition('=')
  224. if param[0] == 'portable':
  225. try:
  226. portable = eval(param[2])
  227. except NameError:
  228. portable = False
  229. if param[0] == 'headless':
  230. if param[2].lower() == 'true':
  231. self.cmd_line_headless = 1
  232. else:
  233. self.cmd_line_headless = None
  234. except Exception as e:
  235. log.debug('App.__init__() -->%s' % str(e))
  236. return
  237. except FileNotFoundError as e:
  238. log.debug(str(e))
  239. pass
  240. if portable is False:
  241. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  242. else:
  243. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  244. self.os = 'windows'
  245. else: # Linux/Unix/MacOS
  246. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  247. self.os = 'unix'
  248. # ##########################################################################
  249. # ################## Setup folders and files ###############################
  250. # ##########################################################################
  251. if not os.path.exists(self.data_path):
  252. os.makedirs(self.data_path)
  253. App.log.debug('Created data folder: ' + self.data_path)
  254. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  255. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  256. self.postprocessorpaths = os.path.join(self.data_path, 'postprocessors')
  257. if not os.path.exists(self.postprocessorpaths):
  258. os.makedirs(self.postprocessorpaths)
  259. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  260. # create tools_db.FlatConfig file if there is none
  261. try:
  262. f = open(self.data_path + '/tools_db.FlatConfig')
  263. f.close()
  264. except IOError:
  265. App.log.debug('Creating empty tool_db.FlatConfig')
  266. f = open(self.data_path + '/tools_db.FlatConfig', 'w')
  267. json.dump({}, f)
  268. f.close()
  269. # create current_defaults.FlatConfig file if there is none
  270. try:
  271. f = open(self.data_path + '/current_defaults.FlatConfig')
  272. f.close()
  273. except IOError:
  274. App.log.debug('Creating empty current_defaults.FlatConfig')
  275. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  276. json.dump({}, f)
  277. f.close()
  278. # create factory_defaults.FlatConfig file if there is none
  279. try:
  280. f = open(self.data_path + '/factory_defaults.FlatConfig')
  281. f.close()
  282. except IOError:
  283. App.log.debug('Creating empty factory_defaults.FlatConfig')
  284. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  285. json.dump({}, f)
  286. f.close()
  287. # create a recent files json file if there is none
  288. try:
  289. f = open(self.data_path + '/recent.json')
  290. f.close()
  291. except IOError:
  292. App.log.debug('Creating empty recent.json')
  293. f = open(self.data_path + '/recent.json', 'w')
  294. json.dump([], f)
  295. f.close()
  296. # create a recent projects json file if there is none
  297. try:
  298. fp = open(self.data_path + '/recent_projects.json')
  299. fp.close()
  300. except IOError:
  301. App.log.debug('Creating empty recent_projects.json')
  302. fp = open(self.data_path + '/recent_projects.json', 'w')
  303. json.dump([], fp)
  304. fp.close()
  305. # Application directory. CHDIR to it. Otherwise, trying to load
  306. # GUI icons will fail as their path is relative.
  307. # This will fail under cx_freeze ...
  308. self.app_home = os.path.dirname(os.path.realpath(__file__))
  309. App.log.debug("Application path is " + self.app_home)
  310. App.log.debug("Started in " + os.getcwd())
  311. # cx_freeze workaround
  312. if os.path.isfile(self.app_home):
  313. self.app_home = os.path.dirname(self.app_home)
  314. os.chdir(self.app_home)
  315. # #################################################################################
  316. # #################### DEFAULTS - PREFERENCES STORAGE #############################
  317. # #################################################################################
  318. self.defaults = LoudDict()
  319. self.defaults.update({
  320. # Global APP Preferences
  321. "version": self.version,
  322. "first_run": True,
  323. "units": "MM",
  324. "global_serial": 0,
  325. "global_stats": dict(),
  326. "global_tabs_detachable": True,
  327. "global_graphic_engine": '3D',
  328. "global_app_level": 'b',
  329. "global_portable": False,
  330. "global_language": 'English',
  331. "global_version_check": True,
  332. "global_send_stats": True,
  333. "global_pan_button": '2',
  334. "global_mselect_key": 'Control',
  335. "global_project_at_startup": False,
  336. "global_systray_icon": True,
  337. "global_project_autohide": True,
  338. "global_toggle_tooltips": True,
  339. "global_worker_number": 2,
  340. "global_tolerance": 0.005,
  341. "global_open_style": True,
  342. "global_delete_confirmation": True,
  343. "global_compression_level": 3,
  344. "global_save_compressed": True,
  345. "global_machinist_setting": False,
  346. # Global GUI Preferences
  347. "global_gridx": 1.0,
  348. "global_gridy": 1.0,
  349. "global_snap_max": 0.05,
  350. "global_workspace": False,
  351. "global_workspaceT": "A4",
  352. "global_workspace_orientation": 'p',
  353. "global_grid_context_menu": {
  354. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  355. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  356. },
  357. "global_plot_fill": '#BBF268BF',
  358. "global_plot_line": '#006E20BF',
  359. "global_sel_fill": '#a5a5ffbf',
  360. "global_sel_line": '#0000ffbf',
  361. "global_alt_sel_fill": '#BBF268BF',
  362. "global_alt_sel_line": '#006E20BF',
  363. "global_draw_color": '#FF0000',
  364. "global_sel_draw_color": '#0000FF',
  365. "global_proj_item_color": '#000000',
  366. "global_proj_item_dis_color": '#b7b7cb',
  367. "global_activity_icon": 'Ball green',
  368. "global_toolbar_view": 511,
  369. "global_background_timeout": 300000, # Default value is 5 minutes
  370. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  371. # (python trace only for unknown errors),
  372. # 1 = show trace(show trace always),
  373. # 2 = (For the future).
  374. # Persistence
  375. "global_last_folder": None,
  376. "global_last_save_folder": None,
  377. # Default window geometry
  378. "global_def_win_x": 100,
  379. "global_def_win_y": 100,
  380. "global_def_win_w": 1024,
  381. "global_def_win_h": 650,
  382. "global_def_notebook_width": 1,
  383. # Constants...
  384. "global_defaults_save_period_ms": 20000, # Time between default saves.
  385. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  386. "global_shell_at_startup": False, # Show the shell at startup.
  387. "global_recent_limit": 10, # Max. items in recent list.
  388. "global_bookmarks": dict(),
  389. "global_bookmarks_limit": 10,
  390. "fit_key": 'V',
  391. "zoom_out_key": '-',
  392. "zoom_in_key": '=',
  393. "grid_toggle_key": 'G',
  394. "global_zoom_ratio": 1.5,
  395. "global_point_clipboard_format": "(%.4f, %.4f)",
  396. "global_zdownrate": None,
  397. # General GUI Settings
  398. "global_theme": 'white',
  399. "global_hover": False,
  400. "global_selection_shape": True,
  401. "global_layout": "compact",
  402. "global_cursor_type": "small",
  403. "global_cursor_size": 20,
  404. # Gerber General
  405. "gerber_plot": True,
  406. "gerber_solid": True,
  407. "gerber_multicolored": False,
  408. "gerber_circle_steps": 64,
  409. "gerber_use_buffer_for_union": True,
  410. "gerber_def_units": 'IN',
  411. "gerber_def_zeros": 'L',
  412. "gerber_save_filters": "Gerber File (*.gbr);;Gerber File (*.bot);;Gerber File (*.bsm);;"
  413. "Gerber File (*.cmp);;Gerber File (*.crc);;Gerber File (*.crs);;"
  414. "Gerber File (*.gb0);;Gerber File (*.gb1);;Gerber File (*.gb2);;"
  415. "Gerber File (*.gb3);;Gerber File (*.gb4);;Gerber File (*.gb5);;"
  416. "Gerber File (*.gb6);;Gerber File (*.gb7);;Gerber File (*.gb8);;"
  417. "Gerber File (*.gb9);;Gerber File (*.gbd);;Gerber File (*.gbl);;"
  418. "Gerber File (*.gbo);;Gerber File (*.gbp);;Gerber File (*.gbs);;"
  419. "Gerber File (*.gdo);;Gerber File (*.ger);;Gerber File (*.gko);;"
  420. "Gerber File (*.gm1);;Gerber File (*.gm2);;Gerber File (*.gm3);;"
  421. "Gerber File (*.grb);;Gerber File (*.gtl);;Gerber File (*.gto);;"
  422. "Gerber File (*.gtp);;Gerber File (*.gts);;Gerber File (*.ly15);;"
  423. "Gerber File (*.ly2);;Gerber File (*.mil);;Gerber File (*.pho);;"
  424. "Gerber File (*.plc);;Gerber File (*.pls);;Gerber File (*.smb);;"
  425. "Gerber File (*.smt);;Gerber File (*.sol);;Gerber File (*.spb);;"
  426. "Gerber File (*.spt);;Gerber File (*.ssb);;Gerber File (*.sst);;"
  427. "Gerber File (*.stc);;Gerber File (*.sts);;Gerber File (*.top);;"
  428. "Gerber File (*.tsm);;Gerber File (*.art)"
  429. "All Files (*.*)",
  430. # Gerber Options
  431. "gerber_isotooldia": 0.1,
  432. "gerber_isopasses": 1,
  433. "gerber_isooverlap": 10,
  434. "gerber_milling_type": "cl",
  435. "gerber_combine_passes": False,
  436. "gerber_iso_scope": 'all',
  437. "gerber_noncoppermargin": 0.1,
  438. "gerber_noncopperrounded": False,
  439. "gerber_bboxmargin": 0.1,
  440. "gerber_bboxrounded": False,
  441. # Gerber Advanced Options
  442. "gerber_aperture_display": False,
  443. "gerber_aperture_scale_factor": 1.0,
  444. "gerber_aperture_buffer_factor": 0.0,
  445. "gerber_follow": False,
  446. "gerber_tool_type": 'circular',
  447. "gerber_vtipdia": 0.1,
  448. "gerber_vtipangle": 30,
  449. "gerber_vcutz": -0.05,
  450. "gerber_iso_type": "full",
  451. "gerber_buffering": "full",
  452. "gerber_simplification": False,
  453. "gerber_simp_tolerance": 0.0005,
  454. # Gerber Export
  455. "gerber_exp_units": 'IN',
  456. "gerber_exp_integer": 2,
  457. "gerber_exp_decimals": 4,
  458. "gerber_exp_zeros": 'L',
  459. # Gerber Editor
  460. "gerber_editor_sel_limit": 30,
  461. "gerber_editor_newcode": 10,
  462. "gerber_editor_newsize": 0.8,
  463. "gerber_editor_newtype": 'C',
  464. "gerber_editor_newdim": "0.5, 0.5",
  465. "gerber_editor_array_size": 5,
  466. "gerber_editor_lin_axis": 'X',
  467. "gerber_editor_lin_pitch": 0.1,
  468. "gerber_editor_lin_angle": 0.0,
  469. "gerber_editor_circ_dir": 'CW',
  470. "gerber_editor_circ_angle": 0.0,
  471. "gerber_editor_scale_f": 1.0,
  472. "gerber_editor_buff_f": 0.1,
  473. "gerber_editor_ma_low": 0.0,
  474. "gerber_editor_ma_high": 1.0,
  475. # Excellon General
  476. "excellon_plot": True,
  477. "excellon_solid": True,
  478. "excellon_format_upper_in": 2,
  479. "excellon_format_lower_in": 4,
  480. "excellon_format_upper_mm": 3,
  481. "excellon_format_lower_mm": 3,
  482. "excellon_zeros": "L",
  483. "excellon_units": "INCH",
  484. "excellon_update": True,
  485. "excellon_optimization_type": 'B',
  486. "excellon_search_time": 3,
  487. "excellon_save_filters": "Excellon File (*.txt);;Excellon File (*.drd);;Excellon File (*.drl);;"
  488. "Excellon File (*.exc);;Excellon File (*.ncd);;Excellon File (*.tap);;"
  489. "Excellon File (*.xln);;All Files (*.*)",
  490. # Excellon Options
  491. "excellon_drillz": -1.7,
  492. "excellon_travelz": 2,
  493. "excellon_endz": 0.5,
  494. "excellon_feedrate": 300,
  495. "excellon_spindlespeed": None,
  496. "excellon_dwell": False,
  497. "excellon_dwelltime": 1,
  498. "excellon_toolchange": False,
  499. "excellon_toolchangez": 15,
  500. "excellon_ppname_e": 'default',
  501. "excellon_tooldia": 0.8,
  502. "excellon_slot_tooldia": 1.8,
  503. "excellon_gcode_type": "drills",
  504. # Excellon Advanced Options
  505. "excellon_offset": 0.0,
  506. "excellon_toolchangexy": "0.0, 0.0",
  507. "excellon_startz": None,
  508. "excellon_feedrate_rapid": 1500,
  509. "excellon_z_pdepth": -0.02,
  510. "excellon_feedrate_probe": 75,
  511. "excellon_spindledir": 'CW',
  512. "excellon_f_plunge": False,
  513. "excellon_f_retract": False,
  514. # Excellon Export
  515. "excellon_exp_units": 'INCH',
  516. "excellon_exp_format": 'ndec',
  517. "excellon_exp_integer": 2,
  518. "excellon_exp_decimals": 4,
  519. "excellon_exp_zeros": 'LZ',
  520. "excellon_exp_slot_type": 'routing',
  521. # Excellon Editor
  522. "excellon_editor_sel_limit": 30,
  523. "excellon_editor_newdia": 1.0,
  524. "excellon_editor_array_size": 5,
  525. "excellon_editor_lin_dir": 'X',
  526. "excellon_editor_lin_pitch": 2.54,
  527. "excellon_editor_lin_angle": 0.0,
  528. "excellon_editor_circ_dir": 'CW',
  529. "excellon_editor_circ_angle": 12,
  530. # Excellon Slots
  531. "excellon_editor_slot_direction": 'X',
  532. "excellon_editor_slot_angle": 0.0,
  533. "excellon_editor_slot_length": 5.0,
  534. # Excellon Slot Array
  535. "excellon_editor_slot_array_size": 5,
  536. "excellon_editor_slot_lin_dir": 'X',
  537. "excellon_editor_slot_lin_pitch": 2.54,
  538. "excellon_editor_slot_lin_angle": 0.0,
  539. "excellon_editor_slot_circ_dir": 'CW',
  540. "excellon_editor_slot_circ_angle": 0.0,
  541. # Geometry General
  542. "geometry_plot": True,
  543. "geometry_circle_steps": 64,
  544. "geometry_cnctooldia": "2.4",
  545. # Geometry Options
  546. "geometry_cutz": -2.4,
  547. "geometry_vtipdia": 0.1,
  548. "geometry_vtipangle": 30,
  549. "geometry_multidepth": False,
  550. "geometry_depthperpass": 0.8,
  551. "geometry_travelz": 2,
  552. "geometry_toolchange": False,
  553. "geometry_toolchangez": 15.0,
  554. "geometry_endz": 15.0,
  555. "geometry_feedrate": 120,
  556. "geometry_feedrate_z": 60,
  557. "geometry_spindlespeed": None,
  558. "geometry_dwell": False,
  559. "geometry_dwelltime": 1,
  560. "geometry_ppname_g": 'default',
  561. # Geometry Advanced Options
  562. "geometry_toolchangexy": "0.0, 0.0",
  563. "geometry_startz": None,
  564. "geometry_feedrate_rapid": 1500,
  565. "geometry_extracut": False,
  566. "geometry_z_pdepth": -0.02,
  567. "geometry_f_plunge": False,
  568. "geometry_spindledir": 'CW',
  569. "geometry_feedrate_probe": 75,
  570. "geometry_segx": 0.0,
  571. "geometry_segy": 0.0,
  572. # Geometry Editor
  573. "geometry_editor_sel_limit": 30,
  574. "geometry_editor_milling_type": "cl",
  575. # CNC Job General
  576. "cncjob_plot": True,
  577. "cncjob_plot_kind": 'all',
  578. "cncjob_annotation": True,
  579. "cncjob_tooldia": 1.0,
  580. "cncjob_coords_type": "G90",
  581. "cncjob_coords_decimals": 4,
  582. "cncjob_fr_decimals": 2,
  583. "cncjob_steps_per_circle": 64,
  584. "cncjob_footer": False,
  585. "cncjob_line_ending": False,
  586. "cncjob_save_filters": "G-Code Files (*.nc);;G-Code Files (*.din);;G-Code Files (*.dnc);;"
  587. "G-Code Files (*.ecs);;G-Code Files (*.eia);;G-Code Files (*.fan);;"
  588. "G-Code Files (*.fgc);;G-Code Files (*.fnc);;G-Code Files (*.gc);;"
  589. "G-Code Files (*.gcd);;G-Code Files (*.gcode);;G-Code Files (*.h);;"
  590. "G-Code Files (*.hnc);;G-Code Files (*.i);;G-Code Files (*.min);;"
  591. "G-Code Files (*.mpf);;G-Code Files (*.mpr);;G-Code Files (*.cnc);;"
  592. "G-Code Files (*.ncc);;G-Code Files (*.ncg);;G-Code Files (*.ncp);;"
  593. "G-Code Files (*.ngc);;G-Code Files (*.out);;G-Code Files (*.ply);;"
  594. "G-Code Files (*.sbp);;G-Code Files (*.tap);;G-Code Files (*.xpi);;"
  595. "All Files (*.*)",
  596. # CNC Job Options
  597. "cncjob_prepend": "",
  598. "cncjob_append": "",
  599. # CNC Job Advanced Options
  600. "cncjob_toolchange_macro": "",
  601. "cncjob_toolchange_macro_enable": False,
  602. "cncjob_annotation_fontsize": 9,
  603. "cncjob_annotation_fontcolor": '#990000',
  604. # NCC Tool
  605. "tools_ncctools": "1.0, 0.5",
  606. "tools_nccorder": 'rev',
  607. "tools_nccoverlap": 40,
  608. "tools_nccmargin": 1.0,
  609. "tools_nccmethod": "seed",
  610. "tools_nccconnect": True,
  611. "tools_ncccontour": True,
  612. "tools_nccrest": False,
  613. "tools_ncc_offset_choice": False,
  614. "tools_ncc_offset_value": 0.0000,
  615. "tools_nccref": 'itself',
  616. "tools_ncc_plotting": 'normal',
  617. "tools_nccmilling_type": 'cl',
  618. "tools_ncctool_type": 'V',
  619. "tools_ncccutz": -0.05,
  620. "tools_ncctipdia": 0.1,
  621. "tools_ncctipangle": 30,
  622. "tools_nccnewdia": 1.0,
  623. # Cutout Tool
  624. "tools_cutouttooldia": 2.4,
  625. "tools_cutoutkind": "single",
  626. "tools_cutoutmargin": 0.1,
  627. "tools_cutout_z": -1.8,
  628. "tools_cutout_depthperpass": 0.6,
  629. "tools_cutout_mdepth": True,
  630. "tools_cutoutgapsize": 4,
  631. "tools_gaps_ff": "4",
  632. "tools_cutout_convexshape": False,
  633. # Paint Tool
  634. "tools_painttooldia": 0.3,
  635. "tools_paintorder": 'rev',
  636. "tools_paintoverlap": 20,
  637. "tools_paintmargin": 0.0,
  638. "tools_paintmethod": "seed",
  639. "tools_selectmethod": "all",
  640. "tools_pathconnect": True,
  641. "tools_paintcontour": True,
  642. "tools_paint_plotting": 'normal',
  643. # 2-Sided Tool
  644. "tools_2sided_mirror_axis": "X",
  645. "tools_2sided_axis_loc": "point",
  646. "tools_2sided_drilldia": 3.125,
  647. # Film Tool
  648. "tools_film_type": 'neg',
  649. "tools_film_boundary": 1.0,
  650. "tools_film_scale_stroke": 0,
  651. "tools_film_color": '#000000',
  652. "tools_film_scale_cb": False,
  653. "tools_film_scale_x_entry": 1.0,
  654. "tools_film_scale_y_entry": 1.0,
  655. "tools_film_skew_cb": False,
  656. "tools_film_skew_x_entry": 0.0,
  657. "tools_film_skew_y_entry": 0.0,
  658. "tools_film_skew_ref_radio": 'bottomleft',
  659. "tools_film_mirror_cb": False,
  660. "tools_film_mirror_axis_radio": 'none',
  661. "tools_film_file_type_radio": 'svg',
  662. "tools_film_orientation": 'p',
  663. "tools_film_pagesize": 'A4',
  664. # Panel Tool
  665. "tools_panelize_spacing_columns": 0,
  666. "tools_panelize_spacing_rows": 0,
  667. "tools_panelize_columns": 1,
  668. "tools_panelize_rows": 1,
  669. "tools_panelize_constrain": False,
  670. "tools_panelize_constrainx": 200.0,
  671. "tools_panelize_constrainy": 290.0,
  672. "tools_panelize_panel_type": 'gerber',
  673. # Calculators Tool
  674. "tools_calc_vshape_tip_dia": 0.2,
  675. "tools_calc_vshape_tip_angle": 30,
  676. "tools_calc_vshape_cut_z": 0.05,
  677. "tools_calc_electro_length": 10.0,
  678. "tools_calc_electro_width": 10.0,
  679. "tools_calc_electro_cdensity": 13.0,
  680. "tools_calc_electro_growth": 10.0,
  681. # Transform Tool
  682. "tools_transform_rotate": 90,
  683. "tools_transform_skew_x": 0.0,
  684. "tools_transform_skew_y": 0.0,
  685. "tools_transform_scale_x": 1.0,
  686. "tools_transform_scale_y": 1.0,
  687. "tools_transform_scale_link": True,
  688. "tools_transform_scale_reference": True,
  689. "tools_transform_offset_x": 0.0,
  690. "tools_transform_offset_y": 0.0,
  691. "tools_transform_mirror_reference": False,
  692. "tools_transform_mirror_point": (0, 0),
  693. # SolderPaste Tool
  694. "tools_solderpaste_tools": "1.0, 0.3",
  695. "tools_solderpaste_new": 0.3,
  696. "tools_solderpaste_z_start": 0.05,
  697. "tools_solderpaste_z_dispense": 0.1,
  698. "tools_solderpaste_z_stop": 0.05,
  699. "tools_solderpaste_z_travel": 0.1,
  700. "tools_solderpaste_z_toolchange": 1.0,
  701. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  702. "tools_solderpaste_frxy": 150,
  703. "tools_solderpaste_frz": 150,
  704. "tools_solderpaste_frz_dispense": 1.0,
  705. "tools_solderpaste_speedfwd": 300,
  706. "tools_solderpaste_dwellfwd": 1,
  707. "tools_solderpaste_speedrev": 200,
  708. "tools_solderpaste_dwellrev": 1,
  709. "tools_solderpaste_pp": 'Paste_1',
  710. # Subtract Tool
  711. "tools_sub_close_paths": True,
  712. # ###################################################################################
  713. # ################################ TOOLS 2 ##########################################
  714. # ###################################################################################
  715. # Optimal Tool
  716. "tools_opt_precision": 4,
  717. # Check Rules Tool
  718. "tools_cr_trace_size": True,
  719. "tools_cr_trace_size_val": 0.25,
  720. "tools_cr_c2c": True,
  721. "tools_cr_c2c_val": 0.25,
  722. "tools_cr_c2o": True,
  723. "tools_cr_c2o_val": 1.0,
  724. "tools_cr_s2s": True,
  725. "tools_cr_s2s_val": 0.25,
  726. "tools_cr_s2sm": True,
  727. "tools_cr_s2sm_val": 0.25,
  728. "tools_cr_s2o": True,
  729. "tools_cr_s2o_val": 1.0,
  730. "tools_cr_sm2sm": True,
  731. "tools_cr_sm2sm_val": 0.25,
  732. "tools_cr_ri": True,
  733. "tools_cr_ri_val": 0.3,
  734. "tools_cr_h2h": True,
  735. "tools_cr_h2h_val": 0.3,
  736. "tools_cr_dh": True,
  737. "tools_cr_dh_val": 0.3,
  738. # QRCode Tool
  739. "tools_qrcode_version": 1,
  740. "tools_qrcode_error": 'L',
  741. "tools_qrcode_box_size": 3,
  742. "tools_qrcode_border_size": 4,
  743. "tools_qrcode_qrdata": '',
  744. "tools_qrcode_polarity": 'pos',
  745. "tools_qrcode_rounded": 's',
  746. "tools_qrcode_fill_color": '#000000',
  747. "tools_qrcode_back_color": '#FFFFFF',
  748. "tools_qrcode_sel_limit": 330,
  749. # Copper Thieving Tool
  750. "tools_copper_thieving_clearance": 0.25,
  751. "tools_copper_thieving_margin": 1.0,
  752. "tools_copper_thieving_reference": 'itself',
  753. "tools_copper_thieving_box_type": 'rect',
  754. "tools_copper_thieving_circle_steps": 64,
  755. "tools_copper_thieving_fill_type": 'solid',
  756. "tools_copper_thieving_dots_dia": 1.0,
  757. "tools_copper_thieving_dots_spacing": 2.0,
  758. "tools_copper_thieving_squares_size": 1.0,
  759. "tools_copper_thieving_squares_spacing": 2.0,
  760. "tools_copper_thieving_lines_size": 0.25,
  761. "tools_copper_thieving_lines_spacing": 2.0,
  762. "tools_copper_thieving_rb_margin": 1.0,
  763. "tools_copper_thieving_rb_thickness": 1.0,
  764. "tools_copper_thieving_mask_clearance": 0.0,
  765. # Fiducials Tool
  766. "tools_fiducials_dia": 1.0,
  767. "tools_fiducials_margin": 1.0,
  768. "tools_fiducials_mode": 'auto',
  769. "tools_fiducials_second_pos": 'up',
  770. "tools_fiducials_type": 'circular',
  771. "tools_fiducials_line_thickness": 0.25,
  772. # Utilities
  773. # file associations
  774. "fa_excellon": 'drd, drl, exc, ncd, tap, xln',
  775. "fa_gcode": 'cnc, din, dnc, ecs, eia, fan, fgc, fnc, gc, gcd, gcode, h, hnc, i, min, mpf, mpr, nc, ncc, '
  776. 'ncg, ncp, ngc, out, plt, ply, rol, sbp, tap, xpi',
  777. "fa_gerber": 'art, bot, bsm, cmp, crc, crs, dim, gb0, gb1, gb2, gb3, gb4, gb5, gb6, gb7, gb8, gb9, gbd, '
  778. 'gbl, gbo, gbp, gbr, gbs, gdo, ger, gko, gm1, gm2, gm3, grb, gtl, gto, gtp, gts, ly15, ly2, '
  779. 'mil, pho, plc, pls, smb, smt, sol, spb, spt, ssb, sst, stc, sts, top, tsm',
  780. # Keyword list
  781. "util_autocomplete_keywords": 'Desktop, Documents, FlatConfig, FlatPrj, Marius, My Documents, Paste_1, '
  782. 'Repetier, Roland_MDX_20, Users, Toolchange_Custom, Toolchange_Probe_MACH3, '
  783. 'Toolchange_manual, Users, all, angle_x, angle_y, axis, auto, axisoffset, '
  784. 'box, center_x, center_y, columns, combine, connect, contour, default, '
  785. 'depthperpass, dia, diatol, dist, drilled_dias, drillz, dwell, dwelltime, '
  786. 'feedrate_z, grbl_11, grbl_laser, gridoffsety, gridx, gridy, has_offset, '
  787. 'holes, hpgl, iso_type, line_xyz, margin, marlin, method, milled_dias, '
  788. 'minoffset, multidepth, name, offset, opt_type, order, outname, overlap, '
  789. 'passes, postamble, pp, ppname_e, ppname_g, preamble, radius, ref, rest, '
  790. 'rows, shellvar_, scale_factor, spacing_columns, spacing_rows, spindlespeed, '
  791. 'toolchange_xy, tooldia, use_threads, value, x, x0, x1, y, y0, y1, z_cut, '
  792. 'z_move',
  793. "script_autocompleter": True,
  794. "script_text": "",
  795. "script_plot": True,
  796. "script_source_file": "",
  797. "document_autocompleter": False,
  798. "document_text": "",
  799. "document_plot": True,
  800. "document_source_file": "",
  801. "document_font_color": '#000000',
  802. "document_sel_color": '#0055ff',
  803. "document_font_size": 6,
  804. "document_tab_size": 80,
  805. })
  806. # ############################################################
  807. # ############### Load defaults from file ####################
  808. # ############################################################
  809. self.old_defaults_found = False
  810. if user_defaults:
  811. self.load_defaults(filename='current_defaults')
  812. # #############################################################################
  813. # ##################### CREATE MULTIPROCESSING POOL ###########################
  814. # #############################################################################
  815. self.pool = Pool(processes=cpu_count())
  816. # ##########################################################################
  817. # ################## Setting the Splash Screen #############################
  818. # ##########################################################################
  819. splash_settings = QSettings("Open Source", "FlatCAM")
  820. if splash_settings.contains("splash_screen"):
  821. show_splash = splash_settings.value("splash_screen")
  822. else:
  823. splash_settings.setValue('splash_screen', 1)
  824. # This will write the setting to the platform specific storage.
  825. del splash_settings
  826. show_splash = 1
  827. if show_splash and self.cmd_line_headless != 1:
  828. splash_pix = QtGui.QPixmap('share/splash.png')
  829. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  830. # self.splash.setMask(splash_pix.mask())
  831. # move splashscreen to the current monitor
  832. desktop = QtWidgets.QApplication.desktop()
  833. screen = desktop.screenNumber(QtGui.QCursor.pos())
  834. current_screen_center = desktop.availableGeometry(screen).center()
  835. self.splash.move(current_screen_center - self.splash.rect().center())
  836. self.splash.show()
  837. self.splash.showMessage(_("FlatCAM is initializing ..."),
  838. alignment=Qt.AlignBottom | Qt.AlignLeft,
  839. color=QtGui.QColor("gray"))
  840. else:
  841. show_splash = 0
  842. # #############################################################################
  843. # ##################### Initialize GUI ########################################
  844. # #############################################################################
  845. # FlatCAM colors used in plotting
  846. self.FC_light_green = '#BBF268BF'
  847. self.FC_dark_green = '#006E20BF'
  848. self.FC_light_blue = '#a5a5ffbf'
  849. self.FC_dark_blue = '#0000ffbf'
  850. QtCore.QObject.__init__(self)
  851. self.ui = FlatCAMGUI(self.version, self.beta, self)
  852. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  853. if theme_settings.contains("theme"):
  854. theme = theme_settings.value('theme', type=str)
  855. else:
  856. theme = 'white'
  857. if theme == 'white':
  858. self.cursor_color_3D = 'black'
  859. else:
  860. self.cursor_color_3D = 'gray'
  861. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  862. self.ui.final_save.connect(self.final_save)
  863. # restore the toolbar view
  864. self.restore_toolbar_view()
  865. # restore the GUI geometry
  866. self.restore_main_win_geom()
  867. # set FlatCAM units in the Status bar
  868. self.set_screen_units(self.defaults['units'])
  869. # #############################################################################
  870. # ######################## UPDATE PREFERENCES GUI FORMS #######################
  871. # #############################################################################
  872. # when adding entries here read the comments in the method found bellow named:
  873. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  874. self.defaults_form_fields = {
  875. # General App
  876. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  877. "global_graphic_engine": self.ui.general_defaults_form.general_app_group.ge_radio,
  878. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  879. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  880. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  881. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  882. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  883. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  884. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  885. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  886. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  887. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  888. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_spinner,
  889. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  890. "global_bookmarks_limit": self.ui.general_defaults_form.general_app_group.bm_limit_spinner,
  891. "global_machinist_setting": self.ui.general_defaults_form.general_app_group.machinist_cb,
  892. # General GUI Preferences
  893. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  894. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  895. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  896. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  897. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  898. "global_workspace_orientation": self.ui.general_defaults_form.general_gui_group.wk_orientation_radio,
  899. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  900. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  901. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  902. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  903. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  904. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  905. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  906. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  907. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  908. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  909. "global_activity_icon": self.ui.general_defaults_form.general_gui_group.activity_combo,
  910. # General GUI Settings
  911. "global_theme": self.ui.general_defaults_form.general_gui_set_group.theme_radio,
  912. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  913. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  914. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  915. "global_systray_icon": self.ui.general_defaults_form.general_gui_set_group.systray_cb,
  916. "global_shell_at_startup": self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb,
  917. "global_project_at_startup": self.ui.general_defaults_form.general_gui_set_group.project_startup_cb,
  918. "global_project_autohide": self.ui.general_defaults_form.general_gui_set_group.project_autohide_cb,
  919. "global_toggle_tooltips": self.ui.general_defaults_form.general_gui_set_group.toggle_tooltips_cb,
  920. "global_delete_confirmation": self.ui.general_defaults_form.general_gui_set_group.delete_conf_cb,
  921. "global_cursor_type": self.ui.general_defaults_form.general_gui_set_group.cursor_radio,
  922. "global_cursor_size": self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry,
  923. # Gerber General
  924. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  925. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  926. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  927. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  928. "gerber_def_units": self.ui.gerber_defaults_form.gerber_gen_group.gerber_units_radio,
  929. "gerber_def_zeros": self.ui.gerber_defaults_form.gerber_gen_group.gerber_zeros_radio,
  930. # Gerber Options
  931. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  932. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  933. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  934. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  935. "gerber_iso_scope": self.ui.gerber_defaults_form.gerber_opt_group.iso_scope_radio,
  936. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  937. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  938. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  939. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  940. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  941. # Gerber Advanced Options
  942. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  943. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  944. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  945. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  946. "gerber_tool_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.tool_type_radio,
  947. "gerber_vtipdia": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipdia_spinner,
  948. "gerber_vtipangle": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipangle_spinner,
  949. "gerber_vcutz": self.ui.gerber_defaults_form.gerber_adv_opt_group.cutz_spinner,
  950. "gerber_iso_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.iso_type_radio,
  951. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  952. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  953. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  954. # Gerber Export
  955. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  956. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  957. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  958. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  959. # Gerber Editor
  960. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  961. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  962. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  963. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  964. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  965. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  966. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  967. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  968. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  969. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  970. "gerber_editor_circ_angle":
  971. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  972. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  973. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  974. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  975. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  976. # Excellon General
  977. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  978. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  979. "excellon_format_upper_in":
  980. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  981. "excellon_format_lower_in":
  982. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  983. "excellon_format_upper_mm":
  984. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  985. "excellon_format_lower_mm":
  986. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  987. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  988. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  989. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  990. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  991. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  992. # Excellon Options
  993. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  994. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  995. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.eendz_entry,
  996. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  997. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  998. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  999. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  1000. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  1001. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  1002. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  1003. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  1004. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  1005. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  1006. # Excellon Advanced Options
  1007. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  1008. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  1009. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  1010. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1011. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  1012. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  1013. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  1014. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  1015. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  1016. # Excellon Export
  1017. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  1018. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  1019. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  1020. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  1021. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  1022. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  1023. # Excellon Editor
  1024. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  1025. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  1026. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  1027. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  1028. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  1029. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  1030. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  1031. "excellon_editor_circ_angle":
  1032. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  1033. # Excellon Slots
  1034. "excellon_editor_slot_direction":
  1035. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  1036. "excellon_editor_slot_angle":
  1037. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  1038. "excellon_editor_slot_length":
  1039. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  1040. # Excellon Slots
  1041. "excellon_editor_slot_array_size":
  1042. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  1043. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  1044. "excellon_editor_slot_lin_pitch":
  1045. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  1046. "excellon_editor_slot_lin_angle":
  1047. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  1048. "excellon_editor_slot_circ_dir":
  1049. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  1050. "excellon_editor_slot_circ_angle":
  1051. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  1052. # Geometry General
  1053. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  1054. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  1055. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  1056. # Geometry Options
  1057. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  1058. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  1059. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  1060. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  1061. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  1062. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  1063. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  1064. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  1065. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  1066. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  1067. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.gendz_entry,
  1068. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  1069. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  1070. # Geometry Advanced Options
  1071. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  1072. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  1073. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1074. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  1075. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  1076. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  1077. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  1078. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  1079. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  1080. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  1081. # Geometry Editor
  1082. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  1083. "geometry_editor_milling_type": self.ui.geometry_defaults_form.geometry_editor_group.milling_type_radio,
  1084. # CNCJob General
  1085. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  1086. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  1087. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  1088. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  1089. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  1090. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  1091. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  1092. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  1093. "cncjob_line_ending": self.ui.cncjob_defaults_form.cncjob_gen_group.line_ending_cb,
  1094. # CNC Job Options
  1095. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  1096. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  1097. # CNC Job Advanced Options
  1098. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  1099. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  1100. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  1101. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  1102. # NCC Tool
  1103. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  1104. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  1105. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  1106. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  1107. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  1108. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  1109. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  1110. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  1111. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  1112. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  1113. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  1114. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  1115. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  1116. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  1117. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  1118. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  1119. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  1120. "tools_nccnewdia": self.ui.tools_defaults_form.tools_ncc_group.newdia_entry,
  1121. # CutOut Tool
  1122. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  1123. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  1124. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  1125. "tools_cutout_z": self.ui.tools_defaults_form.tools_cutout_group.cutz_entry,
  1126. "tools_cutout_depthperpass": self.ui.tools_defaults_form.tools_cutout_group.maxdepth_entry,
  1127. "tools_cutout_mdepth": self.ui.tools_defaults_form.tools_cutout_group.mpass_cb,
  1128. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  1129. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  1130. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  1131. # Paint Area Tool
  1132. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  1133. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  1134. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  1135. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  1136. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  1137. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  1138. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  1139. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  1140. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  1141. # 2-sided Tool
  1142. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  1143. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  1144. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  1145. # Film Tool
  1146. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  1147. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  1148. "tools_film_scale_stroke": self.ui.tools_defaults_form.tools_film_group.film_scale_stroke_entry,
  1149. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  1150. "tools_film_scale_cb": self.ui.tools_defaults_form.tools_film_group.film_scale_cb,
  1151. "tools_film_scale_x_entry": self.ui.tools_defaults_form.tools_film_group.film_scalex_entry,
  1152. "tools_film_scale_y_entry": self.ui.tools_defaults_form.tools_film_group.film_scaley_entry,
  1153. "tools_film_skew_cb": self.ui.tools_defaults_form.tools_film_group.film_skew_cb,
  1154. "tools_film_skew_x_entry": self.ui.tools_defaults_form.tools_film_group.film_skewx_entry,
  1155. "tools_film_skew_y_entry": self.ui.tools_defaults_form.tools_film_group.film_skewy_entry,
  1156. "tools_film_skew_ref_radio": self.ui.tools_defaults_form.tools_film_group.film_skew_reference,
  1157. "tools_film_mirror_cb": self.ui.tools_defaults_form.tools_film_group.film_mirror_cb,
  1158. "tools_film_mirror_axis_radio": self.ui.tools_defaults_form.tools_film_group.film_mirror_axis,
  1159. "tools_film_file_type_radio": self.ui.tools_defaults_form.tools_film_group.file_type_radio,
  1160. "tools_film_orientation": self.ui.tools_defaults_form.tools_film_group.orientation_radio,
  1161. "tools_film_pagesize": self.ui.tools_defaults_form.tools_film_group.pagesize_combo,
  1162. # Panelize Tool
  1163. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  1164. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  1165. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  1166. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  1167. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  1168. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  1169. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  1170. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  1171. # Calculators Tool
  1172. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  1173. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  1174. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  1175. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  1176. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  1177. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  1178. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  1179. # Transformations Tool
  1180. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  1181. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  1182. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  1183. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  1184. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  1185. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  1186. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  1187. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  1188. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  1189. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  1190. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  1191. # SolderPaste Dispensing Tool
  1192. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  1193. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  1194. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  1195. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  1196. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  1197. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  1198. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  1199. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  1200. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  1201. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  1202. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  1203. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  1204. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  1205. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  1206. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  1207. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  1208. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  1209. # ###################################################################################
  1210. # ################################ TOOLS 2 ##########################################
  1211. # ###################################################################################
  1212. # Optimal Tool
  1213. "tools_opt_precision": self.ui.tools2_defaults_form.tools2_optimal_group.precision_sp,
  1214. # Check Rules Tool
  1215. "tools_cr_trace_size": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_cb,
  1216. "tools_cr_trace_size_val": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_entry,
  1217. "tools_cr_c2c": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_cb,
  1218. "tools_cr_c2c_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_entry,
  1219. "tools_cr_c2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_cb,
  1220. "tools_cr_c2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_entry,
  1221. "tools_cr_s2s": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_cb,
  1222. "tools_cr_s2s_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_entry,
  1223. "tools_cr_s2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_cb,
  1224. "tools_cr_s2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_entry,
  1225. "tools_cr_s2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_cb,
  1226. "tools_cr_s2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_entry,
  1227. "tools_cr_sm2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_cb,
  1228. "tools_cr_sm2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_entry,
  1229. "tools_cr_ri": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_cb,
  1230. "tools_cr_ri_val": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_entry,
  1231. "tools_cr_h2h": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_cb,
  1232. "tools_cr_h2h_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_entry,
  1233. "tools_cr_dh": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_cb,
  1234. "tools_cr_dh_val": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_entry,
  1235. # QRCode Tool
  1236. "tools_qrcode_version": self.ui.tools2_defaults_form.tools2_qrcode_group.version_entry,
  1237. "tools_qrcode_error": self.ui.tools2_defaults_form.tools2_qrcode_group.error_radio,
  1238. "tools_qrcode_box_size": self.ui.tools2_defaults_form.tools2_qrcode_group.bsize_entry,
  1239. "tools_qrcode_border_size": self.ui.tools2_defaults_form.tools2_qrcode_group.border_size_entry,
  1240. "tools_qrcode_qrdata": self.ui.tools2_defaults_form.tools2_qrcode_group.text_data,
  1241. "tools_qrcode_polarity": self.ui.tools2_defaults_form.tools2_qrcode_group.pol_radio,
  1242. "tools_qrcode_rounded": self.ui.tools2_defaults_form.tools2_qrcode_group.bb_radio,
  1243. "tools_qrcode_fill_color": self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry,
  1244. "tools_qrcode_back_color": self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry,
  1245. "tools_qrcode_sel_limit": self.ui.tools2_defaults_form.tools2_qrcode_group.sel_limit_entry,
  1246. # Copper Thieving Tool
  1247. "tools_copper_thieving_clearance": self.ui.tools2_defaults_form.tools2_cfill_group.clearance_entry,
  1248. "tools_copper_thieving_margin": self.ui.tools2_defaults_form.tools2_cfill_group.margin_entry,
  1249. "tools_copper_thieving_reference": self.ui.tools2_defaults_form.tools2_cfill_group.reference_radio,
  1250. "tools_copper_thieving_box_type": self.ui.tools2_defaults_form.tools2_cfill_group.bbox_type_radio,
  1251. "tools_copper_thieving_circle_steps": self.ui.tools2_defaults_form.tools2_cfill_group.circlesteps_entry,
  1252. "tools_copper_thieving_fill_type": self.ui.tools2_defaults_form.tools2_cfill_group.fill_type_radio,
  1253. "tools_copper_thieving_dots_dia": self.ui.tools2_defaults_form.tools2_cfill_group.dot_dia_entry,
  1254. "tools_copper_thieving_dots_spacing": self.ui.tools2_defaults_form.tools2_cfill_group.dot_spacing_entry,
  1255. "tools_copper_thieving_squares_size": self.ui.tools2_defaults_form.tools2_cfill_group.square_size_entry,
  1256. "tools_copper_thieving_squares_spacing":
  1257. self.ui.tools2_defaults_form.tools2_cfill_group.squares_spacing_entry,
  1258. "tools_copper_thieving_lines_size": self.ui.tools2_defaults_form.tools2_cfill_group.line_size_entry,
  1259. "tools_copper_thieving_lines_spacing": self.ui.tools2_defaults_form.tools2_cfill_group.lines_spacing_entry,
  1260. "tools_copper_thieving_rb_margin": self.ui.tools2_defaults_form.tools2_cfill_group.rb_margin_entry,
  1261. "tools_copper_thieving_rb_thickness": self.ui.tools2_defaults_form.tools2_cfill_group.rb_thickness_entry,
  1262. "tools_copper_thieving_mask_clearance": self.ui.tools2_defaults_form.tools2_cfill_group.clearance_ppm_entry,
  1263. # Fiducials Tool
  1264. "tools_fiducials_dia": self.ui.tools2_defaults_form.tools2_fiducials_group.dia_entry,
  1265. "tools_fiducials_margin": self.ui.tools2_defaults_form.tools2_fiducials_group.margin_entry,
  1266. "tools_fiducials_mode": self.ui.tools2_defaults_form.tools2_fiducials_group.mode_radio,
  1267. "tools_fiducials_second_pos": self.ui.tools2_defaults_form.tools2_fiducials_group.pos_radio,
  1268. "tools_fiducials_type": self.ui.tools2_defaults_form.tools2_fiducials_group.fid_type_radio,
  1269. "tools_fiducials_line_thickness": self.ui.tools2_defaults_form.tools2_fiducials_group.line_thickness_entry,
  1270. # Utilities
  1271. # File associations
  1272. "fa_excellon": self.ui.util_defaults_form.fa_excellon_group.exc_list_text,
  1273. "fa_gcode": self.ui.util_defaults_form.fa_gcode_group.gco_list_text,
  1274. # "fa_geometry": self.ui.util_defaults_form.fa_geometry_group.close_paths_cb,
  1275. "fa_gerber": self.ui.util_defaults_form.fa_gerber_group.grb_list_text,
  1276. "util_autocomplete_keywords": self.ui.util_defaults_form.kw_group.kw_list_text,
  1277. }
  1278. # update the Preferences GUI elements with the values in the self.defaults
  1279. self.defaults_write_form()
  1280. # When the self.defaults dictionary changes will update the Preferences GUI forms
  1281. self.defaults.set_change_callback(self.on_defaults_dict_change)
  1282. # #############################################################################
  1283. # ############################## Data #########################################
  1284. # #############################################################################
  1285. self.recent = []
  1286. self.recent_projects = []
  1287. self.clipboard = QtWidgets.QApplication.clipboard()
  1288. self.project_filename = None
  1289. self.toggle_units_ignore = False
  1290. # #############################################################################
  1291. # ########################## LOAD POSTPROCESSORS ##############################
  1292. # #############################################################################
  1293. # a dictionary that have as keys the name of the postprocessor files and the value is the class from
  1294. # the postprocessor file
  1295. self.postprocessors = load_postprocessors(self)
  1296. # make sure that always the 'default' postprocessor is the first item in the dictionary
  1297. if 'default' in self.postprocessors.keys():
  1298. new_ppp_dict = dict()
  1299. # add the 'default' name first in the dict after removing from the postprocessor's dictionary
  1300. default_pp = self.postprocessors.pop('default')
  1301. new_ppp_dict['default'] = default_pp
  1302. # then add the rest of the keys
  1303. for name, val_class in self.postprocessors.items():
  1304. new_ppp_dict[name] = val_class
  1305. # and now put back the ordered dict with 'default' key first
  1306. self.postprocessors = new_ppp_dict
  1307. for name in list(self.postprocessors.keys()):
  1308. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  1309. if name.partition('_')[0] == 'Paste':
  1310. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  1311. continue
  1312. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1313. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  1314. if name == 'hpgl':
  1315. continue
  1316. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1317. # #############################################################################
  1318. # ########################## LOAD LANGUAGES ##################################
  1319. # #############################################################################
  1320. self.languages = fcTranslate.load_languages()
  1321. for name in sorted(self.languages.values()):
  1322. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  1323. # #############################################################################
  1324. # ############################ APPLY APP LANGUAGE #############################
  1325. # #############################################################################
  1326. ret_val = fcTranslate.apply_language('strings')
  1327. if ret_val == "no language":
  1328. self.inform.emit('[ERROR] %s' %
  1329. _("Could not find the Language files. The App strings are missing."))
  1330. log.debug("Could not find the Language files. The App strings are missing.")
  1331. else:
  1332. # make the current language the current selection on the language combobox
  1333. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1334. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1335. # #############################################################################
  1336. # ########################### CREATE UNIQUE SERIAL NUMBER #####################
  1337. # #############################################################################
  1338. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1339. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1340. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  1341. self.save_defaults(silent=True, first_time=True)
  1342. self.propagate_defaults(silent=True)
  1343. # def auto_save_defaults():
  1344. # try:
  1345. # self.save_defaults(silent=True)
  1346. # self.propagate_defaults(silent=True)
  1347. # finally:
  1348. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1349. # the following lines activates automatic defaults save
  1350. # if user_defaults:
  1351. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1352. # #############################################################################
  1353. # ########################### UPDATE THE OPTIONS ##############################
  1354. # #############################################################################
  1355. self.options = LoudDict()
  1356. # ----------------------------------------------------------------------------------------------------
  1357. # Update the self.options from the self.defaults
  1358. # The self.defaults holds the application defaults while the self.options holds the object defaults
  1359. # -----------------------------------------------------------------------------------------------------
  1360. # Copy app defaults to project options
  1361. for def_key, def_val in self.defaults.items():
  1362. self.options[def_key] = deepcopy(def_val)
  1363. # self.options.update(self.defaults)
  1364. self.gen_form = None
  1365. self.ger_form = None
  1366. self.exc_form = None
  1367. self.geo_form = None
  1368. self.cnc_form = None
  1369. self.tools_form = None
  1370. self.tools2_form = None
  1371. self.fa_form = None
  1372. # Will show the Preferences GUI
  1373. self.show_preferences_gui()
  1374. # Initialize the color box's color in Preferences -> Global -> Color
  1375. self.init_color_pickers_in_preferences_gui()
  1376. # ### End of Data ####
  1377. # #############################################################################
  1378. # ######################## SETUP OBJECT COLLECTION ############################
  1379. # #############################################################################
  1380. self.collection = ObjectCollection(self)
  1381. self.ui.project_tab_layout.addWidget(self.collection.view)
  1382. # ### Adjust tabs width ## ##
  1383. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1384. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1385. self.collection.view.setMinimumWidth(290)
  1386. self.log.debug("Finished creating Object Collection.")
  1387. # #############################################################################
  1388. # ############################## SETUP Plot Area ##############################
  1389. # #############################################################################
  1390. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  1391. if self.defaults["global_graphic_engine"] == '3D':
  1392. self.is_legacy = False
  1393. else:
  1394. self.is_legacy = True
  1395. # Event signals disconnect id holders
  1396. self.mp = None
  1397. self.mm = None
  1398. self.mr = None
  1399. self.mdc = None
  1400. self.mp_zc = None
  1401. # Matplotlib axis
  1402. self.axes = None
  1403. if show_splash:
  1404. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1405. "Canvas initialization started."),
  1406. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1407. color=QtGui.QColor("gray"))
  1408. start_plot_time = time.time() # debug
  1409. self.plotcanvas = None
  1410. self.app_cursor = None
  1411. self.hover_shapes = None
  1412. # setup the PlotCanvas
  1413. self.on_plotcanvas_setup()
  1414. end_plot_time = time.time()
  1415. self.used_time = end_plot_time - start_plot_time
  1416. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1417. if show_splash:
  1418. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1419. "Canvas initialization started.\n"
  1420. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1421. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1422. color=QtGui.QColor("gray"))
  1423. self.ui.splitter.setStretchFactor(1, 2)
  1424. # #############################################################################
  1425. # ################################### SYS TRAY ################################
  1426. # #############################################################################
  1427. if self.defaults["global_systray_icon"]:
  1428. self.parent_w = QtWidgets.QWidget()
  1429. if self.cmd_line_headless == 1:
  1430. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1431. headless=True,
  1432. parent=self.parent_w)
  1433. else:
  1434. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1435. parent=self.parent_w)
  1436. # #############################################################################
  1437. # ################################## Worker SETUP #############################
  1438. # #############################################################################
  1439. if self.defaults["global_worker_number"]:
  1440. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1441. else:
  1442. self.workers = WorkerStack(workers_number=2)
  1443. self.worker_task.connect(self.workers.add_task)
  1444. self.log.debug("Finished creating Workers crew.")
  1445. # #############################################################################
  1446. # ################################# Activity Monitor ##########################
  1447. # #############################################################################
  1448. self.activity_view = FlatCAMActivityView(app=self)
  1449. self.ui.infobar.addWidget(self.activity_view)
  1450. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  1451. # #############################################################################
  1452. # ################################## Signal handling ##########################
  1453. # #############################################################################
  1454. # ################################# Custom signals ###########################
  1455. # signal for displaying messages in status bar
  1456. self.inform.connect(self.info)
  1457. # signal to be called when the app is quiting
  1458. self.app_quit.connect(self.quit_application)
  1459. self.message.connect(self.message_dialog)
  1460. self.progress.connect(self.set_progress_bar)
  1461. # signals that are emitted when object state changes
  1462. self.object_created.connect(self.on_object_created)
  1463. self.object_changed.connect(self.on_object_changed)
  1464. self.object_plotted.connect(self.on_object_plotted)
  1465. self.plots_updated.connect(self.on_plots_updated)
  1466. # signals emitted when file state change
  1467. self.file_opened.connect(self.register_recent)
  1468. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1469. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1470. # ############# Standard signals ###################
  1471. # ### Menu
  1472. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1473. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1474. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1475. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1476. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  1477. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1478. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1479. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1480. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1481. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1482. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1483. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1484. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1485. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1486. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1487. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1488. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1489. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1490. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1491. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1492. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1493. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1494. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1495. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1496. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1497. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1498. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1499. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1500. self.ui.menufile_exit.triggered.connect(self.final_save)
  1501. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1502. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1503. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1504. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1505. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1506. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1507. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1508. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1509. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1510. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1511. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1512. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1513. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1514. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1515. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1516. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1517. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1518. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1519. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1520. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1521. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1522. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1523. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1524. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1525. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1526. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1527. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1528. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1529. self.ui.menuoptions_tools_db.triggered.connect(self.on_tools_database)
  1530. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1531. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1532. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1533. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1534. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1535. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1536. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1537. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1538. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1539. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1540. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1541. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  1542. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1543. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  1544. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1545. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  1546. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1547. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1548. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1549. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1550. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1551. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1552. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1553. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1554. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1555. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1556. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1557. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1558. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1559. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1560. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1561. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1562. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1563. # ToolBar signals
  1564. self.connect_toolbar_signals()
  1565. # Notebook and Plot Tab Area signals
  1566. # make the right click on the notebook tab and plot tab area tab raise a menu
  1567. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1568. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1569. self.on_tab_setup_context_menu()
  1570. # activate initial state
  1571. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1572. # Context Menu
  1573. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1574. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1575. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1576. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1577. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1578. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1579. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1580. self.ui.clearplot.triggered.connect(self.clear_plots)
  1581. self.ui.replot.triggered.connect(self.plot_all)
  1582. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1583. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1584. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1585. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1586. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1587. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1588. # Preferences Plot Area TAB
  1589. self.ui.pref_save_button.clicked.connect(lambda: self.on_save_button(save_to_file=True))
  1590. self.ui.pref_apply_button.clicked.connect(lambda: self.on_save_button(save_to_file=False))
  1591. self.ui.pref_close_button.clicked.connect(self.on_pref_close_button)
  1592. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1593. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1594. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1595. # #############################################################################
  1596. # ######################### GUI PREFERENCES SIGNALS ###########################
  1597. # #############################################################################
  1598. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  1599. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1600. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1601. )
  1602. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1603. lambda: self.on_toggle_units(no_pref=False))
  1604. # #############################################################################
  1605. # ############################# GUI COLORS SIGNALS ############################
  1606. # #############################################################################
  1607. # Setting plot colors signals
  1608. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1609. self.on_pf_color_entry)
  1610. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1611. self.on_pf_color_button)
  1612. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1613. self.on_pf_color_spinner)
  1614. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1615. self.on_pf_color_slider)
  1616. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1617. self.on_pl_color_entry)
  1618. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1619. self.on_pl_color_button)
  1620. # Setting selection (left - right) colors signals
  1621. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1622. self.on_sf_color_entry)
  1623. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1624. self.on_sf_color_button)
  1625. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1626. self.on_sf_color_spinner)
  1627. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1628. self.on_sf_color_slider)
  1629. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1630. self.on_sl_color_entry)
  1631. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1632. self.on_sl_color_button)
  1633. # Setting selection (right - left) colors signals
  1634. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1635. self.on_alt_sf_color_entry)
  1636. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1637. self.on_alt_sf_color_button)
  1638. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1639. self.on_alt_sf_color_spinner)
  1640. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1641. self.on_alt_sf_color_slider)
  1642. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1643. self.on_alt_sl_color_entry)
  1644. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1645. self.on_alt_sl_color_button)
  1646. # Setting Editor Draw colors signals
  1647. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1648. self.on_draw_color_entry)
  1649. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1650. self.on_draw_color_button)
  1651. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1652. self.on_sel_draw_color_entry)
  1653. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1654. self.on_sel_draw_color_button)
  1655. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1656. self.on_proj_color_entry)
  1657. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1658. self.on_proj_color_button)
  1659. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1660. self.on_proj_color_dis_entry)
  1661. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1662. self.on_proj_color_dis_button)
  1663. # ############################# workspace setting signals #####################
  1664. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1665. self.ui.general_defaults_form.general_gui_group.wk_orientation_radio.activated_custom.connect(
  1666. self.on_workspace_modified
  1667. )
  1668. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1669. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1670. # #############################################################################
  1671. # ############################# GUI SETTINGS SIGNALS ##########################
  1672. # #############################################################################
  1673. self.ui.general_defaults_form.general_gui_set_group.theme_radio.activated_custom.connect(self.on_theme_change)
  1674. self.ui.general_defaults_form.general_gui_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  1675. # ########## CNC Job related signals #############
  1676. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1677. self.on_cnc_custom_parameters)
  1678. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.editingFinished.connect(
  1679. self.on_annotation_fontcolor_entry)
  1680. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.clicked.connect(
  1681. self.on_annotation_fontcolor_button)
  1682. # ########## Tools related signals #############
  1683. # Film Tool
  1684. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1685. self.on_film_color_entry)
  1686. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1687. self.on_film_color_button)
  1688. # QRCode Tool
  1689. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  1690. self.on_qrcode_fill_color_entry)
  1691. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  1692. self.on_qrcode_fill_color_button)
  1693. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  1694. self.on_qrcode_back_color_entry)
  1695. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  1696. self.on_qrcode_back_color_button)
  1697. # portability changed signal
  1698. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1699. # Object list
  1700. self.collection.view.activated.connect(self.on_row_activated)
  1701. self.collection.item_selected.connect(self.on_row_selected)
  1702. self.object_status_changed.connect(self.on_collection_updated)
  1703. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1704. self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1705. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1706. # Export Excellon parameters.
  1707. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1708. self.on_update_exc_export
  1709. )
  1710. # call it once to make sure it is updated at startup
  1711. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1712. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1713. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1714. self.on_excellon_defaults_button)
  1715. # when there are arguments at application startup this get launched
  1716. self.args_at_startup[list].connect(self.on_startup_args)
  1717. # #############################################################################
  1718. # ########################## FILE ASSOCIATIONS SIGNALS ########################
  1719. # #############################################################################
  1720. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1721. lambda: self.restore_extensions(ext_type='excellon'))
  1722. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1723. lambda: self.restore_extensions(ext_type='gcode'))
  1724. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1725. lambda: self.restore_extensions(ext_type='gerber'))
  1726. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1727. lambda: self.delete_all_extensions(ext_type='excellon'))
  1728. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1729. lambda: self.delete_all_extensions(ext_type='gcode'))
  1730. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1731. lambda: self.delete_all_extensions(ext_type='gerber'))
  1732. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1733. lambda: self.add_extension(ext_type='excellon'))
  1734. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1735. lambda: self.add_extension(ext_type='gcode'))
  1736. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1737. lambda: self.add_extension(ext_type='gerber'))
  1738. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1739. lambda: self.del_extension(ext_type='excellon'))
  1740. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1741. lambda: self.del_extension(ext_type='gcode'))
  1742. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1743. lambda: self.del_extension(ext_type='gerber'))
  1744. # connect the 'Apply' buttons from the Preferences/File Associations
  1745. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1746. lambda: self.on_register_files(obj_type='excellon'))
  1747. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1748. lambda: self.on_register_files(obj_type='gcode'))
  1749. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1750. lambda: self.on_register_files(obj_type='gerber'))
  1751. # #############################################################################
  1752. # ################################ KEYWORDS SIGNALS ###########################
  1753. # #############################################################################
  1754. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1755. lambda: self.restore_extensions(ext_type='keyword'))
  1756. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1757. lambda: self.delete_all_extensions(ext_type='keyword'))
  1758. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1759. lambda: self.add_extension(ext_type='keyword'))
  1760. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1761. lambda: self.del_extension(ext_type='keyword'))
  1762. # splash screen button signal
  1763. self.ui.general_defaults_form.general_gui_set_group.splash_cb.stateChanged.connect(self.on_splash_changed)
  1764. # connect the abort_all_tasks related slots to the related signals
  1765. self.proc_container.idle_flag.connect(self.app_is_idle)
  1766. # signal emitted when a tab is closed in the Plot Area
  1767. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  1768. # #####################################################################################
  1769. # ########### FINISHED CONNECTING SIGNALS #############################################
  1770. # #####################################################################################
  1771. self.log.debug("Finished connecting Signals.")
  1772. # #####################################################################################
  1773. # ########################## Other setups #############################################
  1774. # #####################################################################################
  1775. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  1776. # depending on from where those tools are called different actions can be done
  1777. self.call_source = 'app'
  1778. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1779. self.tool_tab_locked = False
  1780. # decide if to show or hide the Notebook side of the screen at startup
  1781. if self.defaults["global_project_at_startup"] is True:
  1782. self.ui.splitter.setSizes([1, 1])
  1783. else:
  1784. self.ui.splitter.setSizes([0, 1])
  1785. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1786. self.setup_obj_classes()
  1787. self.setup_component_editor()
  1788. # #####################################################################################
  1789. # ######################### Auto-complete KEYWORDS ####################################
  1790. # #####################################################################################
  1791. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1792. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1793. 'delete', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon', 'ee', 'export_exc',
  1794. 'export_gcode', 'export_gerber', 'egr', 'export_svg', 'ext', 'exteriors', 'follow',
  1795. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1796. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1797. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1798. 'mirror', 'ncc',
  1799. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1800. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'origin',
  1801. 'paint', 'pan', 'panel', 'panelize', 'plot_all', 'plot_objects', 'quit_flatcam',
  1802. 'save', 'save_project',
  1803. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_sys',
  1804. 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1805. 'version', 'write_gcode'
  1806. ]
  1807. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'Marius', 'My Documents', 'Paste_1',
  1808. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  1809. 'Toolchange_manual', 'Users', 'all', 'angle_x', 'angle_y', 'auto', 'axis',
  1810. 'axisoffset',
  1811. 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect', 'contour', 'default',
  1812. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dwell',
  1813. 'dwelltime', 'feedrate_z', 'grbl_11', 'grbl_laser', 'gridoffsety', 'gridx', 'gridy',
  1814. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  1815. 'milled_dias', 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order',
  1816. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  1817. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  1818. 'spacing_columns',
  1819. 'spacing_rows', 'spindlespeed', 'toolchange_xy', 'tooldia', 'use_threads', 'value',
  1820. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1821. ]
  1822. self.tcl_keywords = [
  1823. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1824. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1825. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1826. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1827. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1828. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1829. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1830. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1831. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1832. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1833. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1834. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1835. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1836. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1837. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1838. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1839. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1840. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1841. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1842. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1843. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1844. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1845. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1846. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1847. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1848. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1849. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1850. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1851. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1852. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1853. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1854. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1855. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1856. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1857. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1858. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1859. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1860. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1861. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1862. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1863. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1864. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1865. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1866. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1867. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1868. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1869. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1870. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1871. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1872. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1873. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1874. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1875. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1876. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1877. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1878. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1879. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1880. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1881. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1882. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1883. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1884. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1885. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1886. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1887. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1888. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1889. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1890. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1891. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1892. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1893. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1894. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1895. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1896. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1897. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1898. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1899. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1900. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1901. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1902. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1903. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1904. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1905. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1906. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1907. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1908. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1909. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1910. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1911. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1912. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1913. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1914. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1915. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1916. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1917. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1918. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1919. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1920. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1921. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1922. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1923. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1924. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1925. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1926. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1927. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1928. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1929. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1930. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1931. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1932. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1933. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1934. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1935. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1936. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1937. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1938. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1939. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1940. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1941. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1942. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1943. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1944. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1945. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1946. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1947. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1948. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1949. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1950. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1951. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1952. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1953. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1954. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1955. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1956. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1957. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1958. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1959. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1960. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1961. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1962. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1963. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1964. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1965. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1966. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1967. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1968. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1969. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1970. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1971. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1972. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1973. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1974. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1975. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1976. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1977. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1978. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1979. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1980. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1981. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1982. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1983. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1984. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1985. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1986. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1987. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1988. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1989. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1990. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1991. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1992. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1993. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1994. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1995. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1996. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1997. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1998. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1999. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  2000. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  2001. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  2002. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  2003. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  2004. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  2005. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  2006. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  2007. ]
  2008. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  2009. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2010. # ####################################################################################
  2011. # ####################### Shell SETUP ################################################
  2012. # ####################################################################################
  2013. # this will hold the TCL instance
  2014. self.tcl = None
  2015. self.init_tcl()
  2016. self.shell = FCShell(self, version=self.version)
  2017. self.shell._edit.set_model_data(self.myKeywords)
  2018. self.shell.setWindowIcon(self.ui.app_icon)
  2019. self.shell.setWindowTitle("FlatCAM Shell")
  2020. self.shell.resize(*self.defaults["global_shell_shape"])
  2021. self.shell.append_output("FlatCAM %s - " % self.version)
  2022. self.shell.append_output(_("Type >help< to get started\n\n"))
  2023. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  2024. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  2025. self.ui.shell_dock.setWidget(self.shell)
  2026. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  2027. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  2028. QtWidgets.QDockWidget.DockWidgetFloatable |
  2029. QtWidgets.QDockWidget.DockWidgetClosable)
  2030. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  2031. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  2032. if self.defaults["global_shell_at_startup"]:
  2033. self.ui.shell_dock.show()
  2034. else:
  2035. self.ui.shell_dock.hide()
  2036. # ##################################################################################
  2037. # ###################### Tools and Plugins #########################################
  2038. # ##################################################################################
  2039. self.dblsidedtool = None
  2040. self.distance_tool = None
  2041. self.distance_min_tool = None
  2042. self.panelize_tool = None
  2043. self.film_tool = None
  2044. self.paste_tool = None
  2045. self.calculator_tool = None
  2046. self.rules_tool = None
  2047. self.sub_tool = None
  2048. self.move_tool = None
  2049. self.cutout_tool = None
  2050. self.ncclear_tool = None
  2051. self.optimal_tool = None
  2052. self.paint_tool = None
  2053. self.transform_tool = None
  2054. self.properties_tool = None
  2055. self.pdf_tool = None
  2056. self.image_tool = None
  2057. self.pcb_wizard_tool = None
  2058. self.cal_exc_tool = None
  2059. self.qrcode_tool = None
  2060. self.copper_thieving_tool = None
  2061. self.fiducial_tool = None
  2062. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  2063. self.install_tools()
  2064. # ##################################################################################
  2065. # ########################### SETUP RECENT ITEMS ###################################
  2066. # ##################################################################################
  2067. self.setup_recent_items()
  2068. # ##################################################################################
  2069. # ########################### BookMarks Manager ####################################
  2070. # ##################################################################################
  2071. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  2072. self.install_bookmarks()
  2073. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  2074. # ##################################################################################
  2075. # ############################## Tools Database ####################################
  2076. # ##################################################################################
  2077. self.tools_db_tab = None
  2078. # ### System Font Parsing ###
  2079. # self.f_parse = ParseFont(self)
  2080. # self.parse_system_fonts()
  2081. # #####################################################################################
  2082. # ######################## Check for updates ##########################################
  2083. # #####################################################################################
  2084. # Separate thread (Not worker)
  2085. # Check for updates on startup but only if the user consent and the app is not in Beta version
  2086. if (self.beta is False or self.beta is None) and \
  2087. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  2088. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  2089. self.thr2 = QtCore.QThread()
  2090. self.worker_task.emit({'fcn': self.version_check,
  2091. 'params': []})
  2092. self.thr2.start(QtCore.QThread.LowPriority)
  2093. # #####################################################################################
  2094. # ######################### Register files with FlatCAM; #############################
  2095. # ######################### It works only for Windows for now ########################
  2096. # #####################################################################################
  2097. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  2098. self.on_register_files()
  2099. # #####################################################################################
  2100. # ###################### Variables for global usage ###################################
  2101. # #####################################################################################
  2102. # hold the App units
  2103. self.units = 'IN'
  2104. # coordinates for relative position display
  2105. self.rel_point1 = (0, 0)
  2106. self.rel_point2 = (0, 0)
  2107. # variable to store coordinates
  2108. self.pos = (0, 0)
  2109. self.pos_jump = (0, 0)
  2110. # variable to store mouse coordinates
  2111. self.mouse = [0, 0]
  2112. # decide if we have a double click or single click
  2113. self.doubleclick = False
  2114. # store here the is_dragging value
  2115. self.event_is_dragging = False
  2116. # variable to store if a command is active (then the var is not None) and which one it is
  2117. self.command_active = None
  2118. # variable to store the status of moving selection action
  2119. # None value means that it's not an selection action
  2120. # True value = a selection from left to right
  2121. # False value = a selection from right to left
  2122. self.selection_type = None
  2123. # List to store the objects that are currently loaded in FlatCAM
  2124. # This list is updated on each object creation or object delete
  2125. self.all_objects_list = list()
  2126. # List to store the objects that are selected
  2127. self.sel_objects_list = list()
  2128. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  2129. self.key_modifiers = None
  2130. # Variable to hold the status of the axis
  2131. self.toggle_axis = True
  2132. # Variable to hold the status of the grid lines
  2133. self.toggle_grid_lines = True
  2134. # Variable to store the status of the fullscreen event
  2135. self.toggle_fscreen = False
  2136. # Variable to store the status of the code editor
  2137. self.toggle_codeeditor = False
  2138. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  2139. self.click_noproject = False
  2140. self.cursor = None
  2141. # Variable to store the GCODE that was edited
  2142. self.gcode_edited = ""
  2143. self.text_editor_tab = None
  2144. # reference for the self.ui.code_editor
  2145. self.reference_code_editor = None
  2146. self.script_code = ''
  2147. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  2148. self.preferences_changed_flag = False
  2149. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  2150. self.tools_db_changed_flag = False
  2151. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  2152. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  2153. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'pho',
  2154. 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top', 'tsm']
  2155. self.exc_list = ['drd', 'drl', 'exc', 'ncd', 'tap', 'txt', 'xln']
  2156. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  2157. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'plt', 'ply', 'rol',
  2158. 'sbp', 'tap', 'xpi']
  2159. self.svg_list = ['svg']
  2160. self.dxf_list = ['dxf']
  2161. self.pdf_list = ['pdf']
  2162. self.prj_list = ['flatprj']
  2163. self.conf_list = ['flatconfig']
  2164. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  2165. # flag for polygons not cleared
  2166. self.poly_not_cleared = False
  2167. # VisPy visuals
  2168. self.isHovering = False
  2169. self.notHovering = True
  2170. # Window geometry
  2171. self.x_pos = None
  2172. self.y_pos = None
  2173. self.width = None
  2174. self.height = None
  2175. # when True, the app has to return from any thread
  2176. self.abort_flag = False
  2177. # set the value used in the Windows Title
  2178. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  2179. # this holds a widget that is installed in the Plot Area when View Source option is used
  2180. self.source_editor_tab = None
  2181. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  2182. # VisPy visuals
  2183. if self.is_legacy is False:
  2184. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  2185. else:
  2186. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  2187. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  2188. # ###############################################################################
  2189. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  2190. # ############# It's done only once after install ###############
  2191. # ###############################################################################
  2192. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  2193. fac_def_from_file = factory_file.read()
  2194. factory_defaults = json.loads(fac_def_from_file)
  2195. # if the file contain an empty dictionary then save the factory defaults into the file
  2196. if not factory_defaults:
  2197. self.save_factory_defaults(silent_message=False)
  2198. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  2199. initial_lay = 'compact'
  2200. self.on_layout(lay=initial_lay)
  2201. # Set the combobox in Preferences to the current layout
  2202. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  2203. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  2204. factory_file.close()
  2205. # and then make the factory_defaults.FlatConfig file read_only so it can't be modified after creation.
  2206. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  2207. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  2208. # after the first run, this object should be False
  2209. self.defaults["first_run"] = False
  2210. # ###############################################################################
  2211. # ################# ADDING FlatCAM EDITORS section ##############################
  2212. # ###############################################################################
  2213. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2214. # at the first launch of the App , the editors will not be functional.
  2215. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  2216. self.exc_editor = FlatCAMExcEditor(self)
  2217. self.grb_editor = FlatCAMGrbEditor(self)
  2218. self.log.debug("Finished adding FlatCAM Editor's.")
  2219. self.set_ui_title(name=_("New Project - Not saved"))
  2220. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2221. current_platform = platform.architecture()[0]
  2222. if current_platform != '64bit':
  2223. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2224. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2225. # ###############################################################################
  2226. # ####################### Finished the CONSTRUCTOR ##############################
  2227. # ###############################################################################
  2228. App.log.debug("END of constructor. Releasing control.")
  2229. # #####################################################################################
  2230. # ########################## SHOW GUI #################################################
  2231. # #####################################################################################
  2232. # if the app is not started as headless, show it
  2233. if self.cmd_line_headless != 1:
  2234. if show_splash:
  2235. # finish the splash
  2236. self.splash.finish(self.ui)
  2237. mgui_settings = QSettings("Open Source", "FlatCAM")
  2238. if mgui_settings.contains("maximized_gui"):
  2239. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  2240. if maximized_ui is True:
  2241. self.ui.showMaximized()
  2242. else:
  2243. self.ui.show()
  2244. else:
  2245. self.ui.show()
  2246. if self.defaults["global_systray_icon"]:
  2247. self.trayIcon.show()
  2248. else:
  2249. log.warning("******************* RUNNING HEADLESS *******************")
  2250. # #####################################################################################
  2251. # ########################## START-UP ARGUMENTS #######################################
  2252. # #####################################################################################
  2253. # test if the program was started with a script as parameter
  2254. if self.cmd_line_shellvar:
  2255. try:
  2256. cnt = 0
  2257. command_tcl = 0
  2258. for i in self.cmd_line_shellvar.split(','):
  2259. if i is not None:
  2260. # noinspection PyBroadException
  2261. try:
  2262. command_tcl = eval(i)
  2263. except Exception:
  2264. command_tcl = i
  2265. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  2266. cnt += 1
  2267. # if there are Windows paths then replace the path separator with a Unix like one
  2268. if sys.platform == 'win32':
  2269. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  2270. self.shell._sysShell.exec_command(command_tcl_formatted, no_echo=True)
  2271. except Exception as ext:
  2272. print("ERROR: ", ext)
  2273. sys.exit(2)
  2274. if self.cmd_line_shellfile:
  2275. try:
  2276. if self.ui.shell_dock.isHidden():
  2277. self.ui.shell_dock.show()
  2278. with open(self.cmd_line_shellfile, "r") as myfile:
  2279. if show_splash:
  2280. self.splash.showMessage('%s: %ssec\n%s' % (
  2281. _("Canvas initialization started.\n"
  2282. "Canvas initialization finished in"), '%.2f' % self.used_time,
  2283. _("Executing Tcl Script ...")),
  2284. alignment=Qt.AlignBottom | Qt.AlignLeft,
  2285. color=QtGui.QColor("gray"))
  2286. cmd_line_shellfile_text = myfile.read()
  2287. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  2288. except Exception as ext:
  2289. print("ERROR: ", ext)
  2290. sys.exit(2)
  2291. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2292. # the path/file_name must be enclosed in quotes if it contain spaces
  2293. if App.args:
  2294. self.args_at_startup.emit(App.args)
  2295. if self.old_defaults_found is True:
  2296. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  2297. "Please reboot the application to update."))
  2298. self.old_defaults_found = False
  2299. @staticmethod
  2300. def copy_and_overwrite(from_path, to_path):
  2301. """
  2302. From here:
  2303. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2304. :param from_path: source path
  2305. :param to_path: destination path
  2306. :return: None
  2307. """
  2308. if os.path.exists(to_path):
  2309. shutil.rmtree(to_path)
  2310. try:
  2311. shutil.copytree(from_path, to_path)
  2312. except FileNotFoundError:
  2313. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2314. shutil.copytree(from_new_path, to_path)
  2315. def on_startup_args(self, args, silent=False):
  2316. """
  2317. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2318. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  2319. :param args: a list containing the application args at startup
  2320. :return: None
  2321. """
  2322. if args is not None:
  2323. args_to_process = args
  2324. else:
  2325. args_to_process = App.args
  2326. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2327. for argument in args_to_process:
  2328. if '.FlatPrj'.lower() in argument.lower():
  2329. try:
  2330. project_name = str(argument)
  2331. if project_name == "":
  2332. if silent is False:
  2333. self.inform.emit(_("Open cancelled."))
  2334. else:
  2335. # self.open_project(project_name)
  2336. run_from_arg = True
  2337. # self.worker_task.emit({'fcn': self.open_project,
  2338. # 'params': [project_name, run_from_arg]})
  2339. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2340. except Exception as e:
  2341. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2342. elif '.FlatConfig'.lower() in argument.lower():
  2343. try:
  2344. file_name = str(argument)
  2345. if file_name == "":
  2346. if silent is False:
  2347. self.inform.emit(_("Open Config file failed."))
  2348. else:
  2349. run_from_arg = True
  2350. # self.worker_task.emit({'fcn': self.open_config_file,
  2351. # 'params': [file_name, run_from_arg]})
  2352. self.open_config_file(file_name, run_from_arg=run_from_arg)
  2353. except Exception as e:
  2354. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2355. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  2356. try:
  2357. file_name = str(argument)
  2358. if file_name == "":
  2359. if silent is False:
  2360. self.inform.emit(_("Open Script file failed."))
  2361. else:
  2362. if silent is False:
  2363. self.on_fileopenscript(name=file_name)
  2364. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  2365. self.on_filerunscript(name=file_name)
  2366. except Exception as e:
  2367. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2368. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  2369. log.debug("App.on_startup_args() --> Quit event.")
  2370. sys.exit()
  2371. elif 'save'.lower() in argument.lower():
  2372. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  2373. self.save_defaults()
  2374. else:
  2375. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2376. proc_arg = argument.lower()
  2377. for ext in exc_list:
  2378. proc_ext = ext.replace(' ', '')
  2379. proc_ext = '.%s' % proc_ext
  2380. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2381. file_name = str(argument)
  2382. if file_name == "":
  2383. if silent is False:
  2384. self.inform.emit(_("Open Excellon file failed."))
  2385. else:
  2386. self.on_fileopenexcellon(name=file_name)
  2387. return
  2388. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2389. for ext in gco_list:
  2390. proc_ext = ext.replace(' ', '')
  2391. proc_ext = '.%s' % proc_ext
  2392. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2393. file_name = str(argument)
  2394. if file_name == "":
  2395. if silent is False:
  2396. self.inform.emit(_("Open GCode file failed."))
  2397. else:
  2398. self.on_fileopengcode(name=file_name)
  2399. return
  2400. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2401. for ext in grb_list:
  2402. proc_ext = ext.replace(' ', '')
  2403. proc_ext = '.%s' % proc_ext
  2404. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2405. file_name = str(argument)
  2406. if file_name == "":
  2407. if silent is False:
  2408. self.inform.emit(_("Open Gerber file failed."))
  2409. else:
  2410. self.on_fileopengerber(name=file_name)
  2411. return
  2412. # if it reached here without already returning then the app was registered with a file that it does not
  2413. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  2414. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  2415. # for arg in args_to_process:
  2416. # if 'FlatCAM.exe' in arg:
  2417. # continue
  2418. # else:
  2419. # sys.exit(2)
  2420. def set_ui_title(self, name):
  2421. """
  2422. Sets the title of the main window.
  2423. :param name: String that store the project path and project name
  2424. :return: None
  2425. """
  2426. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  2427. (self.version,
  2428. ('BETA' if self.beta else ''),
  2429. platform.architecture()[0],
  2430. self.engine,
  2431. name)
  2432. )
  2433. def on_theme_change(self, val):
  2434. t_settings = QSettings("Open Source", "FlatCAM")
  2435. t_settings.setValue('theme', val)
  2436. # This will write the setting to the platform specific storage.
  2437. del t_settings
  2438. self.on_app_restart()
  2439. def on_app_restart(self):
  2440. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  2441. # be left in the SySTray
  2442. try:
  2443. self.trayIcon.hide()
  2444. except Exception:
  2445. pass
  2446. fcTranslate.restart_program(app=self)
  2447. def defaults_read_form(self):
  2448. """
  2449. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2450. :return: None
  2451. """
  2452. for option in self.defaults_form_fields:
  2453. try:
  2454. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2455. except Exception as e:
  2456. log.debug("App.defaults_read_form() --> %s" % str(e))
  2457. def defaults_write_form(self, factor=None, fl_units=None):
  2458. """
  2459. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2460. self.defaults dictionary.
  2461. :param factor: will apply a factor to the values that written in the GUI elements
  2462. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2463. :return: None
  2464. """
  2465. for option in self.defaults:
  2466. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2467. # try:
  2468. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2469. # except KeyError:
  2470. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2471. # # TODO: Rethink this?
  2472. # pass
  2473. def defaults_write_form_field(self, field, factor=None, units=None):
  2474. """
  2475. Basically it is the worker in the self.defaults_write_form()
  2476. :param field: the GUI element in Preferences GUI to be updated
  2477. :param factor: factor to be applied to the field parameter
  2478. :param units: current FLatCAM measuring units
  2479. :return: None, it updates GUI elements
  2480. """
  2481. try:
  2482. if factor is None:
  2483. if units is None:
  2484. self.defaults_form_fields[field].set_value(self.defaults[field])
  2485. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2486. self.defaults_form_fields[field].set_value(self.defaults[field])
  2487. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2488. self.defaults_form_fields[field].set_value(self.defaults[field])
  2489. else:
  2490. if units is None:
  2491. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2492. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2493. self.defaults_form_fields[field].set_value((self.defaults[field] * factor))
  2494. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2495. self.defaults_form_fields[field].set_value((self.defaults[field] * factor))
  2496. except KeyError:
  2497. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2498. # TODO: Rethink this?
  2499. pass
  2500. except AttributeError:
  2501. log.debug(field)
  2502. def clear_pool(self):
  2503. """
  2504. Clear the multiprocessing pool and calls garbage collector.
  2505. :return: None
  2506. """
  2507. self.pool.close()
  2508. self.pool = Pool()
  2509. self.pool_recreated.emit(self.pool)
  2510. gc.collect()
  2511. def install_tools(self):
  2512. """
  2513. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2514. Instantiation of the Tools classes.
  2515. The order that the tools are installed is important as they can depend on each other install position.
  2516. :return: None
  2517. """
  2518. self.dblsidedtool = DblSidedTool(self)
  2519. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2520. self.cal_exc_tool = ToolCalibrateExcellon(self)
  2521. self.cal_exc_tool.install(icon=QtGui.QIcon('share/drill16.png'), pos=self.ui.menutool,
  2522. before=self.dblsidedtool.menuAction,
  2523. separator=False)
  2524. self.distance_tool = Distance(self)
  2525. self.distance_tool.install(icon=QtGui.QIcon('share/distance16.png'), pos=self.ui.menuedit,
  2526. before=self.ui.menueditorigin,
  2527. separator=False)
  2528. self.distance_min_tool = DistanceMin(self)
  2529. self.distance_min_tool.install(icon=QtGui.QIcon('share/distance_min16.png'), pos=self.ui.menuedit,
  2530. before=self.ui.menueditorigin,
  2531. separator=True)
  2532. self.panelize_tool = Panelize(self)
  2533. self.panelize_tool.install(icon=QtGui.QIcon('share/panelize16.png'))
  2534. self.film_tool = Film(self)
  2535. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2536. self.paste_tool = SolderPaste(self)
  2537. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2538. self.calculator_tool = ToolCalculator(self)
  2539. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator16.png'), separator=True)
  2540. self.sub_tool = ToolSub(self)
  2541. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2542. self.rules_tool = RulesCheck(self)
  2543. self.rules_tool.install(icon=QtGui.QIcon('share/rules32.png'), pos=self.ui.menutool, separator=False)
  2544. self.optimal_tool = ToolOptimal(self)
  2545. self.optimal_tool.install(icon=QtGui.QIcon('share/open_excellon32.png'), pos=self.ui.menutool, separator=True)
  2546. self.move_tool = ToolMove(self)
  2547. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2548. before=self.ui.menueditorigin, separator=True)
  2549. self.cutout_tool = CutOut(self)
  2550. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2551. before=self.sub_tool.menuAction)
  2552. self.ncclear_tool = NonCopperClear(self)
  2553. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2554. before=self.sub_tool.menuAction, separator=True)
  2555. self.paint_tool = ToolPaint(self)
  2556. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2557. before=self.sub_tool.menuAction, separator=True)
  2558. self.copper_thieving_tool = ToolCopperThieving(self)
  2559. self.copper_thieving_tool.install(icon=QtGui.QIcon('share/copperfill32.png'), pos=self.ui.menutool)
  2560. self.fiducial_tool = ToolFiducials(self)
  2561. self.fiducial_tool.install(icon=QtGui.QIcon('share/fiducials_32.png'), pos=self.ui.menutool)
  2562. self.qrcode_tool = QRCode(self)
  2563. self.qrcode_tool.install(icon=QtGui.QIcon('share/qrcode32.png'), pos=self.ui.menutool)
  2564. self.transform_tool = ToolTransform(self)
  2565. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2566. self.properties_tool = Properties(self)
  2567. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2568. self.pdf_tool = ToolPDF(self)
  2569. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2570. separator=True)
  2571. self.image_tool = ToolImage(self)
  2572. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2573. separator=True)
  2574. self.pcb_wizard_tool = PcbWizard(self)
  2575. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2576. self.log.debug("Tools are installed.")
  2577. def remove_tools(self):
  2578. """
  2579. Will remove all the actions in the Tool menu.
  2580. :return: None
  2581. """
  2582. for act in self.ui.menutool.actions():
  2583. self.ui.menutool.removeAction(act)
  2584. def init_tools(self):
  2585. """
  2586. Initialize the Tool tab in the notebook side of the central widget.
  2587. Remove the actions in the Tools menu.
  2588. Instantiate again the FlatCAM tools (plugins).
  2589. All this is required when changing the layout: standard, compact etc.
  2590. :return: None
  2591. """
  2592. log.debug("init_tools()")
  2593. # delete the data currently in the Tools Tab and the Tab itself
  2594. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2595. if widget is not None:
  2596. widget.deleteLater()
  2597. self.ui.notebook.removeTab(2)
  2598. # rebuild the Tools Tab
  2599. self.ui.tool_tab = QtWidgets.QWidget()
  2600. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2601. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2602. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2603. self.ui.tool_scroll_area = VerticalScrollArea()
  2604. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2605. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2606. # first remove all of them
  2607. self.remove_tools()
  2608. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2609. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2610. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2611. # third install all of them
  2612. self.install_tools()
  2613. self.log.debug("Tools are initialized.")
  2614. # def parse_system_fonts(self):
  2615. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2616. # 'params': []})
  2617. def connect_toolbar_signals(self):
  2618. """
  2619. Reconnect the signals to the actions in the toolbar.
  2620. This has to be done each time after the FlatCAM tools are removed/installed.
  2621. :return: None
  2622. """
  2623. # Toolbar
  2624. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2625. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2626. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2627. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2628. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2629. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2630. self.ui.replot_btn.triggered.connect(self.plot_all)
  2631. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2632. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2633. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2634. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2635. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2636. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2637. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2638. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2639. self.ui.copy_btn.triggered.connect(self.on_copy_object)
  2640. self.ui.delete_btn.triggered.connect(self.on_delete)
  2641. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  2642. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  2643. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  2644. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  2645. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2646. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2647. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2648. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2649. # Tools Toolbar Signals
  2650. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2651. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2652. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2653. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2654. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2655. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2656. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2657. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2658. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  2659. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  2660. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2661. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2662. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  2663. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  2664. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  2665. def object2editor(self):
  2666. """
  2667. Send the current Geometry or Excellon object (if any) into the it's editor.
  2668. :return: None
  2669. """
  2670. self.report_usage("object2editor()")
  2671. # disable the objects menu as it may interfere with the Editors
  2672. self.ui.menuobjects.setDisabled(True)
  2673. edited_object = self.collection.get_active()
  2674. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2675. isinstance(edited_object, FlatCAMExcellon):
  2676. pass
  2677. else:
  2678. self.inform.emit('[WARNING_NOTCL] %s' %
  2679. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2680. return
  2681. if isinstance(edited_object, FlatCAMGeometry):
  2682. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2683. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2684. # we set the notebook to hidden
  2685. self.ui.splitter.setSizes([0, 1])
  2686. if edited_object.multigeo is True:
  2687. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  2688. if len(sel_rows) > 1:
  2689. self.inform.emit('[WARNING_NOTCL] %s' %
  2690. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  2691. "is not possible.\n"
  2692. "Edit only one geometry at a time."))
  2693. # determine the tool dia of the selected tool
  2694. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  2695. # now find the key in the edited_object.tools that has this tooldia
  2696. multi_tool = 1
  2697. for tool in edited_object.tools:
  2698. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2699. multi_tool = tool
  2700. break
  2701. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2702. else:
  2703. self.geo_editor.edit_fcgeometry(edited_object)
  2704. # set call source to the Editor we go into
  2705. self.call_source = 'geo_editor'
  2706. elif isinstance(edited_object, FlatCAMExcellon):
  2707. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2708. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2709. if self.ui.splitter.sizes()[0] == 0:
  2710. self.ui.splitter.setSizes([1, 1])
  2711. self.exc_editor.edit_fcexcellon(edited_object)
  2712. # set call source to the Editor we go into
  2713. self.call_source = 'exc_editor'
  2714. elif isinstance(edited_object, FlatCAMGerber):
  2715. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2716. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2717. if self.ui.splitter.sizes()[0] == 0:
  2718. self.ui.splitter.setSizes([1, 1])
  2719. self.grb_editor.edit_fcgerber(edited_object)
  2720. # set call source to the Editor we go into
  2721. self.call_source = 'grb_editor'
  2722. # make sure that we can't select another object while in Editor Mode:
  2723. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2724. self.ui.project_frame.setDisabled(True)
  2725. # delete any selection shape that might be active as they are not relevant in Editor
  2726. self.delete_selection_shape()
  2727. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2728. self.ui.plot_tab_area.protectTab(0)
  2729. self.inform.emit('[WARNING_NOTCL] %s' %
  2730. _("Editor is activated ..."))
  2731. self.should_we_save = True
  2732. def editor2object(self, cleanup=None):
  2733. """
  2734. Transfers the Geometry or Excellon from it's editor to the current object.
  2735. :return: None
  2736. """
  2737. self.report_usage("editor2object()")
  2738. # re-enable the objects menu that was disabled on entry in Editor mode
  2739. self.ui.menuobjects.setDisabled(False)
  2740. # do not update a geometry or excellon object unless it comes out of an editor
  2741. if self.call_source != 'app':
  2742. edited_obj = self.collection.get_active()
  2743. if cleanup is None:
  2744. msgbox = QtWidgets.QMessageBox()
  2745. msgbox.setText(_("Do you want to save the edited object?"))
  2746. msgbox.setWindowTitle(_("Close Editor"))
  2747. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2748. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2749. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2750. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2751. msgbox.setDefaultButton(bt_yes)
  2752. msgbox.exec_()
  2753. response = msgbox.clickedButton()
  2754. if response == bt_yes:
  2755. # clean the Tools Tab
  2756. self.ui.tool_scroll_area.takeWidget()
  2757. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2758. self.ui.notebook.setTabText(2, "Tool")
  2759. if isinstance(edited_obj, FlatCAMGeometry):
  2760. obj_type = "Geometry"
  2761. if cleanup is None:
  2762. self.geo_editor.update_fcgeometry(edited_obj)
  2763. self.geo_editor.update_options(edited_obj)
  2764. self.geo_editor.deactivate()
  2765. # update the geo object options so it is including the bounding box values
  2766. try:
  2767. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2768. edited_obj.options['xmin'] = xmin
  2769. edited_obj.options['ymin'] = ymin
  2770. edited_obj.options['xmax'] = xmax
  2771. edited_obj.options['ymax'] = ymax
  2772. except AttributeError as e:
  2773. self.inform.emit('[WARNING] %s' %
  2774. _("Object empty after edit."))
  2775. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2776. elif isinstance(edited_obj, FlatCAMGerber):
  2777. obj_type = "Gerber"
  2778. if cleanup is None:
  2779. self.grb_editor.update_fcgerber()
  2780. self.grb_editor.update_options(edited_obj)
  2781. self.grb_editor.deactivate_grb_editor()
  2782. # delete the old object (the source object) if it was an empty one
  2783. try:
  2784. if len(edited_obj.solid_geometry) == 0:
  2785. old_name = edited_obj.options['name']
  2786. self.collection.set_active(old_name)
  2787. self.collection.delete_active()
  2788. except TypeError:
  2789. # if the solid_geometry is a single Polygon the len() will not work
  2790. # in any case, falling here means that we have something in the solid_geometry, even if only
  2791. # a single Polygon, therefore we pass this
  2792. pass
  2793. # restore GUI to the Selected TAB
  2794. # Remove anything else in the GUI
  2795. self.ui.selected_scroll_area.takeWidget()
  2796. # Switch notebook to Selected page
  2797. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2798. elif isinstance(edited_obj, FlatCAMExcellon):
  2799. obj_type = "Excellon"
  2800. if cleanup is None:
  2801. self.exc_editor.update_fcexcellon(edited_obj)
  2802. self.exc_editor.update_options(edited_obj)
  2803. self.exc_editor.deactivate()
  2804. # delete the old object (the source object) if it was an empty one
  2805. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  2806. old_name = edited_obj.options['name']
  2807. self.collection.set_active(old_name)
  2808. self.collection.delete_active()
  2809. # restore GUI to the Selected TAB
  2810. # Remove anything else in the GUI
  2811. self.ui.tool_scroll_area.takeWidget()
  2812. # Switch notebook to Selected page
  2813. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2814. else:
  2815. self.inform.emit('[WARNING_NOTCL] %s' %
  2816. _("Select a Gerber, Geometry or Excellon Object to update."))
  2817. return
  2818. self.inform.emit('[selected] %s %s' %
  2819. (obj_type, _("is updated, returning to App...")))
  2820. elif response == bt_no:
  2821. # clean the Tools Tab
  2822. self.ui.tool_scroll_area.takeWidget()
  2823. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2824. self.ui.notebook.setTabText(2, "Tool")
  2825. if isinstance(edited_obj, FlatCAMGeometry):
  2826. self.geo_editor.deactivate()
  2827. elif isinstance(edited_obj, FlatCAMGerber):
  2828. self.grb_editor.deactivate_grb_editor()
  2829. elif isinstance(edited_obj, FlatCAMExcellon):
  2830. self.exc_editor.deactivate()
  2831. # set focus on the project tab
  2832. else:
  2833. self.inform.emit('[WARNING_NOTCL] %s' %
  2834. _("Select a Gerber, Geometry or Excellon Object to update."))
  2835. return
  2836. edited_obj.set_ui(edited_obj.ui_type())
  2837. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2838. elif response == bt_cancel:
  2839. return
  2840. else:
  2841. if isinstance(edited_obj, FlatCAMGeometry):
  2842. self.geo_editor.deactivate()
  2843. elif isinstance(edited_obj, FlatCAMGerber):
  2844. self.grb_editor.deactivate_grb_editor()
  2845. elif isinstance(edited_obj, FlatCAMExcellon):
  2846. self.exc_editor.deactivate()
  2847. else:
  2848. self.inform.emit('[WARNING_NOTCL] %s' %
  2849. _("Select a Gerber, Geometry or Excellon Object to update."))
  2850. return
  2851. # if notebook is hidden we show it
  2852. if self.ui.splitter.sizes()[0] == 0:
  2853. self.ui.splitter.setSizes([1, 1])
  2854. # restore the call_source to app
  2855. self.call_source = 'app'
  2856. edited_obj.plot()
  2857. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2858. self.ui.plot_tab_area.protectTab(0)
  2859. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2860. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2861. self.ui.project_frame.setDisabled(False)
  2862. def get_last_folder(self):
  2863. """
  2864. Get the folder path from where the last file was opened.
  2865. :return: String, last opened folder path
  2866. """
  2867. return self.defaults["global_last_folder"]
  2868. def get_last_save_folder(self):
  2869. """
  2870. Get the folder path from where the last file was saved.
  2871. :return: String, last saved folder path
  2872. """
  2873. loc = self.defaults["global_last_save_folder"]
  2874. if loc is None:
  2875. loc = self.defaults["global_last_folder"]
  2876. if loc is None:
  2877. loc = os.path.dirname(__file__)
  2878. return loc
  2879. def report_usage(self, resource):
  2880. """
  2881. Increments usage counter for the given resource
  2882. in self.defaults['global_stats'].
  2883. :param resource: Name of the resource.
  2884. :return: None
  2885. """
  2886. if resource in self.defaults['global_stats']:
  2887. self.defaults['global_stats'][resource] += 1
  2888. else:
  2889. self.defaults['global_stats'][resource] = 1
  2890. def init_tcl(self):
  2891. """
  2892. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2893. :return: None
  2894. """
  2895. if hasattr(self, 'tcl') and self.tcl is not None:
  2896. # self.tcl = None
  2897. # TODO we need to clean non default variables and procedures here
  2898. # new object cannot be used here as it will not remember values created for next passes,
  2899. # because tcl was execudted in old instance of TCL
  2900. pass
  2901. else:
  2902. self.tcl = tk.Tcl()
  2903. self.setup_shell()
  2904. self.log.debug("TCL Shell has been initialized.")
  2905. # TODO: This shouldn't be here.
  2906. class TclErrorException(Exception):
  2907. """
  2908. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2909. """
  2910. pass
  2911. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2912. """
  2913. Shows a message on the FlatCAM Shell
  2914. :param msg: Message to display.
  2915. :param show: Opens the shell.
  2916. :param error: Shows the message as an error.
  2917. :param warning: Shows the message as an warning.
  2918. :param success: Shows the message as an success.
  2919. :param selected: Indicate that something was selected on canvas
  2920. :return: None
  2921. """
  2922. if show:
  2923. self.ui.shell_dock.show()
  2924. try:
  2925. if error:
  2926. self.shell.append_error(msg + "\n")
  2927. elif warning:
  2928. self.shell.append_warning(msg + "\n")
  2929. elif success:
  2930. self.shell.append_success(msg + "\n")
  2931. elif selected:
  2932. self.shell.append_selected(msg + "\n")
  2933. else:
  2934. self.shell.append_output(msg + "\n")
  2935. except AttributeError:
  2936. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2937. def raise_tcl_unknown_error(self, unknownException):
  2938. """
  2939. Raise exception if is different type than TclErrorException
  2940. this is here mainly to show unknown errors inside TCL shell console.
  2941. :param unknownException:
  2942. :return:
  2943. """
  2944. if not isinstance(unknownException, self.TclErrorException):
  2945. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2946. else:
  2947. raise unknownException
  2948. def display_tcl_error(self, error, error_info=None):
  2949. """
  2950. Escape bracket [ with '\' otherwise there is error
  2951. "ERROR: missing close-bracket" instead of real error
  2952. :param error: it may be text or exception
  2953. :param error_info: Some informations about the error
  2954. :return: None
  2955. """
  2956. if isinstance(error, Exception):
  2957. exc_type, exc_value, exc_traceback = error_info
  2958. if not isinstance(error, self.TclErrorException):
  2959. show_trace = 1
  2960. else:
  2961. show_trace = int(self.defaults['global_verbose_error_level'])
  2962. if show_trace > 0:
  2963. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2964. trc_formated = []
  2965. for a in reversed(trc):
  2966. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2967. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2968. else:
  2969. text = "%s" % error
  2970. else:
  2971. text = error
  2972. text = text.replace('[', '\\[').replace('"', '\\"')
  2973. self.tcl.eval('return -code error "%s"' % text)
  2974. def raise_tcl_error(self, text):
  2975. """
  2976. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2977. :param text: text of error
  2978. :return: raise exception
  2979. """
  2980. self.display_tcl_error(text)
  2981. raise self.TclErrorException(text)
  2982. def exec_command(self, text, no_echo=False):
  2983. """
  2984. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2985. Also handles execution in separated threads
  2986. :param text: FlatCAM TclCommand with parameters
  2987. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2988. will create crashes of the _Expandable_Edit widget
  2989. :return: output if there was any
  2990. """
  2991. self.report_usage('exec_command')
  2992. result = self.exec_command_test(text, False, no_echo=no_echo)
  2993. # MS: added this method call so the geometry is updated once the TCL command is executed
  2994. # if no_plot is None:
  2995. # self.plot_all()
  2996. return result
  2997. def exec_command_test(self, text, reraise=True, no_echo=False):
  2998. """
  2999. Same as exec_command(...) with additional control over exceptions.
  3000. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  3001. :param text: Input command
  3002. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  3003. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  3004. will create crashes of the _Expandable_Edit widget
  3005. :return: Output from the command
  3006. """
  3007. tcl_command_string = str(text)
  3008. try:
  3009. if no_echo is False:
  3010. self.shell.open_proccessing() # Disables input box.
  3011. result = self.tcl.eval(str(tcl_command_string))
  3012. if result != 'None' and no_echo is False:
  3013. self.shell.append_output(result + '\n')
  3014. except tk.TclError as e:
  3015. # This will display more precise answer if something in TCL shell fails
  3016. result = self.tcl.eval("set errorInfo")
  3017. self.log.error("Exec command Exception: %s" % (result + '\n'))
  3018. if no_echo is False:
  3019. self.shell.append_error('ERROR: ' + result + '\n')
  3020. # Show error in console and just return or in test raise exception
  3021. if reraise:
  3022. raise e
  3023. finally:
  3024. if no_echo is False:
  3025. self.shell.close_proccessing()
  3026. pass
  3027. return result
  3028. # """
  3029. # Code below is unsused. Saved for later.
  3030. # """
  3031. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  3032. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  3033. # self.log.debug(parts)
  3034. # try:
  3035. # if parts[0] not in commands:
  3036. # self.shell.append_error("Unknown command\n")
  3037. # return
  3038. #
  3039. # #import inspect
  3040. # #inspect.getargspec(someMethod)
  3041. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  3042. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  3043. # self.shell.append_error(
  3044. # "Command %s takes %d arguments. %d given.\n" %
  3045. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  3046. # )
  3047. # return
  3048. #
  3049. # cmdfcn = commands[parts[0]]["fcn"]
  3050. # cmdconv = commands[parts[0]]["converters"]
  3051. # if len(parts) - 1 > 0:
  3052. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  3053. # else:
  3054. # retval = cmdfcn()
  3055. # retfcn = commands[parts[0]]["retfcn"]
  3056. # if retval and retfcn(retval):
  3057. # self.shell.append_output(retfcn(retval) + "\n")
  3058. #
  3059. # except Exception as e:
  3060. # #self.shell.append_error(''.join(traceback.format_exc()))
  3061. # #self.shell.append_error("?\n")
  3062. # self.shell.append_error(str(e) + "\n")
  3063. def info(self, msg):
  3064. """
  3065. Informs the user. Normally on the status bar, optionally
  3066. also on the shell.
  3067. :param msg: Text to write.
  3068. :return: None
  3069. """
  3070. # Type of message in brackets at the beginning of the message.
  3071. match = re.search("\[([^\]]+)\](.*)", msg)
  3072. if match:
  3073. level = match.group(1)
  3074. msg_ = match.group(2)
  3075. self.ui.fcinfo.set_status(str(msg_), level=level)
  3076. if level.lower() == "error":
  3077. self.shell_message(msg, error=True, show=True)
  3078. elif level.lower() == "warning":
  3079. self.shell_message(msg, warning=True, show=True)
  3080. elif level.lower() == "error_notcl":
  3081. self.shell_message(msg, error=True, show=False)
  3082. elif level.lower() == "warning_notcl":
  3083. self.shell_message(msg, warning=True, show=False)
  3084. elif level.lower() == "success":
  3085. self.shell_message(msg, success=True, show=False)
  3086. elif level.lower() == "selected":
  3087. self.shell_message(msg, selected=True, show=False)
  3088. else:
  3089. self.shell_message(msg, show=False)
  3090. else:
  3091. self.ui.fcinfo.set_status(str(msg), level="info")
  3092. # make sure that if the message is to clear the infobar with a space
  3093. # is not printed over and over on the shell
  3094. if msg != '':
  3095. self.shell_message(msg)
  3096. def restore_toolbar_view(self):
  3097. """
  3098. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  3099. was saved in the defaults dictionary.
  3100. :return: None
  3101. """
  3102. tb = self.defaults["global_toolbar_view"]
  3103. if tb & 1:
  3104. self.ui.toolbarfile.setVisible(True)
  3105. else:
  3106. self.ui.toolbarfile.setVisible(False)
  3107. if tb & 2:
  3108. self.ui.toolbargeo.setVisible(True)
  3109. else:
  3110. self.ui.toolbargeo.setVisible(False)
  3111. if tb & 4:
  3112. self.ui.toolbarview.setVisible(True)
  3113. else:
  3114. self.ui.toolbarview.setVisible(False)
  3115. if tb & 8:
  3116. self.ui.toolbartools.setVisible(True)
  3117. else:
  3118. self.ui.toolbartools.setVisible(False)
  3119. if tb & 16:
  3120. self.ui.exc_edit_toolbar.setVisible(True)
  3121. else:
  3122. self.ui.exc_edit_toolbar.setVisible(False)
  3123. if tb & 32:
  3124. self.ui.geo_edit_toolbar.setVisible(True)
  3125. else:
  3126. self.ui.geo_edit_toolbar.setVisible(False)
  3127. if tb & 64:
  3128. self.ui.grb_edit_toolbar.setVisible(True)
  3129. else:
  3130. self.ui.grb_edit_toolbar.setVisible(False)
  3131. if tb & 128:
  3132. self.ui.snap_toolbar.setVisible(True)
  3133. else:
  3134. self.ui.snap_toolbar.setVisible(False)
  3135. if tb & 256:
  3136. self.ui.toolbarshell.setVisible(True)
  3137. else:
  3138. self.ui.toolbarshell.setVisible(False)
  3139. def load_defaults(self, filename):
  3140. """
  3141. Loads the aplication's default settings from current_defaults.FlatConfig into
  3142. ``self.defaults``.
  3143. :return: None
  3144. """
  3145. try:
  3146. f = open(self.data_path + "/" + filename + ".FlatConfig")
  3147. options = f.read()
  3148. f.close()
  3149. except IOError:
  3150. self.log.error("Could not load defaults file.")
  3151. self.inform.emit('[ERROR] %s' % _("Could not load defaults file."))
  3152. # in case the defaults file can't be loaded, show all toolbars
  3153. self.defaults["global_toolbar_view"] = 511
  3154. return
  3155. try:
  3156. defaults = json.loads(options)
  3157. except Exception:
  3158. # in case the defaults file can't be loaded, show all toolbars
  3159. self.defaults["global_toolbar_view"] = 511
  3160. e = sys.exc_info()[0]
  3161. App.log.error(str(e))
  3162. self.inform.emit('[ERROR] %s' % _("Failed to parse defaults file."))
  3163. return
  3164. if 'version' not in defaults or defaults['version'] != self.defaults['version']:
  3165. for k, v in defaults.items():
  3166. if k in self.defaults:
  3167. self.defaults[k] = v
  3168. # delete old factory defaults
  3169. try:
  3170. fact_def_file_path = os.path.join(self.data_path, 'factory_defaults.FlatConfig')
  3171. os.chmod(fact_def_file_path, stat.S_IRWXO | stat.S_IWRITE | stat.S_IWGRP)
  3172. os.remove(fact_def_file_path)
  3173. # recreate a new factory defaults file and save the factory defaults data into it
  3174. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  3175. json.dump(self.defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3176. f_f_def_s.close()
  3177. # and then make the factory_defaults.FlatConfig file read_only so it can't be modified after creation.
  3178. os.chmod(fact_def_file_path, S_IREAD | S_IRGRP | S_IROTH)
  3179. except Exception as e:
  3180. log.debug("App.load_defaults() -> deleting old factory defaults file -> %s" % str(e))
  3181. self.old_defaults_found = True
  3182. else:
  3183. self.defaults.update(defaults)
  3184. log.debug("FlatCAM defaults loaded from: %s" % filename)
  3185. def on_import_preferences(self):
  3186. """
  3187. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  3188. ``self.defaults``.
  3189. :return: None
  3190. """
  3191. self.report_usage("on_import_preferences")
  3192. App.log.debug("on_import_preferences()")
  3193. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  3194. try:
  3195. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3196. directory=self.data_path,
  3197. filter=filter_)
  3198. except TypeError:
  3199. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3200. filter=filter_)
  3201. filename = str(filename)
  3202. if filename == "":
  3203. self.inform.emit('[WARNING_NOTCL] %s' %
  3204. _("FlatCAM preferences import cancelled."))
  3205. else:
  3206. try:
  3207. f = open(filename)
  3208. options = f.read()
  3209. f.close()
  3210. except IOError:
  3211. self.log.error("Could not load defaults file.")
  3212. self.inform.emit('[ERROR_NOTCL] %s' %
  3213. _("Could not load defaults file."))
  3214. return
  3215. try:
  3216. defaults_from_file = json.loads(options)
  3217. except Exception:
  3218. e = sys.exc_info()[0]
  3219. App.log.error(str(e))
  3220. self.inform.emit('[ERROR_NOTCL] %s' %
  3221. _("Failed to parse defaults file."))
  3222. return
  3223. self.defaults.update(defaults_from_file)
  3224. self.on_preferences_edited()
  3225. self.inform.emit('[success] %s: %s' %
  3226. (_("Imported Defaults from"), filename))
  3227. def on_export_preferences(self):
  3228. """
  3229. Save the defaults dictionary to a file.
  3230. :return: None
  3231. """
  3232. self.report_usage("on_export_preferences")
  3233. App.log.debug("on_export_preferences()")
  3234. defaults_file_content = None
  3235. self.date = str(datetime.today()).rpartition('.')[0]
  3236. self.date = ''.join(c for c in self.date if c not in ':-')
  3237. self.date = self.date.replace(' ', '_')
  3238. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  3239. try:
  3240. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  3241. caption=_("Export FlatCAM Preferences"),
  3242. directory=self.data_path + '/preferences_' + self.date,
  3243. filter=filter__
  3244. )
  3245. except TypeError:
  3246. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  3247. filter=filter__)
  3248. filename = str(filename)
  3249. defaults_from_file = {}
  3250. if filename == "":
  3251. self.inform.emit('[WARNING_NOTCL] %s' %
  3252. _("FlatCAM preferences export cancelled."))
  3253. return
  3254. else:
  3255. try:
  3256. f = open(filename, 'w')
  3257. defaults_file_content = f.read()
  3258. f.close()
  3259. except PermissionError:
  3260. self.inform.emit('[WARNING] %s' %
  3261. _("Permission denied, saving not possible.\n"
  3262. "Most likely another app is holding the file open and not accessible."))
  3263. return
  3264. except IOError:
  3265. App.log.debug('Creating a new preferences file ...')
  3266. f = open(filename, 'w')
  3267. json.dump({}, f)
  3268. f.close()
  3269. except Exception:
  3270. e = sys.exc_info()[0]
  3271. App.log.error("Could not load defaults file.")
  3272. App.log.error(str(e))
  3273. self.inform.emit('[ERROR_NOTCL] %s' %
  3274. _("Could not load preferences file."))
  3275. return
  3276. try:
  3277. defaults_from_file = json.loads(defaults_file_content)
  3278. except Exception:
  3279. App.log.warning("Trying to read an empty Preferences file. Continue.")
  3280. # Update options
  3281. self.defaults_read_form()
  3282. defaults_from_file.update(self.defaults)
  3283. self.propagate_defaults(silent=True)
  3284. # Save update options
  3285. try:
  3286. f = open(filename, "w")
  3287. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  3288. f.close()
  3289. except Exception:
  3290. self.inform.emit('[ERROR_NOTCL] %s' %
  3291. _("Failed to write defaults to file."))
  3292. return
  3293. if self.defaults["global_open_style"] is False:
  3294. self.file_opened.emit("preferences", filename)
  3295. self.file_saved.emit("preferences", filename)
  3296. self.inform.emit('[success] %s: %s' %
  3297. (_("Exported preferences to"), filename))
  3298. def on_preferences_open_folder(self):
  3299. """
  3300. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  3301. :return: None
  3302. """
  3303. self.report_usage("on_preferences_open_folder()")
  3304. if sys.platform == 'win32':
  3305. subprocess.Popen('explorer %s' % self.data_path)
  3306. elif sys.platform == 'darwin':
  3307. os.system('open "%s"' % self.data_path)
  3308. else:
  3309. subprocess.Popen(['xdg-open', self.data_path])
  3310. self.inform.emit('[success] %s' %
  3311. _("FlatCAM Preferences Folder opened."))
  3312. def save_geometry(self, x, y, width, height, notebook_width):
  3313. """
  3314. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  3315. launch of the application.
  3316. :param x: X position of the main window
  3317. :param y: Y position of the main window
  3318. :param width: width of the main window
  3319. :param height: height of the main window
  3320. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  3321. :return: None
  3322. """
  3323. self.defaults["global_def_win_x"] = x
  3324. self.defaults["global_def_win_y"] = y
  3325. self.defaults["global_def_win_w"] = width
  3326. self.defaults["global_def_win_h"] = height
  3327. self.defaults["global_def_notebook_width"] = notebook_width
  3328. self.save_defaults()
  3329. def restore_main_win_geom(self):
  3330. try:
  3331. self.ui.setGeometry(self.defaults["global_def_win_x"],
  3332. self.defaults["global_def_win_y"],
  3333. self.defaults["global_def_win_w"],
  3334. self.defaults["global_def_win_h"])
  3335. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  3336. except KeyError as e:
  3337. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  3338. def message_dialog(self, title, message, kind="info"):
  3339. """
  3340. Builds and show a custom QMessageBox to be used in FlatCAM.
  3341. :param title: title of the QMessageBox
  3342. :param message: message to be displayed
  3343. :param kind: type of QMessageBox; will display a specific icon.
  3344. :return:
  3345. """
  3346. icon = {"info": QtWidgets.QMessageBox.Information,
  3347. "warning": QtWidgets.QMessageBox.Warning,
  3348. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3349. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  3350. dlg.setText(message)
  3351. dlg.exec_()
  3352. def register_recent(self, kind, filename):
  3353. """
  3354. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  3355. dictionary.
  3356. :param kind: type of file that was opened
  3357. :param filename: the path and file name for the file that was opened
  3358. :return:
  3359. """
  3360. self.log.debug("register_recent()")
  3361. self.log.debug(" %s" % kind)
  3362. self.log.debug(" %s" % filename)
  3363. record = {'kind': str(kind), 'filename': str(filename)}
  3364. if record in self.recent:
  3365. return
  3366. if record in self.recent_projects:
  3367. return
  3368. if record['kind'] == 'project':
  3369. self.recent_projects.insert(0, record)
  3370. else:
  3371. self.recent.insert(0, record)
  3372. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3373. self.recent.pop()
  3374. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3375. self.recent_projects.pop()
  3376. try:
  3377. f = open(self.data_path + '/recent.json', 'w')
  3378. except IOError:
  3379. App.log.error("Failed to open recent items file for writing.")
  3380. self.inform.emit('[ERROR_NOTCL] %s' %
  3381. _('Failed to open recent files file for writing.'))
  3382. return
  3383. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3384. f.close()
  3385. try:
  3386. fp = open(self.data_path + '/recent_projects.json', 'w')
  3387. except IOError:
  3388. App.log.error("Failed to open recent items file for writing.")
  3389. self.inform.emit('[ERROR_NOTCL] %s' %
  3390. _('Failed to open recent projects file for writing.'))
  3391. return
  3392. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3393. fp.close()
  3394. # Re-build the recent items menu
  3395. self.setup_recent_items()
  3396. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3397. """
  3398. Creates a new specialized FlatCAMObj and attaches it to the application,
  3399. this is, updates the GUI accordingly, any other records and plots it.
  3400. This method is thread-safe.
  3401. Notes:
  3402. * If the name is in use, the self.collection will modify it
  3403. when appending it to the collection. There is no need to handle
  3404. name conflicts here.
  3405. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3406. :type kind: str
  3407. :param name: Name for the object.
  3408. :type name: str
  3409. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3410. The function is called with 2 parameters: the new object and the App instance.
  3411. :type initialize: function
  3412. :param active:
  3413. :param fit:
  3414. :param plot: If to plot the resulting object
  3415. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3416. self.colleaction
  3417. :return: None
  3418. :rtype: None
  3419. """
  3420. App.log.debug("new_object()")
  3421. obj_plot = plot
  3422. obj_autoselected = autoselected
  3423. t0 = time.time() # Debug
  3424. # ## Create object
  3425. classdict = {
  3426. "gerber": FlatCAMGerber,
  3427. "excellon": FlatCAMExcellon,
  3428. "cncjob": FlatCAMCNCjob,
  3429. "geometry": FlatCAMGeometry,
  3430. "script": FlatCAMScript,
  3431. "document": FlatCAMDocument
  3432. }
  3433. App.log.debug("Calling object constructor...")
  3434. # Object creation/instantiation
  3435. obj = classdict[kind](name)
  3436. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3437. # IMPORTANT
  3438. # The key names in defaults and options dictionary's are not random:
  3439. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3440. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  3441. # copied to self.options. After that, below, depending on the type of
  3442. # object that is created, it will strip the name of the object and the underline (if the original key was
  3443. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3444. # "toolchange"
  3445. for option in self.options:
  3446. if option.find(kind + "_") == 0:
  3447. oname = option[len(kind) + 1:]
  3448. obj.options[oname] = self.options[option]
  3449. obj.isHovering = False
  3450. obj.notHovering = True
  3451. # Initialize as per user request
  3452. # User must take care to implement initialize
  3453. # in a thread-safe way as is is likely that we
  3454. # have been invoked in a separate thread.
  3455. t1 = time.time()
  3456. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3457. try:
  3458. return_value = initialize(obj, self)
  3459. except Exception as e:
  3460. msg = '[ERROR_NOTCL] %s' % \
  3461. _("An internal error has ocurred. See shell.\n")
  3462. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3463. msg += traceback.format_exc()
  3464. self.inform.emit(msg)
  3465. # if str(e) == "Empty Geometry":
  3466. # self.inform.emit("[ERROR_NOTCL] )
  3467. # else:
  3468. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  3469. return "fail"
  3470. t2 = time.time()
  3471. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3472. if return_value == 'fail':
  3473. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3474. return "fail"
  3475. # Check units and convert if necessary
  3476. # This condition CAN be true because initialize() can change obj.units
  3477. if self.options["units"].upper() != obj.units.upper():
  3478. self.inform.emit('%s: %s' %
  3479. (_("Converting units to "), self.options["units"]))
  3480. obj.convert_units(self.options["units"])
  3481. t3 = time.time()
  3482. self.log.debug("%f seconds converting units." % (t3 - t2))
  3483. # Create the bounding box for the object and then add the results to the obj.options
  3484. # But not for Scripts or for Documents
  3485. if kind != 'document' and kind != 'script':
  3486. try:
  3487. xmin, ymin, xmax, ymax = obj.bounds()
  3488. obj.options['xmin'] = xmin
  3489. obj.options['ymin'] = ymin
  3490. obj.options['xmax'] = xmax
  3491. obj.options['ymax'] = ymax
  3492. except Exception as e:
  3493. log.warning("The object has no bounds properties. %s" % str(e))
  3494. return "fail"
  3495. # update the KeyWords list with the name of the file
  3496. self.myKeywords.append(obj.options['name'])
  3497. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3498. # Move the object to the main thread and let the app know that it is available.
  3499. obj.moveToThread(self.main_thread)
  3500. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3501. return obj
  3502. def new_excellon_object(self):
  3503. """
  3504. Creates a new, blank Excellon object.
  3505. :return: None
  3506. """
  3507. self.report_usage("new_excellon_object()")
  3508. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3509. def new_geometry_object(self):
  3510. """
  3511. Creates a new, blank and single-tool Geometry object.
  3512. :return: None
  3513. """
  3514. self.report_usage("new_geometry_object()")
  3515. def initialize(obj, app):
  3516. obj.multitool = False
  3517. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3518. def new_gerber_object(self):
  3519. """
  3520. Creates a new, blank Gerber object.
  3521. :return: None
  3522. """
  3523. self.report_usage("new_gerber_object()")
  3524. def initialize(grb_obj, app):
  3525. grb_obj.multitool = False
  3526. grb_obj.source_file = []
  3527. grb_obj.multigeo = False
  3528. grb_obj.follow = False
  3529. grb_obj.apertures = {}
  3530. grb_obj.solid_geometry = []
  3531. try:
  3532. grb_obj.options['xmin'] = 0
  3533. grb_obj.options['ymin'] = 0
  3534. grb_obj.options['xmax'] = 0
  3535. grb_obj.options['ymax'] = 0
  3536. except KeyError:
  3537. pass
  3538. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3539. def new_script_object(self, name=None, text=None):
  3540. """
  3541. Creates a new, blank TCL Script object.
  3542. :param name: a name for the new object
  3543. :param text: pass a source file to the newly created script to be loaded in it
  3544. :return: None
  3545. """
  3546. self.report_usage("new_script_object()")
  3547. if text is not None:
  3548. new_source_file = text
  3549. else:
  3550. commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  3551. "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n"\
  3552. "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  3553. "ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n"\
  3554. "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  3555. "ListSys, MillDrills,\n"\
  3556. "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  3557. "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"\
  3558. "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  3559. "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  3560. "# SubtractRectangle, Version, WriteGCode\n"
  3561. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  3562. '# %s:\n' % _('TCL Tutorial is here') + \
  3563. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  3564. '# %s:\n' % _("FlatCAM commands list")
  3565. new_source_file += commands_list + '\n'
  3566. def initialize(obj, app):
  3567. obj.source_file = deepcopy(new_source_file)
  3568. if name is None:
  3569. outname = 'new_script'
  3570. else:
  3571. outname = name
  3572. self.new_object('script', outname, initialize, plot=False)
  3573. def new_document_object(self):
  3574. """
  3575. Creates a new, blank Document object.
  3576. :return: None
  3577. """
  3578. self.report_usage("new_document_object()")
  3579. def initialize(obj, app):
  3580. obj.source_file = ""
  3581. self.new_object('document', 'new_document', initialize, plot=False)
  3582. def on_object_created(self, obj, plot, auto_select):
  3583. """
  3584. Event callback for object creation.
  3585. It will add the new object to the collection. After that it will plot the object in a threaded way
  3586. :param obj: The newly created FlatCAM object.
  3587. :param plot: if the newly create object t obe plotted
  3588. :param auto_select: if the newly created object to be autoselected after creation
  3589. :return: None
  3590. """
  3591. t0 = time.time() # DEBUG
  3592. self.log.debug("on_object_created()")
  3593. # The Collection might change the name if there is a collision
  3594. self.collection.append(obj)
  3595. # after adding the object to the collection always update the list of objects that are in the collection
  3596. self.all_objects_list = self.collection.get_list()
  3597. # self.inform.emit('[selected] %s created & selected: %s' %
  3598. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3599. if obj.kind == 'gerber':
  3600. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3601. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3602. elif obj.kind == 'excellon':
  3603. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3604. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3605. elif obj.kind == 'cncjob':
  3606. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3607. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3608. elif obj.kind == 'geometry':
  3609. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3610. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3611. elif obj.kind == 'script':
  3612. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3613. kind=obj.kind.capitalize(), color='orange', name=str(obj.options['name'])))
  3614. elif obj.kind == 'document':
  3615. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3616. kind=obj.kind.capitalize(), color='darkCyan', name=str(obj.options['name'])))
  3617. # update the SHELL auto-completer model with the name of the new object
  3618. self.shell._edit.set_model_data(self.myKeywords)
  3619. if auto_select:
  3620. # select the just opened object but deselect the previous ones
  3621. self.collection.set_all_inactive()
  3622. self.collection.set_active(obj.options["name"])
  3623. else:
  3624. self.collection.set_all_inactive()
  3625. # here it is done the object plotting
  3626. def worker_task(t_obj):
  3627. with self.proc_container.new(_("Plotting")):
  3628. if isinstance(t_obj, FlatCAMCNCjob):
  3629. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3630. else:
  3631. t_obj.plot()
  3632. t1 = time.time() # DEBUG
  3633. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3634. self.object_plotted.emit(t_obj)
  3635. # Send to worker
  3636. # self.worker.add_task(worker_task, [self])
  3637. if plot is True:
  3638. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3639. def on_object_changed(self, obj):
  3640. """
  3641. Called whenever the geometry of the object was changed in some way.
  3642. This require the update of it's bounding values so it can be the selected on canvas.
  3643. Update the bounding box data from obj.options
  3644. :param obj: the object that was changed
  3645. :return: None
  3646. """
  3647. xmin, ymin, xmax, ymax = obj.bounds()
  3648. obj.options['xmin'] = xmin
  3649. obj.options['ymin'] = ymin
  3650. obj.options['xmax'] = xmax
  3651. obj.options['ymax'] = ymax
  3652. log.debug("Object changed, updating the bounding box data on self.options")
  3653. # delete the old selection shape
  3654. self.delete_selection_shape()
  3655. self.should_we_save = True
  3656. def on_object_plotted(self):
  3657. """
  3658. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3659. :return: None
  3660. """
  3661. self.on_zoom_fit(None)
  3662. def on_about(self):
  3663. """
  3664. Displays the "about" dialog found in the Menu --> Help.
  3665. :return: None
  3666. """
  3667. self.report_usage("on_about")
  3668. version = self.version
  3669. version_date = self.version_date
  3670. beta = self.beta
  3671. class AboutDialog(QtWidgets.QDialog):
  3672. def __init__(self, parent=None):
  3673. QtWidgets.QDialog.__init__(self, parent)
  3674. # Icon and title
  3675. self.setWindowIcon(parent.app_icon)
  3676. self.setWindowTitle(_("About FlatCAM"))
  3677. self.resize(600, 200)
  3678. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3679. # self.setStyleSheet(
  3680. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3681. # "background-attachment: fixed"
  3682. # )
  3683. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3684. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3685. # palette = QtGui.QPalette()
  3686. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3687. # self.setPalette(palette)
  3688. logo = QtWidgets.QLabel()
  3689. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3690. title = QtWidgets.QLabel(
  3691. "<font size=8><B>FlatCAM</B></font><BR>"
  3692. "{title}<BR>"
  3693. "<BR>"
  3694. "<BR>"
  3695. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3696. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3697. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3698. "<B>{issue}</B></a><BR>".format(
  3699. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3700. devel=_("Development"),
  3701. down=_("DOWNLOAD"),
  3702. issue=_("Issue tracker"))
  3703. )
  3704. title.setOpenExternalLinks(True)
  3705. closebtn = QtWidgets.QPushButton(_("Close"))
  3706. tab_widget = QtWidgets.QTabWidget()
  3707. description_label = QtWidgets.QLabel(
  3708. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3709. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3710. version=version,
  3711. beta=('BETA' if beta else ''),
  3712. date=version_date,
  3713. arch=platform.architecture()[0])
  3714. )
  3715. description_label.setOpenExternalLinks(True)
  3716. lic_lbl_header = QtWidgets.QLabel(
  3717. '%s:<br>%s<br>' % (
  3718. _('Licensed under the MIT license'),
  3719. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  3720. "http://www.opensource.org/licenses/mit-license.php</a>"
  3721. )
  3722. )
  3723. lic_lbl_header.setOpenExternalLinks(True)
  3724. lic_lbl_body = QtWidgets.QLabel(
  3725. _(
  3726. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3727. 'of this software and associated documentation files (the "Software"), to deal\n'
  3728. 'in the Software without restriction, including without limitation the rights\n'
  3729. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3730. 'copies of the Software, and to permit persons to whom the Software is\n'
  3731. 'furnished to do so, subject to the following conditions:\n\n'
  3732. 'The above copyright notice and this permission notice shall be included in\n'
  3733. 'all copies or substantial portions of the Software.\n\n'
  3734. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3735. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3736. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3737. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3738. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3739. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3740. 'THE SOFTWARE.'
  3741. )
  3742. )
  3743. attributions_label = QtWidgets.QLabel(
  3744. _(
  3745. 'Some of the icons used are from the following sources:<br>'
  3746. '<div>Icons made by <a href="https://www.flaticon.com/authors/freepik" '
  3747. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  3748. 'title="Flaticon">www.flaticon.com</a></div>'
  3749. 'Icons by <a target="_blank" href="https://icons8.com">Icons8</a>'
  3750. )
  3751. )
  3752. # layouts
  3753. layout1 = QtWidgets.QVBoxLayout()
  3754. layout1_1 = QtWidgets.QHBoxLayout()
  3755. layout1_2 = QtWidgets.QHBoxLayout()
  3756. layout2 = QtWidgets.QHBoxLayout()
  3757. layout3 = QtWidgets.QHBoxLayout()
  3758. self.setLayout(layout1)
  3759. layout1.addLayout(layout1_1)
  3760. layout1.addLayout(layout1_2)
  3761. layout1.addLayout(layout2)
  3762. layout1.addLayout(layout3)
  3763. layout1_1.addStretch()
  3764. layout1_1.addWidget(description_label)
  3765. layout1_2.addWidget(tab_widget)
  3766. self.splash_tab = QtWidgets.QWidget()
  3767. self.splash_tab.setObjectName("splash_about")
  3768. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3769. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3770. tab_widget.addTab(self.splash_tab, _("Splash"))
  3771. self.programmmers_tab = QtWidgets.QWidget()
  3772. self.programmmers_tab.setObjectName("programmers_about")
  3773. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3774. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3775. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3776. self.translators_tab = QtWidgets.QWidget()
  3777. self.translators_tab.setObjectName("translators_about")
  3778. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3779. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3780. tab_widget.addTab(self.translators_tab, _("Translators"))
  3781. self.license_tab = QtWidgets.QWidget()
  3782. self.license_tab.setObjectName("license_about")
  3783. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3784. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3785. tab_widget.addTab(self.license_tab, _("License"))
  3786. self.attributions_tab = QtWidgets.QWidget()
  3787. self.attributions_tab.setObjectName("attributions_about")
  3788. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  3789. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  3790. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  3791. self.splash_tab_layout.addWidget(logo, stretch=0)
  3792. self.splash_tab_layout.addWidget(title, stretch=1)
  3793. pal = QtGui.QPalette()
  3794. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3795. self.prog_grid_lay = QtWidgets.QGridLayout()
  3796. self.prog_grid_lay.setHorizontalSpacing(20)
  3797. self.prog_grid_lay.setColumnStretch(0, 0)
  3798. self.prog_grid_lay.setColumnStretch(2, 1)
  3799. prog_widget = QtWidgets.QWidget()
  3800. prog_widget.setLayout(self.prog_grid_lay)
  3801. prog_scroll = QtWidgets.QScrollArea()
  3802. prog_scroll.setWidget(prog_widget)
  3803. prog_scroll.setWidgetResizable(True)
  3804. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3805. prog_scroll.setPalette(pal)
  3806. self.programmmers_tab_layout.addWidget(prog_scroll)
  3807. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  3808. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  3809. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3810. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  3811. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Program Author"), 1, 1)
  3812. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  3813. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  3814. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  3815. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  3816. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  3817. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  3818. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  3819. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 6, 0)
  3820. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  3821. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  3822. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  3823. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  3824. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 11, 0)
  3825. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  3826. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  3827. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 14, 0)
  3828. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 12, 0)
  3829. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 15, 0)
  3830. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 16, 0)
  3831. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 17, 0)
  3832. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 18, 0)
  3833. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 19, 0)
  3834. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 20, 0)
  3835. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 21, 0)
  3836. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 22, 0)
  3837. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 23, 0)
  3838. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 24, 0)
  3839. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 25, 0)
  3840. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 26, 0)
  3841. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 27, 0)
  3842. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 28, 0)
  3843. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 29, 0)
  3844. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 30, 0)
  3845. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 31, 0)
  3846. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 32, 0)
  3847. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 33, 0)
  3848. self.translator_grid_lay = QtWidgets.QGridLayout()
  3849. self.translator_grid_lay.setColumnStretch(0, 0)
  3850. self.translator_grid_lay.setColumnStretch(1, 0)
  3851. self.translator_grid_lay.setColumnStretch(2, 1)
  3852. self.translator_grid_lay.setColumnStretch(3, 0)
  3853. # trans_widget = QtWidgets.QWidget()
  3854. # trans_widget.setLayout(self.translator_grid_lay)
  3855. # self.translators_tab_layout.addWidget(trans_widget)
  3856. # self.translators_tab_layout.addStretch()
  3857. trans_widget = QtWidgets.QWidget()
  3858. trans_widget.setLayout(self.translator_grid_lay)
  3859. trans_scroll = QtWidgets.QScrollArea()
  3860. trans_scroll.setWidget(trans_widget)
  3861. trans_scroll.setWidgetResizable(True)
  3862. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3863. trans_scroll.setPalette(pal)
  3864. self.translators_tab_layout.addWidget(trans_scroll)
  3865. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  3866. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  3867. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  3868. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  3869. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  3870. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  3871. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  3872. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  3873. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 2, 1)
  3874. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "(Google-Translation)"), 2, 2)
  3875. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  3876. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  3877. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 3, 1)
  3878. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt"), 3, 2)
  3879. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  3880. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  3881. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  3882. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 3)
  3883. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  3884. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  3885. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 3)
  3886. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  3887. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  3888. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "(Google-Translation)"), 6, 2)
  3889. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 3)
  3890. self.translator_grid_lay.setColumnStretch(0, 0)
  3891. self.translators_tab_layout.addStretch()
  3892. self.license_tab_layout.addWidget(lic_lbl_header)
  3893. self.license_tab_layout.addWidget(lic_lbl_body)
  3894. self.license_tab_layout.addStretch()
  3895. self.attributions_tab_layout.addWidget(attributions_label)
  3896. self.attributions_tab_layout.addStretch()
  3897. layout3.addStretch()
  3898. layout3.addWidget(closebtn)
  3899. closebtn.clicked.connect(self.accept)
  3900. AboutDialog(self.ui).exec_()
  3901. def install_bookmarks(self, book_dict=None):
  3902. """
  3903. Install the bookmarks actions in the Help menu -> Bookmarks
  3904. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  3905. :return: None
  3906. """
  3907. if book_dict is None:
  3908. self.defaults["global_bookmarks"].update(
  3909. {
  3910. '1': ['FlatCAM', "http://flatcam.org"],
  3911. '2': ['Backup Site', ""]
  3912. }
  3913. )
  3914. else:
  3915. self.defaults["global_bookmarks"].clear()
  3916. self.defaults["global_bookmarks"].update(book_dict)
  3917. # first try to disconnect if somehow they get connected from elsewhere
  3918. for act in self.ui.menuhelp_bookmarks.actions():
  3919. try:
  3920. act.triggered.disconnect()
  3921. except TypeError:
  3922. pass
  3923. # clear all actions except the last one who is the Bookmark manager
  3924. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  3925. pass
  3926. else:
  3927. self.ui.menuhelp_bookmarks.removeAction(act)
  3928. bm_limit = int(self.defaults["global_bookmarks_limit"])
  3929. if self.defaults["global_bookmarks"]:
  3930. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  3931. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  3932. # the JSON is first making the keys as strings (therefore I have to use strings too
  3933. # or do the conversion :(
  3934. # )
  3935. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  3936. # the '10' entry jsut after '1' therefore ordering as strings
  3937. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  3938. key=lambda x: int(x[0]))
  3939. for entry, bookmark in sorted_bookmarks:
  3940. title = bookmark[0]
  3941. weblink = bookmark[1]
  3942. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  3943. act.setText(title)
  3944. act.setIcon(QtGui.QIcon('share/link16.png'))
  3945. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  3946. if title == 'Backup Site' and weblink == "":
  3947. act.triggered.connect(self.on_backup_site)
  3948. else:
  3949. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  3950. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  3951. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  3952. def on_bookmarks_manager(self):
  3953. """
  3954. Adds the bookmark manager in a Tab in Plot Area
  3955. :return:
  3956. """
  3957. for idx in range(self.ui.plot_tab_area.count()):
  3958. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  3959. # there can be only one instance of Bookmark Manager at one time
  3960. return
  3961. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  3962. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  3963. # add the tab if it was closed
  3964. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  3965. # delete the absolute and relative position and messages in the infobar
  3966. self.ui.position_label.setText("")
  3967. self.ui.rel_position_label.setText("")
  3968. # Switch plot_area to preferences page
  3969. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  3970. @staticmethod
  3971. def on_backup_site():
  3972. msgbox = QtWidgets.QMessageBox()
  3973. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  3974. "1. FlatCAM.org website is down\n"
  3975. "2. Someone forked FlatCAM project and wants to point\n"
  3976. "to his own website\n\n"
  3977. "If you can't get any informations about FlatCAM beta\n"
  3978. "use the YouTube channel link from the Help menu."))
  3979. msgbox.setWindowTitle(_("Alternative website"))
  3980. msgbox.setWindowIcon(QtGui.QIcon('share/globe16.png'))
  3981. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  3982. msgbox.setDefaultButton(bt_yes)
  3983. msgbox.exec_()
  3984. # response = msgbox.clickedButton()
  3985. def on_file_savedefaults(self):
  3986. """
  3987. Callback for menu item File->Save Defaults. Saves application default options
  3988. ``self.defaults`` to current_defaults.FlatConfig.
  3989. :return: None
  3990. """
  3991. self.save_defaults()
  3992. # def on_app_exit(self):
  3993. # self.report_usage("on_app_exit()")
  3994. #
  3995. # if self.collection.get_list():
  3996. # msgbox = QtWidgets.QMessageBox()
  3997. # # msgbox.setText("<B>Save changes ...</B>")
  3998. # msgbox.setText("There are files/objects opened in FlatCAM. "
  3999. # "\n"
  4000. # "Do you want to Save the project?")
  4001. # msgbox.setWindowTitle("Save changes")
  4002. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4003. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  4004. # QtWidgets.QMessageBox.Cancel)
  4005. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  4006. #
  4007. # response = msgbox.exec_()
  4008. #
  4009. # if response == QtWidgets.QMessageBox.Yes:
  4010. # self.on_file_saveprojectas(thread=False)
  4011. # elif response == QtWidgets.QMessageBox.Cancel:
  4012. # return
  4013. # self.save_defaults()
  4014. # else:
  4015. # self.save_defaults()
  4016. # log.debug("Application defaults saved ... Exit event.")
  4017. # QtWidgets.qApp.quit()
  4018. def save_defaults(self, silent=False, data_path=None, first_time=False):
  4019. """
  4020. Saves application default options
  4021. ``self.defaults`` to current_defaults.FlatConfig file.
  4022. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  4023. used at the next launch of the application.
  4024. :param silent: whether to display a message in status bar or not; boolean
  4025. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  4026. When the application is portable it should be a mobile location.
  4027. :return: None
  4028. """
  4029. self.report_usage("save_defaults")
  4030. if data_path is None:
  4031. data_path = self.data_path
  4032. # Read options from file
  4033. try:
  4034. f = open(data_path + "/current_defaults.FlatConfig")
  4035. defaults_file_content = f.read()
  4036. f.close()
  4037. except Exception:
  4038. e = sys.exc_info()[0]
  4039. App.log.error("Could not load defaults file.")
  4040. App.log.error(str(e))
  4041. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load defaults file."))
  4042. return
  4043. try:
  4044. defaults = json.loads(defaults_file_content)
  4045. except Exception:
  4046. e = sys.exc_info()[0]
  4047. App.log.error("Failed to parse defaults file.")
  4048. App.log.error(str(e))
  4049. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse defaults file."))
  4050. return
  4051. # Update options
  4052. self.defaults_read_form()
  4053. defaults.update(self.defaults)
  4054. self.propagate_defaults(silent=True)
  4055. # Save the toolbar view
  4056. tb_status = 0
  4057. if self.ui.toolbarfile.isVisible():
  4058. tb_status += 1
  4059. if self.ui.toolbargeo.isVisible():
  4060. tb_status += 2
  4061. if self.ui.toolbarview.isVisible():
  4062. tb_status += 4
  4063. if self.ui.toolbartools.isVisible():
  4064. tb_status += 8
  4065. if self.ui.exc_edit_toolbar.isVisible():
  4066. tb_status += 16
  4067. if self.ui.geo_edit_toolbar.isVisible():
  4068. tb_status += 32
  4069. if self.ui.grb_edit_toolbar.isVisible():
  4070. tb_status += 64
  4071. if self.ui.snap_toolbar.isVisible():
  4072. tb_status += 128
  4073. if self.ui.toolbarshell.isVisible():
  4074. tb_status += 256
  4075. if first_time is False:
  4076. self.defaults["global_toolbar_view"] = tb_status
  4077. # Save update options
  4078. try:
  4079. f = open(data_path + "/current_defaults.FlatConfig", "w")
  4080. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  4081. f.close()
  4082. except Exception as e:
  4083. log.debug("App.save_defaults() --> %s" % str(e))
  4084. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to write defaults to file."))
  4085. return
  4086. if not silent:
  4087. self.inform.emit('[success] %s' % _("Preferences saved."))
  4088. def save_factory_defaults(self, silent_message=False, data_path=None):
  4089. """
  4090. Saves application factory default options
  4091. ``self.defaults`` to factory_defaults.FlatConfig.
  4092. It's a one time job done just after the first install.
  4093. :param silent_message: whether to display a message in status bar or not; boolean
  4094. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  4095. When the application is portable it should be a mobile location.
  4096. :return: None
  4097. """
  4098. self.report_usage("save_factory_defaults")
  4099. if data_path is None:
  4100. data_path = self.data_path
  4101. # Read options from file
  4102. try:
  4103. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  4104. factory_defaults_file_content = f_f_def.read()
  4105. f_f_def.close()
  4106. except Exception:
  4107. e = sys.exc_info()[0]
  4108. App.log.error("Could not load factory defaults file.")
  4109. App.log.error(str(e))
  4110. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load factory defaults file."))
  4111. return
  4112. try:
  4113. factory_defaults = json.loads(factory_defaults_file_content)
  4114. except Exception:
  4115. e = sys.exc_info()[0]
  4116. App.log.error("Failed to parse factory defaults file.")
  4117. App.log.error(str(e))
  4118. if silent_message is False:
  4119. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse factory defaults file."))
  4120. return
  4121. # Update options
  4122. self.defaults_read_form()
  4123. factory_defaults.update(self.defaults)
  4124. self.propagate_defaults(silent=True)
  4125. # Save update options
  4126. try:
  4127. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  4128. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  4129. f_f_def_s.close()
  4130. except Exception as e:
  4131. log.debug("App.save_factory_default() save update --> %s" % str(e))
  4132. if silent_message is False:
  4133. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to write factory defaults to file."))
  4134. return
  4135. if silent_message is False:
  4136. self.inform.emit(_("Factory defaults saved."))
  4137. def final_save(self):
  4138. """
  4139. Callback for doing a preferences save to file whenever the application is about to quit.
  4140. If the project has changes, it will ask the user to save the project.
  4141. :return: None
  4142. """
  4143. if self.save_in_progress:
  4144. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  4145. return
  4146. if self.should_we_save and self.collection.get_list():
  4147. msgbox = QtWidgets.QMessageBox()
  4148. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  4149. "\n"
  4150. "Do you want to Save the project?"))
  4151. msgbox.setWindowTitle(_("Save changes"))
  4152. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4153. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4154. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4155. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4156. msgbox.setDefaultButton(bt_yes)
  4157. msgbox.exec_()
  4158. response = msgbox.clickedButton()
  4159. if response == bt_yes:
  4160. try:
  4161. self.trayIcon.hide()
  4162. except Exception:
  4163. pass
  4164. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  4165. elif response == bt_no:
  4166. try:
  4167. self.trayIcon.hide()
  4168. except Exception:
  4169. pass
  4170. self.quit_application()
  4171. elif response == bt_cancel:
  4172. return
  4173. else:
  4174. try:
  4175. self.trayIcon.hide()
  4176. except Exception:
  4177. pass
  4178. self.quit_application()
  4179. def quit_application(self):
  4180. """
  4181. Called (as a pyslot or not) when the application is quit.
  4182. :return: None
  4183. """
  4184. self.save_defaults()
  4185. log.debug("App.final_save() --> App Defaults saved.")
  4186. if self.cmd_line_headless != 1:
  4187. # save app state to file
  4188. stgs = QSettings("Open Source", "FlatCAM")
  4189. stgs.setValue('saved_gui_state', self.ui.saveState())
  4190. stgs.setValue('maximized_gui', self.ui.isMaximized())
  4191. stgs.setValue(
  4192. 'language',
  4193. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  4194. )
  4195. stgs.setValue(
  4196. 'notebook_font_size',
  4197. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  4198. )
  4199. stgs.setValue(
  4200. 'axis_font_size',
  4201. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  4202. )
  4203. stgs.setValue(
  4204. 'textbox_font_size',
  4205. self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  4206. )
  4207. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  4208. stgs.setValue(
  4209. 'machinist',
  4210. 1 if self.ui.general_defaults_form.general_app_group.machinist_cb.get_value() else 0
  4211. )
  4212. # This will write the setting to the platform specific storage.
  4213. del stgs
  4214. log.debug("App.final_save() --> App UI state saved.")
  4215. QtWidgets.qApp.quit()
  4216. def on_portable_checked(self, state):
  4217. """
  4218. Callback called when the checkbox in Preferences GUI is checked.
  4219. It will set the application as portable by creating the preferences and recent files in the
  4220. 'config' folder found in the FlatCAM installation folder.
  4221. :param state: boolean, the state of the checkbox when clicked/checked
  4222. :return:
  4223. """
  4224. line_no = 0
  4225. data = None
  4226. if sys.platform != 'win32':
  4227. # this won't work in Linux or MacOS
  4228. return
  4229. # test if the app was frozen and choose the path for the configuration file
  4230. if getattr(sys, "frozen", False) is True:
  4231. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  4232. else:
  4233. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  4234. config_file = current_data_path + '\\configuration.txt'
  4235. try:
  4236. with open(config_file, 'r') as f:
  4237. try:
  4238. data = f.readlines()
  4239. except Exception as e:
  4240. log.debug('App.__init__() -->%s' % str(e))
  4241. return
  4242. except FileNotFoundError:
  4243. pass
  4244. for line in data:
  4245. line = line.strip('\n')
  4246. param = str(line).rpartition('=')
  4247. if param[0] == 'portable':
  4248. break
  4249. line_no += 1
  4250. if state:
  4251. data[line_no] = 'portable=True\n'
  4252. # create the new defauults files
  4253. # create current_defaults.FlatConfig file if there is none
  4254. try:
  4255. f = open(current_data_path + '/current_defaults.FlatConfig')
  4256. f.close()
  4257. except IOError:
  4258. App.log.debug('Creating empty current_defaults.FlatConfig')
  4259. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  4260. json.dump({}, f)
  4261. f.close()
  4262. # create factory_defaults.FlatConfig file if there is none
  4263. try:
  4264. f = open(current_data_path + '/factory_defaults.FlatConfig')
  4265. f.close()
  4266. except IOError:
  4267. App.log.debug('Creating empty factory_defaults.FlatConfig')
  4268. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  4269. json.dump({}, f)
  4270. f.close()
  4271. try:
  4272. f = open(current_data_path + '/recent.json')
  4273. f.close()
  4274. except IOError:
  4275. App.log.debug('Creating empty recent.json')
  4276. f = open(current_data_path + '/recent.json', 'w')
  4277. json.dump([], f)
  4278. f.close()
  4279. try:
  4280. fp = open(current_data_path + '/recent_projects.json')
  4281. fp.close()
  4282. except IOError:
  4283. App.log.debug('Creating empty recent_projects.json')
  4284. fp = open(current_data_path + '/recent_projects.json', 'w')
  4285. json.dump([], fp)
  4286. fp.close()
  4287. # save the current defaults to the new defaults file
  4288. self.save_defaults(silent=True, data_path=current_data_path)
  4289. self.save_factory_defaults(silent_message=True, data_path=current_data_path)
  4290. else:
  4291. data[line_no] = 'portable=False\n'
  4292. with open(config_file, 'w') as f:
  4293. f.writelines(data)
  4294. def on_toggle_shell(self):
  4295. """
  4296. Toggle shell: if is visible close it, if it is closed then open it
  4297. :return: None
  4298. """
  4299. self.report_usage("on_toggle_shell()")
  4300. if self.ui.shell_dock.isVisible():
  4301. self.ui.shell_dock.hide()
  4302. else:
  4303. self.ui.shell_dock.show()
  4304. def on_register_files(self, obj_type=None):
  4305. """
  4306. Called whenever there is a need to register file extensions with FlatCAM.
  4307. Works only in Windows and should be called only when FlatCAM is run in Windows.
  4308. :param obj_type: the type of object to be register for.
  4309. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  4310. :return: None
  4311. """
  4312. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  4313. new_reg_path = 'Software\\Classes\\'
  4314. # find if the current user is admin
  4315. try:
  4316. is_admin = os.getuid() == 0
  4317. except AttributeError:
  4318. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  4319. if is_admin is True:
  4320. root_path = winreg.HKEY_LOCAL_MACHINE
  4321. else:
  4322. root_path = winreg.HKEY_CURRENT_USER
  4323. # create the keys
  4324. def set_reg(name, root_path, new_reg_path, value):
  4325. try:
  4326. winreg.CreateKey(root_path, new_reg_path)
  4327. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  4328. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  4329. return True
  4330. except WindowsError:
  4331. return False
  4332. # delete key in registry
  4333. def delete_reg(root_path, reg_path, key_to_del):
  4334. key_to_del_path = reg_path + key_to_del
  4335. try:
  4336. winreg.DeleteKey(root_path, key_to_del_path)
  4337. return True
  4338. except WindowsError:
  4339. return False
  4340. if obj_type is None or obj_type == 'excellon':
  4341. exc_list = \
  4342. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4343. exc_list = [x for x in exc_list if x != '']
  4344. # register all keys in the Preferences window
  4345. for ext in exc_list:
  4346. new_k = new_reg_path + '.%s' % ext
  4347. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4348. # and unregister those that are no longer in the Preferences windows but are in the file
  4349. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  4350. if ext not in exc_list:
  4351. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4352. # now write the updated extensions to the self.defaults
  4353. # new_ext = ''
  4354. # for ext in exc_list:
  4355. # new_ext = new_ext + ext + ', '
  4356. # self.defaults["fa_excellon"] = new_ext
  4357. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  4358. if obj_type is None or obj_type == 'gcode':
  4359. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4360. gco_list = [x for x in gco_list if x != '']
  4361. # register all keys in the Preferences window
  4362. for ext in gco_list:
  4363. new_k = new_reg_path + '.%s' % ext
  4364. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4365. # and unregister those that are no longer in the Preferences windows but are in the file
  4366. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  4367. if ext not in gco_list:
  4368. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4369. # now write the updated extensions to the self.defaults
  4370. # new_ext = ''
  4371. # for ext in gco_list:
  4372. # new_ext = new_ext + ext + ', '
  4373. # self.defaults["fa_gcode"] = new_ext
  4374. self.inform.emit('[success] %s' %
  4375. _("Selected GCode file extensions registered with FlatCAM."))
  4376. if obj_type is None or obj_type == 'gerber':
  4377. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4378. grb_list = [x for x in grb_list if x != '']
  4379. # register all keys in the Preferences window
  4380. for ext in grb_list:
  4381. new_k = new_reg_path + '.%s' % ext
  4382. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4383. # and unregister those that are no longer in the Preferences windows but are in the file
  4384. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  4385. if ext not in grb_list:
  4386. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4387. # now write the updated extensions to the self.defaults
  4388. # new_ext = ''
  4389. # for ext in grb_list:
  4390. # new_ext = new_ext + ext + ', '
  4391. # self.defaults["fa_gerber"] = new_ext
  4392. self.inform.emit('[success] %s' %
  4393. _("Selected Gerber file extensions registered with FlatCAM."))
  4394. def add_extension(self, ext_type):
  4395. """
  4396. Add a file extension to the list for a specific object
  4397. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4398. :return:
  4399. """
  4400. if ext_type == 'excellon':
  4401. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4402. if new_ext == '':
  4403. return
  4404. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4405. if new_ext in old_val:
  4406. return
  4407. old_val.append(new_ext)
  4408. old_val.sort()
  4409. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4410. if ext_type == 'gcode':
  4411. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4412. if new_ext == '':
  4413. return
  4414. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4415. if new_ext in old_val:
  4416. return
  4417. old_val.append(new_ext)
  4418. old_val.sort()
  4419. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4420. if ext_type == 'gerber':
  4421. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4422. if new_ext == '':
  4423. return
  4424. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4425. if new_ext in old_val:
  4426. return
  4427. old_val.append(new_ext)
  4428. old_val.sort()
  4429. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4430. if ext_type == 'keyword':
  4431. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4432. if new_kw == '':
  4433. return
  4434. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4435. if new_kw in old_val:
  4436. return
  4437. old_val.append(new_kw)
  4438. old_val.sort()
  4439. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4440. # update the self.myKeywords so the model is updated
  4441. self.autocomplete_kw_list = \
  4442. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4443. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4444. self.shell._edit.set_model_data(self.myKeywords)
  4445. def del_extension(self, ext_type):
  4446. """
  4447. Remove a file extension from the list for a specific object
  4448. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4449. :return:
  4450. """
  4451. if ext_type == 'excellon':
  4452. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4453. if new_ext == '':
  4454. return
  4455. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4456. if new_ext not in old_val:
  4457. return
  4458. old_val.remove(new_ext)
  4459. old_val.sort()
  4460. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4461. if ext_type == 'gcode':
  4462. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4463. if new_ext == '':
  4464. return
  4465. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4466. if new_ext not in old_val:
  4467. return
  4468. old_val.remove(new_ext)
  4469. old_val.sort()
  4470. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4471. if ext_type == 'gerber':
  4472. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4473. if new_ext == '':
  4474. return
  4475. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4476. if new_ext not in old_val:
  4477. return
  4478. old_val.remove(new_ext)
  4479. old_val.sort()
  4480. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4481. if ext_type == 'keyword':
  4482. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4483. if new_kw == '':
  4484. return
  4485. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4486. if new_kw not in old_val:
  4487. return
  4488. old_val.remove(new_kw)
  4489. old_val.sort()
  4490. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4491. # update the self.myKeywords so the model is updated
  4492. self.autocomplete_kw_list = \
  4493. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4494. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4495. self.shell._edit.set_model_data(self.myKeywords)
  4496. def restore_extensions(self, ext_type):
  4497. """
  4498. Restore all file extensions associations with FlatCAM, for a specific object
  4499. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4500. :return:
  4501. """
  4502. if ext_type == 'excellon':
  4503. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  4504. # for the ability to open Excellon files with .txt extension
  4505. new_exc_list = deepcopy(self.exc_list)
  4506. try:
  4507. new_exc_list.remove('txt')
  4508. except ValueError:
  4509. pass
  4510. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  4511. if ext_type == 'gcode':
  4512. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  4513. if ext_type == 'gerber':
  4514. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  4515. if ext_type == 'keyword':
  4516. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  4517. # update the self.myKeywords so the model is updated
  4518. self.autocomplete_kw_list = self.default_keywords
  4519. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4520. self.shell._edit.set_model_data(self.myKeywords)
  4521. def delete_all_extensions(self, ext_type):
  4522. """
  4523. Delete all file extensions associations with FlatCAM, for a specific object
  4524. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4525. :return:
  4526. """
  4527. if ext_type == 'excellon':
  4528. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4529. if ext_type == 'gcode':
  4530. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4531. if ext_type == 'gerber':
  4532. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4533. if ext_type == 'keyword':
  4534. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4535. # update the self.myKeywords so the model is updated
  4536. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4537. self.shell._edit.set_model_data(self.myKeywords)
  4538. def on_edit_join(self, name=None):
  4539. """
  4540. Callback for Edit->Join. Joins the selected geometry objects into
  4541. a new one.
  4542. :return: None
  4543. """
  4544. self.report_usage("on_edit_join()")
  4545. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4546. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4547. geo_type_set = set()
  4548. objs = self.collection.get_selected()
  4549. if len(objs) < 2:
  4550. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4551. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4552. return 'fail'
  4553. for obj in objs:
  4554. geo_type_set.add(obj.multigeo)
  4555. # if len(geo_type_list) == 1 means that all list elements are the same
  4556. if len(geo_type_set) != 1:
  4557. self.inform.emit('[ERROR] %s' %
  4558. _("Failed join. The Geometry objects are of different types.\n"
  4559. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4560. "convert from one to another and retry joining \n"
  4561. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4562. "the result may not be what was expected. \n"
  4563. "Check the generated GCODE."))
  4564. return
  4565. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4566. if True in geo_type_set:
  4567. def initialize(geo_obj, app):
  4568. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=True)
  4569. app.inform.emit('[success] %s.' % _("Multigeo. Geometry merging finished"))
  4570. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4571. for v in obj.tools.values():
  4572. v['data']['name'] = obj_name_multi
  4573. self.new_object("geometry", obj_name_multi, initialize)
  4574. else:
  4575. def initialize(geo_obj, app):
  4576. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=False)
  4577. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  4578. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4579. for v in obj.tools.values():
  4580. v['data']['name'] = obj_name_single
  4581. self.new_object("geometry", obj_name_single, initialize)
  4582. self.should_we_save = True
  4583. def on_edit_join_exc(self):
  4584. """
  4585. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4586. a new Excellon.
  4587. :return: None
  4588. """
  4589. self.report_usage("on_edit_join_exc()")
  4590. objs = self.collection.get_selected()
  4591. for obj in objs:
  4592. if not isinstance(obj, FlatCAMExcellon):
  4593. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  4594. return
  4595. if len(objs) < 2:
  4596. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4597. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4598. return 'fail'
  4599. def initialize(exc_obj, app):
  4600. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=exc_obj)
  4601. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  4602. self.new_object("excellon", 'Combo_Excellon', initialize)
  4603. self.should_we_save = True
  4604. def on_edit_join_grb(self):
  4605. """
  4606. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4607. a new Gerber object.
  4608. :return: None
  4609. """
  4610. self.report_usage("on_edit_join_grb()")
  4611. objs = self.collection.get_selected()
  4612. for obj in objs:
  4613. if not isinstance(obj, FlatCAMGerber):
  4614. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  4615. return
  4616. if len(objs) < 2:
  4617. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4618. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4619. return 'fail'
  4620. def initialize(grb_obj, app):
  4621. FlatCAMGerber.merge(self, grb_list=objs, grb_final=grb_obj)
  4622. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  4623. self.new_object("gerber", 'Combo_Gerber', initialize)
  4624. self.should_we_save = True
  4625. def on_convert_singlegeo_to_multigeo(self):
  4626. """
  4627. Called for converting a Geometry object from single-geo to multi-geo.
  4628. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4629. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4630. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4631. the solid-geometry of that tool.
  4632. :return: None
  4633. """
  4634. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4635. obj = self.collection.get_active()
  4636. if obj is None:
  4637. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  4638. return
  4639. if not isinstance(obj, FlatCAMGeometry):
  4640. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4641. return
  4642. obj.multigeo = True
  4643. for tooluid, dict_value in obj.tools.items():
  4644. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4645. if not isinstance(obj.solid_geometry, list):
  4646. obj.solid_geometry = [obj.solid_geometry]
  4647. obj.solid_geometry[:] = []
  4648. obj.plot()
  4649. self.should_we_save = True
  4650. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  4651. def on_convert_multigeo_to_singlegeo(self):
  4652. """
  4653. Called for converting a Geometry object from multi-geo to single-geo.
  4654. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4655. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4656. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4657. the solid-geometry of that tool.
  4658. :return: None
  4659. """
  4660. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4661. obj = self.collection.get_active()
  4662. if obj is None:
  4663. self.inform.emit('[ERROR_NOTCL] %s' %
  4664. _("Failed. Select a Geometry Object and try again."))
  4665. return
  4666. if not isinstance(obj, FlatCAMGeometry):
  4667. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4668. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4669. return
  4670. obj.multigeo = False
  4671. total_solid_geometry = []
  4672. for tooluid, dict_value in obj.tools.items():
  4673. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4674. # clear the original geometry
  4675. dict_value['solid_geometry'][:] = []
  4676. obj.solid_geometry = deepcopy(total_solid_geometry)
  4677. obj.plot()
  4678. self.should_we_save = True
  4679. self.inform.emit('[success] %s' %
  4680. _("A Geometry object was converted to SingleGeo type."))
  4681. def on_defaults_dict_change(self, field):
  4682. """
  4683. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4684. Edit -> Preferences tab window.
  4685. :param field: the key of the self.defaults dictionary that was changed.
  4686. :return: None
  4687. """
  4688. self.defaults_write_form_field(field)
  4689. if field == "units":
  4690. self.set_screen_units(self.defaults['units'])
  4691. def set_screen_units(self, units):
  4692. """
  4693. Set the FlatCAM units on the status bar.
  4694. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4695. :return: None
  4696. """
  4697. self.ui.units_label.setText("[" + units.lower() + "]")
  4698. def on_toggle_units(self, no_pref=False):
  4699. """
  4700. Callback for the Units radio-button change in the Preferences tab.
  4701. Changes the application's default units adn for the project too.
  4702. If changing the project's units, the change propagates to all of
  4703. the objects in the project.
  4704. :return: None
  4705. """
  4706. self.report_usage("on_toggle_units")
  4707. if self.toggle_units_ignore:
  4708. return
  4709. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4710. # If option is the same, then ignore
  4711. if new_units == self.defaults["units"].upper():
  4712. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4713. return
  4714. # Options to scale
  4715. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin', "gerber_isooverlap",
  4716. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  4717. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  4718. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4719. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  4720. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  4721. "excellon_editor_slot_lin_pitch",
  4722. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4723. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4724. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  4725. "geometry_feedrate_probe", "geometry_startz",
  4726. 'cncjob_tooldia',
  4727. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4728. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  4729. "tools_nccnewdia",
  4730. "tools_2sided_drilldia", "tools_film_boundary",
  4731. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4732. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4733. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4734. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4735. "tools_transform_offset_y",
  4736. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4737. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4738. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4739. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4740. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  4741. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  4742. "tools_cr_h2h_val", "tools_cr_dh_val", "tools_fiducials_dia", "tools_fiducials_margin",
  4743. "tools_fiducials_mode", "tools_fiducials_second_pos", "tools_fiducials_type",
  4744. "tools_fiducials_line_thickness",
  4745. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  4746. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  4747. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  4748. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  4749. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  4750. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance"]
  4751. def scale_defaults(sfactor):
  4752. for dim in dimensions:
  4753. if dim == 'excellon_toolchangexy':
  4754. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4755. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4756. coords_xy[0] *= sfactor
  4757. coords_xy[1] *= sfactor
  4758. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4759. elif dim == 'geometry_toolchangexy':
  4760. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4761. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4762. coords_xy[0] *= sfactor
  4763. coords_xy[1] *= sfactor
  4764. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4765. elif dim == 'geometry_cnctooldia':
  4766. tools_diameters = []
  4767. try:
  4768. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4769. tools_diameters = [eval(a) for a in tools_string if a != '']
  4770. except Exception as e:
  4771. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4772. self.defaults['geometry_cnctooldia'] = ''
  4773. for t in range(len(tools_diameters)):
  4774. tools_diameters[t] *= sfactor
  4775. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  4776. elif dim == 'tools_ncctools':
  4777. ncctools = []
  4778. try:
  4779. tools_string = self.defaults["tools_ncctools"].split(",")
  4780. ncctools = [eval(a) for a in tools_string if a != '']
  4781. except Exception as e:
  4782. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4783. self.defaults['tools_ncctools'] = ''
  4784. for t in range(len(ncctools)):
  4785. ncctools[t] *= sfactor
  4786. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  4787. elif dim == 'tools_solderpaste_tools':
  4788. sptools = []
  4789. try:
  4790. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4791. sptools = [eval(a) for a in tools_string if a != '']
  4792. except Exception as e:
  4793. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4794. self.defaults['tools_solderpaste_tools'] = ""
  4795. for t in range(len(sptools)):
  4796. sptools[t] *= sfactor
  4797. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  4798. elif dim == 'tools_solderpaste_xy_toolchange':
  4799. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4800. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4801. sp_coords[0] *= sfactor
  4802. sp_coords[1] *= sfactor
  4803. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  4804. elif dim == 'global_gridx' or dim == 'global_gridy':
  4805. if new_units == 'IN':
  4806. val = 0.1
  4807. try:
  4808. val = float(self.defaults[dim]) * sfactor
  4809. except Exception as e:
  4810. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4811. self.defaults[dim] = float('%.6f' % val)
  4812. else:
  4813. val = 0.1
  4814. try:
  4815. val = float(self.defaults[dim]) * sfactor
  4816. except Exception as e:
  4817. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4818. self.defaults[dim] = float('%.4f' % val)
  4819. else:
  4820. val = 0.1
  4821. if self.defaults[dim]:
  4822. try:
  4823. val = float(self.defaults[dim]) * sfactor
  4824. except Exception as e:
  4825. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4826. self.defaults[dim] = val
  4827. # The scaling factor depending on choice of units.
  4828. factor = 1/25.4
  4829. if new_units == 'MM':
  4830. factor = 25.4
  4831. # Changing project units. Warn user.
  4832. msgbox = QtWidgets.QMessageBox()
  4833. msgbox.setWindowTitle(_("Toggle Units"))
  4834. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  4835. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4836. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  4837. "properties of all objects to be scaled accordingly.\nContinue?"))
  4838. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4839. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4840. msgbox.setDefaultButton(bt_ok)
  4841. msgbox.exec_()
  4842. response = msgbox.clickedButton()
  4843. if response == bt_ok:
  4844. if no_pref is False:
  4845. self.defaults_read_form()
  4846. scale_defaults(factor)
  4847. self.defaults_write_form(fl_units=new_units)
  4848. self.defaults["units"] = new_units
  4849. # save the defaults to file, some may assume that the conversion is enough and it's not
  4850. self.on_save_button(save_to_file=True)
  4851. self.should_we_save = True
  4852. # change this only if the workspace is active
  4853. if self.defaults['global_workspace'] is True:
  4854. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  4855. # adjust the grid values on the main toolbar
  4856. dec = 6 if new_units == 'IN'else 4
  4857. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  4858. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  4859. if not self.ui.grid_gap_link_cb.isChecked():
  4860. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  4861. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  4862. for obj in self.collection.get_list():
  4863. obj.convert_units(new_units)
  4864. # make that the properties stored in the object are also updated
  4865. self.object_changed.emit(obj)
  4866. obj.build_ui()
  4867. current = self.collection.get_active()
  4868. if current is not None:
  4869. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4870. if not isinstance(current, FlatCAMGeometry):
  4871. current.to_form()
  4872. self.plot_all()
  4873. self.inform.emit('[success] %s: %s' %
  4874. (_("Converted units to"), new_units))
  4875. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4876. self.set_screen_units(new_units)
  4877. else:
  4878. # Undo toggling
  4879. self.toggle_units_ignore = True
  4880. if self.defaults['units'].upper() == 'MM':
  4881. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4882. else:
  4883. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4884. self.toggle_units_ignore = False
  4885. self.inform.emit('[WARNING_NOTCL]%s' %
  4886. _(" Units conversion cancelled."))
  4887. self.defaults_read_form()
  4888. def on_toggle_units_click(self):
  4889. try:
  4890. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4891. except (TypeError, AttributeError):
  4892. pass
  4893. if self.defaults["units"] == 'MM':
  4894. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4895. else:
  4896. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4897. self.on_toggle_units(no_pref=True)
  4898. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4899. lambda: self.on_toggle_units(no_pref=False))
  4900. def on_fullscreen(self, disable=False):
  4901. self.report_usage("on_fullscreen()")
  4902. if self.toggle_fscreen is False and disable is False:
  4903. # self.ui.showFullScreen()
  4904. self.ui.setWindowFlags(self.ui.windowFlags() | Qt.FramelessWindowHint)
  4905. a = self.ui.geometry()
  4906. self.x_pos = a.x()
  4907. self.y_pos = a.y()
  4908. self.width = a.width()
  4909. self.height = a.height()
  4910. # set new geometry to full desktop rect
  4911. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  4912. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  4913. # everything else will not work without this hack. This happen in Windows.
  4914. # https://bugreports.qt.io/browse/QTBUG-41309
  4915. desktop = QtWidgets.QApplication.desktop()
  4916. screen = desktop.screenNumber(QtGui.QCursor.pos())
  4917. rec = desktop.screenGeometry(screen)
  4918. x = rec.x() - 1
  4919. y = rec.y() - 1
  4920. h = rec.height() + 2
  4921. w = rec.width() + 2
  4922. self.ui.setGeometry(x, y, w, h)
  4923. self.ui.show()
  4924. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4925. tb.setVisible(False)
  4926. self.ui.splitter_left.setVisible(False)
  4927. self.toggle_fscreen = True
  4928. elif self.toggle_fscreen is True or disable is True:
  4929. self.ui.setWindowFlags(self.ui.windowFlags() & ~Qt.FramelessWindowHint)
  4930. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  4931. self.ui.showNormal()
  4932. self.restore_toolbar_view()
  4933. self.ui.splitter_left.setVisible(True)
  4934. self.toggle_fscreen = False
  4935. def on_toggle_plotarea(self):
  4936. self.report_usage("on_toggle_plotarea()")
  4937. try:
  4938. name = self.ui.plot_tab_area.widget(0).objectName()
  4939. except AttributeError:
  4940. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4941. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4942. self.ui.plot_tab_area.protectTab(0)
  4943. return
  4944. if name != 'plotarea':
  4945. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4946. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4947. self.ui.plot_tab_area.protectTab(0)
  4948. else:
  4949. self.ui.plot_tab_area.closeTab(0)
  4950. def on_toggle_notebook(self):
  4951. if self.ui.splitter.sizes()[0] == 0:
  4952. self.ui.splitter.setSizes([1, 1])
  4953. self.ui.menu_toggle_nb.setChecked(True)
  4954. else:
  4955. self.ui.splitter.setSizes([0, 1])
  4956. self.ui.menu_toggle_nb.setChecked(False)
  4957. def on_toggle_axis(self):
  4958. self.report_usage("on_toggle_axis()")
  4959. if self.toggle_axis is False:
  4960. if self.is_legacy is False:
  4961. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  4962. parent=self.plotcanvas.view.scene)
  4963. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  4964. parent=self.plotcanvas.view.scene)
  4965. else:
  4966. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  4967. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  4968. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  4969. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  4970. self.plotcanvas.canvas.draw()
  4971. self.toggle_axis = True
  4972. else:
  4973. if self.is_legacy is False:
  4974. self.plotcanvas.v_line.parent = None
  4975. self.plotcanvas.h_line.parent = None
  4976. else:
  4977. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  4978. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  4979. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  4980. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  4981. self.plotcanvas.canvas.draw()
  4982. self.toggle_axis = False
  4983. def on_toggle_grid(self):
  4984. self.report_usage("on_toggle_grid()")
  4985. self.ui.grid_snap_btn.trigger()
  4986. def on_toggle_grid_lines(self):
  4987. self.report_usage("on_toggle_grd_lines()")
  4988. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  4989. if tt_settings.contains("theme"):
  4990. theme = tt_settings.value('theme', type=str)
  4991. else:
  4992. theme = 'white'
  4993. if self.toggle_grid_lines is False:
  4994. if self.is_legacy is False:
  4995. if theme == 'white':
  4996. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  4997. else:
  4998. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  4999. else:
  5000. self.plotcanvas.axes.grid(True)
  5001. try:
  5002. self.plotcanvas.canvas.draw()
  5003. except IndexError:
  5004. pass
  5005. pass
  5006. self.toggle_grid_lines = True
  5007. else:
  5008. if self.is_legacy is False:
  5009. if theme == 'white':
  5010. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  5011. else:
  5012. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  5013. else:
  5014. self.plotcanvas.axes.grid(False)
  5015. try:
  5016. self.plotcanvas.canvas.draw()
  5017. except IndexError:
  5018. pass
  5019. self.toggle_grid_lines = False
  5020. if self.is_legacy is False:
  5021. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  5022. # - perhaps is a bug in VisPy implementation
  5023. if self.grid_status() is True:
  5024. self.app_cursor.enabled = False
  5025. self.app_cursor.enabled = True
  5026. else:
  5027. self.app_cursor.enabled = True
  5028. self.app_cursor.enabled = False
  5029. def show_preferences_gui(self):
  5030. """
  5031. Called to initialize and show the Preferences GUI
  5032. :return: None
  5033. """
  5034. self.gen_form = self.ui.general_defaults_form
  5035. self.ger_form = self.ui.gerber_defaults_form
  5036. self.exc_form = self.ui.excellon_defaults_form
  5037. self.geo_form = self.ui.geometry_defaults_form
  5038. self.cnc_form = self.ui.cncjob_defaults_form
  5039. self.tools_form = self.ui.tools_defaults_form
  5040. self.tools2_form = self.ui.tools2_defaults_form
  5041. self.fa_form = self.ui.util_defaults_form
  5042. try:
  5043. self.ui.general_scroll_area.takeWidget()
  5044. except Exception:
  5045. self.log.debug("Nothing to remove")
  5046. self.ui.general_scroll_area.setWidget(self.gen_form)
  5047. self.gen_form.show()
  5048. try:
  5049. self.ui.gerber_scroll_area.takeWidget()
  5050. except Exception:
  5051. self.log.debug("Nothing to remove")
  5052. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  5053. self.ger_form.show()
  5054. try:
  5055. self.ui.excellon_scroll_area.takeWidget()
  5056. except Exception:
  5057. self.log.debug("Nothing to remove")
  5058. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  5059. self.exc_form.show()
  5060. try:
  5061. self.ui.geometry_scroll_area.takeWidget()
  5062. except Exception:
  5063. self.log.debug("Nothing to remove")
  5064. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  5065. self.geo_form.show()
  5066. try:
  5067. self.ui.cncjob_scroll_area.takeWidget()
  5068. except Exception:
  5069. self.log.debug("Nothing to remove")
  5070. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  5071. self.cnc_form.show()
  5072. try:
  5073. self.ui.tools_scroll_area.takeWidget()
  5074. except Exception:
  5075. self.log.debug("Nothing to remove")
  5076. self.ui.tools_scroll_area.setWidget(self.tools_form)
  5077. self.tools_form.show()
  5078. try:
  5079. self.ui.tools2_scroll_area.takeWidget()
  5080. except Exception:
  5081. self.log.debug("Nothing to remove")
  5082. self.ui.tools2_scroll_area.setWidget(self.tools2_form)
  5083. self.tools2_form.show()
  5084. try:
  5085. self.ui.fa_scroll_area.takeWidget()
  5086. except Exception:
  5087. self.log.debug("Nothing to remove")
  5088. self.ui.fa_scroll_area.setWidget(self.fa_form)
  5089. self.fa_form.show()
  5090. self.log.debug("Finished Preferences GUI form initialization.")
  5091. # self.options2form()
  5092. def init_color_pickers_in_preferences_gui(self):
  5093. # Init Plot Colors
  5094. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  5095. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5096. "background-color:%s;"
  5097. "border-color: dimgray" % str(self.defaults['global_plot_fill'])[:7])
  5098. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  5099. int(self.defaults['global_plot_fill'][7:9], 16))
  5100. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  5101. int(self.defaults['global_plot_fill'][7:9], 16))
  5102. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  5103. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5104. "background-color:%s;"
  5105. "border-color: dimgray" % str(self.defaults['global_plot_line'])[:7])
  5106. # Init Left-Right Selection colors
  5107. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  5108. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5109. "background-color:%s;"
  5110. "border-color: dimgray" % str(self.defaults['global_sel_fill'])[:7])
  5111. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  5112. int(self.defaults['global_sel_fill'][7:9], 16))
  5113. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  5114. int(self.defaults['global_sel_fill'][7:9], 16))
  5115. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  5116. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5117. "background-color:%s;"
  5118. "border-color: dimgray" % str(self.defaults['global_sel_line'])[:7])
  5119. # Init Right-Left Selection colors
  5120. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  5121. self.defaults['global_alt_sel_fill'])
  5122. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5123. "background-color:%s;"
  5124. "border-color: dimgray" % str(self.defaults['global_alt_sel_fill'])[:7])
  5125. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  5126. int(self.defaults['global_sel_fill'][7:9], 16))
  5127. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  5128. int(self.defaults['global_sel_fill'][7:9], 16))
  5129. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  5130. self.defaults['global_alt_sel_line'])
  5131. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5132. "background-color:%s;"
  5133. "border-color: dimgray" % str(self.defaults['global_alt_sel_line'])[:7])
  5134. # Init Draw color and Selection Draw Color
  5135. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  5136. self.defaults['global_draw_color'])
  5137. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5138. "background-color:%s;"
  5139. "border-color: dimgray" % str(self.defaults['global_draw_color'])[:7])
  5140. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  5141. self.defaults['global_sel_draw_color'])
  5142. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5143. "background-color:%s;"
  5144. "border-color: dimgray" % str(self.defaults['global_sel_draw_color'])[:7])
  5145. # Init Project Items color
  5146. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  5147. self.defaults['global_proj_item_color'])
  5148. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5149. "background-color:%s;"
  5150. "border-color: dimgray" % str(self.defaults['global_proj_item_color'])[:7])
  5151. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  5152. self.defaults['global_proj_item_dis_color'])
  5153. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5154. "background-color:%s;"
  5155. "border-color: dimgray" % str(self.defaults['global_proj_item_dis_color'])[:7])
  5156. # Init the Annotation CNC Job color
  5157. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  5158. self.defaults['cncjob_annotation_fontcolor'])
  5159. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5160. "background-color:%s;"
  5161. "border-color: dimgray" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  5162. # Init the Tool Film color
  5163. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  5164. self.defaults['tools_film_color'])
  5165. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5166. "background-color:%s;"
  5167. "border-color: dimgray" % str(self.defaults['tools_film_color'])[:7]
  5168. )
  5169. # Init the Tool QRCode colors
  5170. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(
  5171. self.defaults['tools_qrcode_fill_color'])
  5172. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5173. "background-color:%s;"
  5174. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])[:7])
  5175. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(
  5176. self.defaults['tools_qrcode_back_color'])
  5177. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5178. "background-color:%s;"
  5179. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])[:7])
  5180. def on_excellon_defaults_button(self):
  5181. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  5182. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  5183. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  5184. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  5185. self.defaults_form_fields["excellon_zeros"].set_value('L')
  5186. self.defaults_form_fields["excellon_units"].set_value('INCH')
  5187. log.debug("Excellon app defaults loaded ...")
  5188. def on_update_exc_export(self, state):
  5189. """
  5190. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  5191. if the update_excellon_cb checkbox is checked
  5192. :param state: state of the checkbox whose signals is tied to his slot
  5193. :return:
  5194. """
  5195. if state:
  5196. # first try to disconnect
  5197. try:
  5198. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.\
  5199. disconnect(self.on_excellon_format_changed)
  5200. except TypeError:
  5201. pass
  5202. try:
  5203. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.\
  5204. disconnect(self.on_excellon_format_changed)
  5205. except TypeError:
  5206. pass
  5207. try:
  5208. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.\
  5209. disconnect(self.on_excellon_format_changed)
  5210. except TypeError:
  5211. pass
  5212. try:
  5213. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.\
  5214. disconnect(self.on_excellon_format_changed)
  5215. except TypeError:
  5216. pass
  5217. try:
  5218. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  5219. disconnect(self.on_excellon_zeros_changed)
  5220. except TypeError:
  5221. pass
  5222. try:
  5223. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  5224. disconnect(self.on_excellon_zeros_changed)
  5225. except TypeError:
  5226. pass
  5227. # the connect them
  5228. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  5229. self.on_excellon_format_changed)
  5230. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  5231. self.on_excellon_format_changed)
  5232. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  5233. self.on_excellon_format_changed)
  5234. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  5235. self.on_excellon_format_changed)
  5236. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  5237. self.on_excellon_zeros_changed)
  5238. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  5239. self.on_excellon_units_changed)
  5240. else:
  5241. # disconnect the signals
  5242. try:
  5243. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  5244. disconnect(self.on_excellon_format_changed)
  5245. except TypeError:
  5246. pass
  5247. try:
  5248. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  5249. disconnect(self.on_excellon_format_changed)
  5250. except TypeError:
  5251. pass
  5252. try:
  5253. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  5254. disconnect(self.on_excellon_format_changed)
  5255. except TypeError:
  5256. pass
  5257. try:
  5258. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  5259. disconnect(self.on_excellon_format_changed)
  5260. except TypeError:
  5261. pass
  5262. try:
  5263. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  5264. disconnect(self.on_excellon_zeros_changed)
  5265. except TypeError:
  5266. pass
  5267. try:
  5268. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  5269. disconnect(self.on_excellon_zeros_changed)
  5270. except TypeError:
  5271. pass
  5272. def on_excellon_format_changed(self):
  5273. """
  5274. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  5275. :return: None
  5276. """
  5277. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  5278. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5279. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  5280. )
  5281. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5282. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  5283. )
  5284. else:
  5285. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5286. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  5287. )
  5288. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5289. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  5290. )
  5291. def on_excellon_zeros_changed(self):
  5292. """
  5293. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  5294. :return: None
  5295. """
  5296. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  5297. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  5298. )
  5299. def on_excellon_units_changed(self):
  5300. """
  5301. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  5302. :return: None
  5303. """
  5304. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  5305. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  5306. )
  5307. self.on_excellon_format_changed()
  5308. # Setting plot colors handlers
  5309. def on_pf_color_entry(self):
  5310. self.defaults['global_plot_fill'] = \
  5311. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  5312. self.defaults['global_plot_fill'][7:9]
  5313. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5314. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  5315. def on_pf_color_button(self):
  5316. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  5317. c_dialog = QtWidgets.QColorDialog()
  5318. plot_fill_color = c_dialog.getColor(initial=current_color)
  5319. if plot_fill_color.isValid() is False:
  5320. return
  5321. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5322. "background-color:%s" % str(plot_fill_color.name()))
  5323. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  5324. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  5325. self.defaults['global_plot_fill'] = new_val
  5326. def on_pf_color_spinner(self):
  5327. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  5328. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  5329. self.defaults['global_plot_fill'] = \
  5330. self.defaults['global_plot_fill'][:7] + \
  5331. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5332. self.defaults['global_plot_line'] = \
  5333. self.defaults['global_plot_line'][:7] + \
  5334. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5335. def on_pf_color_slider(self):
  5336. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  5337. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  5338. def on_pl_color_entry(self):
  5339. self.defaults['global_plot_line'] = \
  5340. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  5341. self.defaults['global_plot_line'][7:9]
  5342. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5343. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  5344. def on_pl_color_button(self):
  5345. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  5346. # print(current_color)
  5347. c_dialog = QtWidgets.QColorDialog()
  5348. plot_line_color = c_dialog.getColor(initial=current_color)
  5349. if plot_line_color.isValid() is False:
  5350. return
  5351. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5352. "background-color:%s" % str(plot_line_color.name()))
  5353. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  5354. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  5355. self.defaults['global_plot_line'] = new_val_line
  5356. # Setting selection colors (left - right) handlers
  5357. def on_sf_color_entry(self):
  5358. self.defaults['global_sel_fill'] = \
  5359. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  5360. self.defaults['global_sel_fill'][7:9]
  5361. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5362. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  5363. def on_sf_color_button(self):
  5364. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  5365. c_dialog = QtWidgets.QColorDialog()
  5366. plot_fill_color = c_dialog.getColor(initial=current_color)
  5367. if plot_fill_color.isValid() is False:
  5368. return
  5369. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5370. "background-color:%s" % str(plot_fill_color.name()))
  5371. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  5372. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  5373. self.defaults['global_sel_fill'] = new_val
  5374. def on_sf_color_spinner(self):
  5375. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  5376. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  5377. self.defaults['global_sel_fill'] = \
  5378. self.defaults['global_sel_fill'][:7] + \
  5379. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5380. self.defaults['global_sel_line'] = \
  5381. self.defaults['global_sel_line'][:7] + \
  5382. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5383. def on_sf_color_slider(self):
  5384. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  5385. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  5386. def on_sl_color_entry(self):
  5387. self.defaults['global_sel_line'] = \
  5388. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  5389. self.defaults['global_sel_line'][7:9]
  5390. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5391. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  5392. def on_sl_color_button(self):
  5393. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  5394. c_dialog = QtWidgets.QColorDialog()
  5395. plot_line_color = c_dialog.getColor(initial=current_color)
  5396. if plot_line_color.isValid() is False:
  5397. return
  5398. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5399. "background-color:%s" % str(plot_line_color.name()))
  5400. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  5401. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  5402. self.defaults['global_sel_line'] = new_val_line
  5403. # Setting selection colors (right - left) handlers
  5404. def on_alt_sf_color_entry(self):
  5405. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  5406. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  5407. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5408. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  5409. def on_alt_sf_color_button(self):
  5410. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  5411. c_dialog = QtWidgets.QColorDialog()
  5412. plot_fill_color = c_dialog.getColor(initial=current_color)
  5413. if plot_fill_color.isValid() is False:
  5414. return
  5415. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5416. "background-color:%s" % str(plot_fill_color.name()))
  5417. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  5418. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  5419. self.defaults['global_alt_sel_fill'] = new_val
  5420. def on_alt_sf_color_spinner(self):
  5421. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  5422. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  5423. self.defaults['global_alt_sel_fill'] = \
  5424. self.defaults['global_alt_sel_fill'][:7] + \
  5425. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5426. self.defaults['global_alt_sel_line'] = \
  5427. self.defaults['global_alt_sel_line'][:7] + \
  5428. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5429. def on_alt_sf_color_slider(self):
  5430. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  5431. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  5432. def on_alt_sl_color_entry(self):
  5433. self.defaults['global_alt_sel_line'] = \
  5434. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  5435. self.defaults['global_alt_sel_line'][7:9]
  5436. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5437. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  5438. def on_alt_sl_color_button(self):
  5439. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  5440. c_dialog = QtWidgets.QColorDialog()
  5441. plot_line_color = c_dialog.getColor(initial=current_color)
  5442. if plot_line_color.isValid() is False:
  5443. return
  5444. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5445. "background-color:%s" % str(plot_line_color.name()))
  5446. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  5447. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  5448. self.defaults['global_alt_sel_line'] = new_val_line
  5449. # Setting Editor colors
  5450. def on_draw_color_entry(self):
  5451. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5452. .draw_color_entry.get_value()
  5453. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5454. "background-color:%s" % str(self.defaults['global_draw_color']))
  5455. def on_draw_color_button(self):
  5456. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  5457. c_dialog = QtWidgets.QColorDialog()
  5458. draw_color = c_dialog.getColor(initial=current_color)
  5459. if draw_color.isValid() is False:
  5460. return
  5461. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5462. "background-color:%s" % str(draw_color.name()))
  5463. new_val = str(draw_color.name())
  5464. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  5465. self.defaults['global_draw_color'] = new_val
  5466. def on_sel_draw_color_entry(self):
  5467. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5468. .sel_draw_color_entry.get_value()
  5469. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5470. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  5471. def on_sel_draw_color_button(self):
  5472. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  5473. c_dialog = QtWidgets.QColorDialog()
  5474. sel_draw_color = c_dialog.getColor(initial=current_color)
  5475. if sel_draw_color.isValid() is False:
  5476. return
  5477. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5478. "background-color:%s" % str(sel_draw_color.name()))
  5479. new_val_sel = str(sel_draw_color.name())
  5480. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  5481. self.defaults['global_sel_draw_color'] = new_val_sel
  5482. def on_proj_color_entry(self):
  5483. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  5484. .proj_color_entry.get_value()
  5485. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5486. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  5487. def on_proj_color_button(self):
  5488. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  5489. c_dialog = QtWidgets.QColorDialog()
  5490. proj_color = c_dialog.getColor(initial=current_color)
  5491. if proj_color.isValid() is False:
  5492. return
  5493. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5494. "background-color:%s" % str(proj_color.name()))
  5495. new_val_sel = str(proj_color.name())
  5496. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  5497. self.defaults['global_proj_item_color'] = new_val_sel
  5498. def on_proj_color_dis_entry(self):
  5499. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  5500. .proj_color_dis_entry.get_value()
  5501. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5502. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  5503. def on_proj_color_dis_button(self):
  5504. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  5505. c_dialog = QtWidgets.QColorDialog()
  5506. proj_color = c_dialog.getColor(initial=current_color)
  5507. if proj_color.isValid() is False:
  5508. return
  5509. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5510. "background-color:%s" % str(proj_color.name()))
  5511. new_val_sel = str(proj_color.name())
  5512. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  5513. self.defaults['global_proj_item_dis_color'] = new_val_sel
  5514. def on_annotation_fontcolor_entry(self):
  5515. self.defaults['cncjob_annotation_fontcolor'] = \
  5516. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.get_value()
  5517. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5518. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  5519. def on_annotation_fontcolor_button(self):
  5520. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  5521. c_dialog = QtWidgets.QColorDialog()
  5522. annotation_color = c_dialog.getColor(initial=current_color)
  5523. if annotation_color.isValid() is False:
  5524. return
  5525. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5526. "background-color:%s" % str(annotation_color.name()))
  5527. new_val_sel = str(annotation_color.name())
  5528. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(new_val_sel)
  5529. self.defaults['cncjob_annotation_fontcolor'] = new_val_sel
  5530. def on_film_color_entry(self):
  5531. self.defaults['tools_film_color'] = \
  5532. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  5533. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5534. "background-color:%s;"
  5535. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  5536. )
  5537. def on_film_color_button(self):
  5538. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  5539. c_dialog = QtWidgets.QColorDialog()
  5540. film_color = c_dialog.getColor(initial=current_color)
  5541. if film_color.isValid() is False:
  5542. return
  5543. # if new color is different then mark that the Preferences are changed
  5544. if film_color != current_color:
  5545. self.on_preferences_edited()
  5546. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5547. "background-color:%s;"
  5548. "border-color: dimgray" % str(film_color.name())
  5549. )
  5550. new_val_sel = str(film_color.name())
  5551. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  5552. self.defaults['tools_film_color'] = new_val_sel
  5553. def on_qrcode_fill_color_entry(self):
  5554. self.defaults['tools_qrcode_fill_color'] = \
  5555. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  5556. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5557. "background-color:%s;"
  5558. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  5559. )
  5560. def on_qrcode_fill_color_button(self):
  5561. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  5562. c_dialog = QtWidgets.QColorDialog()
  5563. fill_color = c_dialog.getColor(initial=current_color)
  5564. if fill_color.isValid() is False:
  5565. return
  5566. # if new color is different then mark that the Preferences are changed
  5567. if fill_color != current_color:
  5568. self.on_preferences_edited()
  5569. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5570. "background-color:%s;"
  5571. "border-color: dimgray" % str(fill_color.name())
  5572. )
  5573. new_val_sel = str(fill_color.name())
  5574. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  5575. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  5576. def on_qrcode_back_color_entry(self):
  5577. self.defaults['tools_qrcode_back_color'] = \
  5578. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  5579. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5580. "background-color:%s;"
  5581. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  5582. )
  5583. def on_qrcode_back_color_button(self):
  5584. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  5585. c_dialog = QtWidgets.QColorDialog()
  5586. back_color = c_dialog.getColor(initial=current_color)
  5587. if back_color.isValid() is False:
  5588. return
  5589. # if new color is different then mark that the Preferences are changed
  5590. if back_color != current_color:
  5591. self.on_preferences_edited()
  5592. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5593. "background-color:%s;"
  5594. "border-color: dimgray" % str(back_color.name())
  5595. )
  5596. new_val_sel = str(back_color.name())
  5597. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  5598. self.defaults['tools_qrcode_back_color'] = new_val_sel
  5599. def on_splash_changed(self, state):
  5600. settings = QSettings("Open Source", "FlatCAM")
  5601. settings.setValue('splash_screen', 1) if state else settings.setValue('splash_screen', 0)
  5602. # This will write the setting to the platform specific storage.
  5603. del settings
  5604. def on_tab_rmb_click(self, checked):
  5605. self.ui.notebook.set_detachable(val=checked)
  5606. self.defaults["global_tabs_detachable"] = checked
  5607. self.ui.plot_tab_area.set_detachable(val=checked)
  5608. self.defaults["global_tabs_detachable"] = checked
  5609. def on_tab_setup_context_menu(self):
  5610. initial_checked = self.defaults["global_tabs_detachable"]
  5611. action_name = str(_("Detachable Tabs"))
  5612. action = QtWidgets.QAction(self)
  5613. action.setCheckable(True)
  5614. action.setText(action_name)
  5615. action.setChecked(initial_checked)
  5616. self.ui.notebook.tabBar.addAction(action)
  5617. self.ui.plot_tab_area.tabBar.addAction(action)
  5618. try:
  5619. action.triggered.disconnect()
  5620. except TypeError:
  5621. pass
  5622. action.triggered.connect(self.on_tab_rmb_click)
  5623. def on_deselect_all(self):
  5624. self.collection.set_all_inactive()
  5625. self.delete_selection_shape()
  5626. def on_workspace_modified(self):
  5627. # self.save_defaults(silent=True)
  5628. if self.is_legacy is True:
  5629. self.plotcanvas.delete_workspace()
  5630. self.defaults_read_form()
  5631. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  5632. def on_workspace(self):
  5633. if self.ui.general_defaults_form.general_gui_group.workspace_cb.get_value():
  5634. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  5635. else:
  5636. self.plotcanvas.delete_workspace()
  5637. self.defaults_read_form()
  5638. # self.save_defaults(silent=True)
  5639. def on_workspace_toggle(self):
  5640. state = False if self.ui.general_defaults_form.general_gui_group.workspace_cb.get_value() else True
  5641. try:
  5642. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  5643. except TypeError:
  5644. pass
  5645. self.ui.general_defaults_form.general_gui_group.workspace_cb.set_value(state)
  5646. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  5647. self.on_workspace()
  5648. def on_layout(self, index=None, lay=None):
  5649. """
  5650. Set the toolbars layout (location)
  5651. :param index:
  5652. :param lay: type of layout to be set on the toolbard
  5653. :return: None
  5654. """
  5655. self.report_usage("on_layout()")
  5656. if lay:
  5657. current_layout = lay
  5658. else:
  5659. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  5660. lay_settings = QSettings("Open Source", "FlatCAM")
  5661. lay_settings.setValue('layout', current_layout)
  5662. # This will write the setting to the platform specific storage.
  5663. del lay_settings
  5664. # first remove the toolbars:
  5665. try:
  5666. self.ui.removeToolBar(self.ui.toolbarfile)
  5667. self.ui.removeToolBar(self.ui.toolbargeo)
  5668. self.ui.removeToolBar(self.ui.toolbarview)
  5669. self.ui.removeToolBar(self.ui.toolbarshell)
  5670. self.ui.removeToolBar(self.ui.toolbartools)
  5671. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  5672. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  5673. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  5674. self.ui.removeToolBar(self.ui.snap_toolbar)
  5675. self.ui.removeToolBar(self.ui.toolbarshell)
  5676. except Exception:
  5677. pass
  5678. if current_layout == 'standard':
  5679. # ## TOOLBAR INSTALLATION # ##
  5680. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5681. self.ui.toolbarfile.setObjectName('File_TB')
  5682. self.ui.addToolBar(self.ui.toolbarfile)
  5683. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5684. self.ui.toolbargeo.setObjectName('Edit_TB')
  5685. self.ui.addToolBar(self.ui.toolbargeo)
  5686. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5687. self.ui.toolbarview.setObjectName('View_TB')
  5688. self.ui.addToolBar(self.ui.toolbarview)
  5689. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5690. self.ui.toolbarshell.setObjectName('Shell_TB')
  5691. self.ui.addToolBar(self.ui.toolbarshell)
  5692. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5693. self.ui.toolbartools.setObjectName('Tools_TB')
  5694. self.ui.addToolBar(self.ui.toolbartools)
  5695. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5696. # self.ui.exc_edit_toolbar.setVisible(False)
  5697. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5698. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  5699. self.ui.addToolBarBreak()
  5700. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5701. # self.ui.geo_edit_toolbar.setVisible(False)
  5702. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5703. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  5704. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5705. # self.ui.grb_edit_toolbar.setVisible(False)
  5706. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5707. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  5708. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5709. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5710. # self.ui.snap_toolbar.setMaximumHeight(30)
  5711. self.ui.addToolBar(self.ui.snap_toolbar)
  5712. self.ui.corner_snap_btn.setVisible(False)
  5713. self.ui.snap_magnet.setVisible(False)
  5714. elif current_layout == 'compact':
  5715. # ## TOOLBAR INSTALLATION # ##
  5716. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5717. self.ui.toolbarfile.setObjectName('File_TB')
  5718. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  5719. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5720. self.ui.toolbargeo.setObjectName('Edit_TB')
  5721. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  5722. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5723. self.ui.toolbarshell.setObjectName('Shell_TB')
  5724. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  5725. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5726. self.ui.toolbartools.setObjectName('Tools_TB')
  5727. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  5728. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5729. # self.ui.geo_edit_toolbar.setVisible(False)
  5730. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5731. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  5732. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5733. self.ui.toolbarview.setObjectName('View_TB')
  5734. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  5735. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  5736. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5737. # self.ui.grb_edit_toolbar.setVisible(False)
  5738. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5739. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  5740. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5741. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5742. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  5743. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5744. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5745. self.ui.snap_toolbar.setMaximumHeight(30)
  5746. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  5747. self.ui.corner_snap_btn.setVisible(True)
  5748. self.ui.snap_magnet.setVisible(True)
  5749. # add all the actions to the toolbars
  5750. self.ui.populate_toolbars()
  5751. # reconnect all the signals to the toolbar actions
  5752. self.connect_toolbar_signals()
  5753. self.ui.grid_snap_btn.setChecked(True)
  5754. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  5755. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  5756. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  5757. self.ui.grid_gap_link_cb.setChecked(True)
  5758. def on_cursor_type(self, val):
  5759. """
  5760. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  5761. :return: None
  5762. """
  5763. self.app_cursor.enabled = False
  5764. if val == 'small':
  5765. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(False)
  5766. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(False)
  5767. self.app_cursor = self.plotcanvas.new_cursor()
  5768. else:
  5769. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(True)
  5770. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(True)
  5771. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  5772. if self.ui.grid_snap_btn.isChecked():
  5773. self.app_cursor.enabled = True
  5774. else:
  5775. self.app_cursor.enabled = False
  5776. def on_cnc_custom_parameters(self, signal_text):
  5777. if signal_text == 'Parameters':
  5778. return
  5779. else:
  5780. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  5781. def on_save_button(self, save_to_file=True):
  5782. log.debug("App.on_save_button() --> Applying preferences to file.")
  5783. # Preferences saved, update flag
  5784. self.preferences_changed_flag = False
  5785. # Preferences save, update the color of the Preferences Tab text
  5786. for idx in range(self.ui.plot_tab_area.count()):
  5787. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5788. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  5789. self.inform.emit('%s' % _("Preferences applied."))
  5790. if save_to_file:
  5791. self.save_defaults(silent=False)
  5792. # load the defaults so they are updated into the app
  5793. self.load_defaults(filename='current_defaults')
  5794. # Re-fresh project options
  5795. self.on_options_app2project()
  5796. settgs = QSettings("Open Source", "FlatCAM")
  5797. # save the notebook font size
  5798. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  5799. settgs.setValue('notebook_font_size', fsize)
  5800. # save the axis font size
  5801. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  5802. settgs.setValue('axis_font_size', g_fsize)
  5803. # save the textbox font size
  5804. tb_fsize = self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  5805. settgs.setValue('textbox_font_size', tb_fsize)
  5806. settgs.setValue(
  5807. 'machinist',
  5808. 1 if self.ui.general_defaults_form.general_app_group.machinist_cb.get_value() else 0
  5809. )
  5810. # This will write the setting to the platform specific storage.
  5811. del settgs
  5812. def on_pref_close_button(self):
  5813. # Preferences saved, update flag
  5814. self.preferences_changed_flag = False
  5815. try:
  5816. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_plot_area_tab_closed)
  5817. except TypeError:
  5818. pass
  5819. self.defaults_write_form()
  5820. # Preferences save, update the color of the Preferences Tab text
  5821. for idx in range(self.ui.plot_tab_area.count()):
  5822. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5823. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  5824. self.ui.plot_tab_area.closeTab(idx)
  5825. break
  5826. self.inform.emit('%s' % _("Preferences closed without saving."))
  5827. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  5828. def on_tool_add_keypress(self):
  5829. # ## Current application units in Upper Case
  5830. self.units = self.defaults['units'].upper()
  5831. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5832. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5833. if notebook_widget_name == 'selected_tab':
  5834. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5835. # Tool add works for Geometry only if Advanced is True in Preferences
  5836. if self.defaults["global_app_level"] == 'a':
  5837. tool_add_popup = FCInputDialog(title="New Tool ...",
  5838. text='Enter a Tool Diameter:',
  5839. min=0.0000, max=99.9999, decimals=4)
  5840. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5841. val, ok = tool_add_popup.get_value()
  5842. if ok:
  5843. if float(val) == 0:
  5844. self.inform.emit('[WARNING_NOTCL] %s' %
  5845. _("Please enter a tool diameter with non-zero value, in Float format."))
  5846. return
  5847. self.collection.get_active().on_tool_add(dia=float(val))
  5848. else:
  5849. self.inform.emit('[WARNING_NOTCL] %s...' %
  5850. _("Adding Tool cancelled"))
  5851. else:
  5852. msgbox = QtWidgets.QMessageBox()
  5853. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5854. "Go to Preferences -> General - Show Advanced Options."))
  5855. msgbox.setWindowTitle("Tool adding ...")
  5856. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  5857. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5858. msgbox.setDefaultButton(bt_ok)
  5859. msgbox.exec_()
  5860. # work only if the notebook tab on focus is the Tools_Tab
  5861. if notebook_widget_name == 'tool_tab':
  5862. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5863. # and only if the tool is NCC Tool
  5864. if tool_widget == self.ncclear_tool.toolName:
  5865. self.ncclear_tool.on_add_tool_by_key()
  5866. # and only if the tool is Paint Area Tool
  5867. elif tool_widget == self.paint_tool.toolName:
  5868. self.paint_tool.on_add_tool_by_key()
  5869. # and only if the tool is Solder Paste Dispensing Tool
  5870. elif tool_widget == self.paste_tool.toolName:
  5871. self.paste_tool.on_add_tool_by_key()
  5872. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5873. # See description bellow.
  5874. def on_delete_keypress(self):
  5875. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5876. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5877. if notebook_widget_name == 'selected_tab':
  5878. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5879. self.collection.get_active().on_tool_delete()
  5880. # work only if the notebook tab on focus is the Tools_Tab
  5881. elif notebook_widget_name == 'tool_tab':
  5882. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5883. # and only if the tool is NCC Tool
  5884. if tool_widget == self.ncclear_tool.toolName:
  5885. self.ncclear_tool.on_tool_delete()
  5886. # and only if the tool is Paint Tool
  5887. elif tool_widget == self.paint_tool.toolName:
  5888. self.paint_tool.on_tool_delete()
  5889. # and only if the tool is Solder Paste Dispensing Tool
  5890. elif tool_widget == self.paste_tool.toolName:
  5891. self.paste_tool.on_tool_delete()
  5892. else:
  5893. self.on_delete()
  5894. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5895. # some screens you have to be careful where you hover with your mouse.
  5896. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5897. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5898. # Complicated, I know :)
  5899. def on_delete(self):
  5900. """
  5901. Delete the currently selected FlatCAMObjs.
  5902. :return: None
  5903. """
  5904. self.report_usage("on_delete()")
  5905. response = None
  5906. bt_ok = None
  5907. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5908. # a geometry object before we update it.
  5909. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5910. and self.grb_editor.editor_active is False:
  5911. if self.defaults["global_delete_confirmation"] is True:
  5912. msgbox = QtWidgets.QMessageBox()
  5913. msgbox.setWindowTitle(_("Delete objects"))
  5914. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  5915. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5916. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5917. "the selected objects?"))
  5918. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5919. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5920. msgbox.setDefaultButton(bt_ok)
  5921. msgbox.exec_()
  5922. response = msgbox.clickedButton()
  5923. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  5924. if self.collection.get_active():
  5925. self.log.debug("App.on_delete()")
  5926. while self.collection.get_active():
  5927. obj_active = self.collection.get_active()
  5928. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  5929. if isinstance(obj_active, FlatCAMGerber):
  5930. for el in obj_active.mark_shapes:
  5931. obj_active.mark_shapes[el].clear(update=True)
  5932. obj_active.mark_shapes[el].enabled = False
  5933. # obj_active.mark_shapes[el] = None
  5934. del el
  5935. elif isinstance(obj_active, FlatCAMCNCjob):
  5936. try:
  5937. obj_active.annotation.clear(update=True)
  5938. obj_active.annotation.enabled = False
  5939. except AttributeError:
  5940. pass
  5941. self.delete_first_selected()
  5942. self.inform.emit('%s...' %
  5943. _("Object(s) deleted"))
  5944. # make sure that the selection shape is deleted, too
  5945. self.delete_selection_shape()
  5946. else:
  5947. self.inform.emit(_("Failed. No object(s) selected..."))
  5948. else:
  5949. self.inform.emit(_("Save the work in Editor and try again ..."))
  5950. def delete_first_selected(self):
  5951. # Keep this for later
  5952. try:
  5953. sel_obj = self.collection.get_active()
  5954. name = sel_obj.options["name"]
  5955. isPlotted = sel_obj.options["plot"]
  5956. except AttributeError:
  5957. self.log.debug("Nothing selected for deletion")
  5958. return
  5959. if self.is_legacy is True:
  5960. # Remove plot only if the object was plotted otherwise delaxes will fail
  5961. if isPlotted:
  5962. try:
  5963. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  5964. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  5965. except Exception as e:
  5966. log.debug("App.delete_first_selected() --> %s" % str(e))
  5967. self.plotcanvas.auto_adjust_axes()
  5968. # Remove from dictionary
  5969. self.collection.delete_active()
  5970. # Clear form
  5971. self.setup_component_editor()
  5972. self.inform.emit('%s: %s' %
  5973. (_("Object deleted"), name))
  5974. def on_set_origin(self):
  5975. """
  5976. Set the origin to the left mouse click position
  5977. :return: None
  5978. """
  5979. # display the message for the user
  5980. # and ask him to click on the desired position
  5981. self.report_usage("on_set_origin()")
  5982. def origin_replot():
  5983. def worker_task():
  5984. with self.proc_container.new('%s...' % _("Plotting")):
  5985. for obj in self.collection.get_list():
  5986. obj.plot()
  5987. self.plotcanvas.fit_view()
  5988. if self.is_legacy:
  5989. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  5990. else:
  5991. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  5992. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5993. self.inform.emit(_('Click to set the origin ...'))
  5994. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  5995. # first disconnect it as it may have been used by something else
  5996. try:
  5997. self.replot_signal.disconnect()
  5998. except TypeError:
  5999. pass
  6000. self.replot_signal[list].connect(origin_replot)
  6001. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  6002. """
  6003. :param event:
  6004. :param location:
  6005. :param noplot:
  6006. :param use_thread:
  6007. :return:
  6008. """
  6009. noplot_sig = noplot
  6010. def worker_task():
  6011. with self.proc_container.new(_("Setting Origin...")):
  6012. for obj in self.collection.get_list():
  6013. obj.offset((x, y))
  6014. self.object_changed.emit(obj)
  6015. # Update the object bounding box options
  6016. a, b, c, d = obj.bounds()
  6017. obj.options['xmin'] = a
  6018. obj.options['ymin'] = b
  6019. obj.options['xmax'] = c
  6020. obj.options['ymax'] = d
  6021. self.inform.emit('[success] %s...' %
  6022. _('Origin set'))
  6023. if noplot_sig is False:
  6024. self.replot_signal.emit([])
  6025. if location is not None:
  6026. if len(location) != 2:
  6027. self.inform.emit('[ERROR_NOTCL] %s...' %
  6028. _("Origin coordinates specified but incomplete."))
  6029. return 'fail'
  6030. x, y = location
  6031. if use_thread is True:
  6032. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6033. else:
  6034. worker_task()
  6035. self.should_we_save = True
  6036. return
  6037. if event.button == 1:
  6038. if self.is_legacy is False:
  6039. event_pos = event.pos
  6040. else:
  6041. event_pos = (event.xdata, event.ydata)
  6042. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6043. if self.grid_status() == True:
  6044. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6045. else:
  6046. pos = pos_canvas
  6047. x = 0 - pos[0]
  6048. y = 0 - pos[1]
  6049. if use_thread is True:
  6050. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6051. else:
  6052. worker_task()
  6053. self.should_we_save = True
  6054. def on_jump_to(self, custom_location=None, fit_center=True):
  6055. """
  6056. Jump to a location by setting the mouse cursor location
  6057. :return:
  6058. """
  6059. self.report_usage("on_jump_to()")
  6060. # if self.is_legacy is True:
  6061. # self.inform.emit(_("Not available with the current Graphic Engine Legacy(2D)."))
  6062. # return
  6063. if not custom_location:
  6064. dia_box_location = None
  6065. try:
  6066. dia_box_location = eval(self.clipboard.text())
  6067. except Exception:
  6068. pass
  6069. if type(dia_box_location) == tuple:
  6070. dia_box_location = str(dia_box_location)
  6071. else:
  6072. dia_box_location = None
  6073. dia_box = Dialog_box(title=_("Jump to ..."),
  6074. label=_("Enter the coordinates in format X,Y:"),
  6075. icon=QtGui.QIcon('share/jump_to16.png'),
  6076. initial_text=dia_box_location)
  6077. if dia_box.ok is True:
  6078. try:
  6079. location = eval(dia_box.location)
  6080. if not isinstance(location, tuple):
  6081. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  6082. return
  6083. except Exception:
  6084. return
  6085. else:
  6086. return
  6087. else:
  6088. location = custom_location
  6089. if fit_center:
  6090. self.plotcanvas.fit_center(loc=location)
  6091. cursor = QtGui.QCursor()
  6092. if self.is_legacy is False:
  6093. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6094. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  6095. j_pos = (canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  6096. cursor.setPos(j_pos[0], j_pos[1])
  6097. else:
  6098. # find the canvas origin which is in the top left corner
  6099. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6100. # determine the coordinates for the lowest left point of the canvas
  6101. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  6102. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  6103. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  6104. # canvas) and the point (width, height) is in the top-right location
  6105. loc = self.plotcanvas.axes.transData.transform_point(location)
  6106. j_pos = (x0 + loc[0], y0 - loc[1])
  6107. cursor.setPos(j_pos[0], j_pos[1])
  6108. if self.grid_status() == True:
  6109. # Update cursor
  6110. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  6111. symbol='++', edge_color=self.cursor_color_3D,
  6112. size=self.defaults["global_cursor_size"])
  6113. # Set the position label
  6114. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6115. "<b>Y</b>: %.4f" % (location[0], location[1]))
  6116. # Set the relative position label
  6117. dx = location[0] - float(self.rel_point1[0])
  6118. dy = location[1] - float(self.rel_point1[1])
  6119. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6120. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6121. self.inform.emit('[success] %s' %
  6122. _("Done."))
  6123. return location
  6124. def on_copy_object(self):
  6125. self.report_usage("on_copy_object()")
  6126. def initialize(obj_init, app):
  6127. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6128. try:
  6129. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  6130. except AttributeError:
  6131. pass
  6132. try:
  6133. obj_init.apertures = deepcopy(obj.apertures)
  6134. except AttributeError:
  6135. pass
  6136. try:
  6137. if obj.tools:
  6138. obj_init.tools = deepcopy(obj.tools)
  6139. except Exception as e:
  6140. log.debug("App.on_copy_object() --> %s" % str(e))
  6141. try:
  6142. obj_init.source_file = deepcopy(obj.source_file)
  6143. except (AttributeError, TypeError):
  6144. pass
  6145. def initialize_excellon(obj_init, app):
  6146. obj_init.source_file = deepcopy(obj.source_file)
  6147. obj_init.tools = deepcopy(obj.tools)
  6148. # drills are offset, so they need to be deep copied
  6149. obj_init.drills = deepcopy(obj.drills)
  6150. # slots are offset, so they need to be deep copied
  6151. obj_init.slots = deepcopy(obj.slots)
  6152. obj_init.create_geometry()
  6153. def initialize_script(obj_init, app_obj):
  6154. obj_init.source_file = deepcopy(obj.source_file)
  6155. def initialize_document(obj_init, app_obj):
  6156. obj_init.source_file = deepcopy(obj.source_file)
  6157. for obj in self.collection.get_selected():
  6158. obj_name = obj.options["name"]
  6159. try:
  6160. if isinstance(obj, FlatCAMExcellon):
  6161. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  6162. elif isinstance(obj, FlatCAMGerber):
  6163. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  6164. elif isinstance(obj, FlatCAMGeometry):
  6165. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  6166. elif isinstance(obj, FlatCAMScript):
  6167. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  6168. elif isinstance(obj, FlatCAMDocument):
  6169. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  6170. except Exception as e:
  6171. return "Operation failed: %s" % str(e)
  6172. def on_copy_object2(self, custom_name):
  6173. def initialize_geometry(obj_init, app):
  6174. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6175. try:
  6176. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  6177. except AttributeError:
  6178. pass
  6179. try:
  6180. obj_init.apertures = deepcopy(obj.apertures)
  6181. except AttributeError:
  6182. pass
  6183. try:
  6184. if obj.tools:
  6185. obj_init.tools = deepcopy(obj.tools)
  6186. except Exception as ee:
  6187. log.debug("on_copy_object2() --> %s" % str(ee))
  6188. def initialize_gerber(obj_init, app):
  6189. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6190. obj_init.apertures = deepcopy(obj.apertures)
  6191. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  6192. def initialize_excellon(obj_init, app):
  6193. obj_init.tools = deepcopy(obj.tools)
  6194. # drills are offset, so they need to be deep copied
  6195. obj_init.drills = deepcopy(obj.drills)
  6196. # slots are offset, so they need to be deep copied
  6197. obj_init.slots = deepcopy(obj.slots)
  6198. obj_init.create_geometry()
  6199. for obj in self.collection.get_selected():
  6200. obj_name = obj.options["name"]
  6201. try:
  6202. if isinstance(obj, FlatCAMExcellon):
  6203. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  6204. elif isinstance(obj, FlatCAMGerber):
  6205. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  6206. elif isinstance(obj, FlatCAMGeometry):
  6207. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  6208. except Exception as e:
  6209. return "Operation failed: %s" % str(e)
  6210. def on_rename_object(self, text):
  6211. self.report_usage("on_rename_object()")
  6212. named_obj = self.collection.get_active()
  6213. for obj in named_obj:
  6214. if obj is list:
  6215. self.on_rename_object(text)
  6216. else:
  6217. try:
  6218. obj.options['name'] = text
  6219. except Exception as e:
  6220. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  6221. def convert_any2geo(self):
  6222. self.report_usage("convert_any2geo()")
  6223. def initialize(obj_init, app):
  6224. obj_init.solid_geometry = obj.solid_geometry
  6225. try:
  6226. obj_init.follow_geometry = obj.follow_geometry
  6227. except AttributeError:
  6228. pass
  6229. try:
  6230. obj_init.apertures = obj.apertures
  6231. except AttributeError:
  6232. pass
  6233. try:
  6234. if obj.tools:
  6235. obj_init.tools = obj.tools
  6236. except AttributeError:
  6237. pass
  6238. def initialize_excellon(obj_init, app):
  6239. # objs = self.collection.get_selected()
  6240. # FlatCAMGeometry.merge(objs, obj)
  6241. solid_geo = []
  6242. for tool in obj.tools:
  6243. for geo in obj.tools[tool]['solid_geometry']:
  6244. solid_geo.append(geo)
  6245. obj_init.solid_geometry = deepcopy(solid_geo)
  6246. if not self.collection.get_selected():
  6247. log.warning("App.convert_any2geo --> No object selected")
  6248. self.inform.emit('[WARNING_NOTCL] %s' %
  6249. _("No object is selected. Select an object and try again."))
  6250. return
  6251. for obj in self.collection.get_selected():
  6252. obj_name = obj.options["name"]
  6253. try:
  6254. if isinstance(obj, FlatCAMExcellon):
  6255. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  6256. else:
  6257. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  6258. except Exception as e:
  6259. return "Operation failed: %s" % str(e)
  6260. def convert_any2gerber(self):
  6261. self.report_usage("convert_any2gerber()")
  6262. def initialize_geometry(obj_init, app):
  6263. apertures = {}
  6264. apid = 0
  6265. apertures[str(apid)] = {}
  6266. apertures[str(apid)]['geometry'] = []
  6267. for obj_orig in obj.solid_geometry:
  6268. new_elem = dict()
  6269. new_elem['solid'] = obj_orig
  6270. try:
  6271. new_elem['follow'] = obj_orig.exterior
  6272. except AttributeError:
  6273. pass
  6274. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  6275. apertures[str(apid)]['size'] = 0.0
  6276. apertures[str(apid)]['type'] = 'C'
  6277. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6278. obj_init.apertures = deepcopy(apertures)
  6279. def initialize_excellon(obj_init, app):
  6280. apertures = {}
  6281. apid = 10
  6282. for tool in obj.tools:
  6283. apertures[str(apid)] = {}
  6284. apertures[str(apid)]['geometry'] = []
  6285. for geo in obj.tools[tool]['solid_geometry']:
  6286. new_el = dict()
  6287. new_el['solid'] = geo
  6288. new_el['follow'] = geo.exterior
  6289. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  6290. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  6291. apertures[str(apid)]['type'] = 'C'
  6292. apid += 1
  6293. # create solid_geometry
  6294. solid_geometry = []
  6295. for apid in apertures:
  6296. for geo_el in apertures[apid]['geometry']:
  6297. solid_geometry.append(geo_el['solid'])
  6298. solid_geometry = MultiPolygon(solid_geometry)
  6299. solid_geometry = solid_geometry.buffer(0.0000001)
  6300. obj_init.solid_geometry = deepcopy(solid_geometry)
  6301. obj_init.apertures = deepcopy(apertures)
  6302. # clear the working objects (perhaps not necessary due of Python GC)
  6303. apertures.clear()
  6304. if not self.collection.get_selected():
  6305. log.warning("App.convert_any2gerber --> No object selected")
  6306. self.inform.emit('[WARNING_NOTCL] %s' %
  6307. _("No object is selected. Select an object and try again."))
  6308. return
  6309. for obj in self.collection.get_selected():
  6310. obj_name = obj.options["name"]
  6311. try:
  6312. if isinstance(obj, FlatCAMExcellon):
  6313. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  6314. elif isinstance(obj, FlatCAMGeometry):
  6315. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  6316. else:
  6317. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  6318. except Exception as e:
  6319. return "Operation failed: %s" % str(e)
  6320. def abort_all_tasks(self):
  6321. if self.abort_flag is False:
  6322. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  6323. self.abort_flag = True
  6324. def app_is_idle(self):
  6325. if self.abort_flag:
  6326. self.inform.emit('[WARNING_NOTCL] %s' %
  6327. _("The current task was gracefully closed on user request..."))
  6328. self.abort_flag = False
  6329. def on_selectall(self):
  6330. self.report_usage("on_selectall()")
  6331. # delete the possible selection box around a possible selected object
  6332. self.delete_selection_shape()
  6333. for name in self.collection.get_names():
  6334. self.collection.set_active(name)
  6335. curr_sel_obj = self.collection.get_by_name(name)
  6336. # create the selection box around the selected object
  6337. if self.defaults['global_selection_shape'] is True:
  6338. self.draw_selection_shape(curr_sel_obj)
  6339. def on_preferences(self):
  6340. """
  6341. Adds the Preferences in a Tab in Plot Area
  6342. :return:
  6343. """
  6344. # add the tab if it was closed
  6345. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  6346. # delete the absolute and relative position and messages in the infobar
  6347. self.ui.position_label.setText("")
  6348. self.ui.rel_position_label.setText("")
  6349. # Switch plot_area to preferences page
  6350. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  6351. # self.ui.show()
  6352. # detect changes in the preferences
  6353. for idx in range(self.ui.pref_tab_area.count()):
  6354. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6355. try:
  6356. try:
  6357. tb.textEdited.disconnect(self.on_preferences_edited)
  6358. except (TypeError, AttributeError):
  6359. pass
  6360. tb.textEdited.connect(self.on_preferences_edited)
  6361. except AttributeError:
  6362. pass
  6363. try:
  6364. try:
  6365. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6366. except (TypeError, AttributeError):
  6367. pass
  6368. tb.modificationChanged.connect(self.on_preferences_edited)
  6369. except AttributeError:
  6370. pass
  6371. try:
  6372. try:
  6373. tb.toggled.disconnect(self.on_preferences_edited)
  6374. except (TypeError, AttributeError):
  6375. pass
  6376. tb.toggled.connect(self.on_preferences_edited)
  6377. except AttributeError:
  6378. pass
  6379. try:
  6380. try:
  6381. tb.valueChanged.disconnect(self.on_preferences_edited)
  6382. except (TypeError, AttributeError):
  6383. pass
  6384. tb.valueChanged.connect(self.on_preferences_edited)
  6385. except AttributeError:
  6386. pass
  6387. try:
  6388. try:
  6389. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6390. except (TypeError, AttributeError):
  6391. pass
  6392. tb.currentIndexChanged.connect(self.on_preferences_edited)
  6393. except AttributeError:
  6394. pass
  6395. def on_preferences_edited(self):
  6396. self.inform.emit('[WARNING_NOTCL] %s' %
  6397. _("Preferences edited but not saved."))
  6398. for idx in range(self.ui.plot_tab_area.count()):
  6399. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  6400. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  6401. self.preferences_changed_flag = True
  6402. def on_tools_database(self):
  6403. """
  6404. Adds the Tools Database in a Tab in Plot Area
  6405. :return:
  6406. """
  6407. for idx in range(self.ui.plot_tab_area.count()):
  6408. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6409. # there can be only one instance of Tools Database at one time
  6410. return
  6411. self.tools_db_tab = ToolsDB(
  6412. app=self,
  6413. parent=self.ui,
  6414. callback_on_edited=self.on_tools_db_edited,
  6415. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  6416. )
  6417. # add the tab if it was closed
  6418. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  6419. self.tools_db_tab.setObjectName("database_tab")
  6420. # delete the absolute and relative position and messages in the infobar
  6421. self.ui.position_label.setText("")
  6422. self.ui.rel_position_label.setText("")
  6423. # Switch plot_area to preferences page
  6424. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  6425. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  6426. self.tools_db_tab.ui_connect()
  6427. def on_tools_db_edited(self):
  6428. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  6429. for idx in range(self.ui.plot_tab_area.count()):
  6430. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6431. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  6432. self.tools_db_changed_flag = True
  6433. def on_geometry_tool_add_from_db_executed(self, tool):
  6434. """
  6435. Here add the tool from DB in the selected geometry object
  6436. :return:
  6437. """
  6438. tool_from_db = deepcopy(tool)
  6439. obj = self.collection.get_active()
  6440. if isinstance(obj, FlatCAMGeometry):
  6441. obj.on_tool_from_db_inserted(tool=tool_from_db)
  6442. for idx in range(self.ui.plot_tab_area.count()):
  6443. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6444. wdg = self.ui.plot_tab_area.widget(idx)
  6445. wdg.deleteLater()
  6446. self.ui.plot_tab_area.removeTab(idx)
  6447. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  6448. else:
  6449. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  6450. def on_plot_area_tab_closed(self, title):
  6451. if title == _("Preferences"):
  6452. # disconnect
  6453. for idx in range(self.ui.pref_tab_area.count()):
  6454. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6455. try:
  6456. tb.textEdited.disconnect(self.on_preferences_edited)
  6457. except (TypeError, AttributeError):
  6458. pass
  6459. try:
  6460. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6461. except (TypeError, AttributeError):
  6462. pass
  6463. try:
  6464. tb.toggled.disconnect(self.on_preferences_edited)
  6465. except (TypeError, AttributeError):
  6466. pass
  6467. try:
  6468. tb.valueChanged.disconnect(self.on_preferences_edited)
  6469. except (TypeError, AttributeError):
  6470. pass
  6471. try:
  6472. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6473. except (TypeError, AttributeError):
  6474. pass
  6475. if self.preferences_changed_flag is True:
  6476. msgbox = QtWidgets.QMessageBox()
  6477. msgbox.setText(_("One or more values are changed.\n"
  6478. "Do you want to save the Preferences?"))
  6479. msgbox.setWindowTitle(_("Save Preferences"))
  6480. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6481. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6482. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6483. msgbox.setDefaultButton(bt_yes)
  6484. msgbox.exec_()
  6485. response = msgbox.clickedButton()
  6486. if response == bt_yes:
  6487. self.on_save_button(save_to_file=True)
  6488. self.inform.emit('[success] %s' % _("Preferences saved."))
  6489. else:
  6490. self.preferences_changed_flag = False
  6491. self.inform.emit('')
  6492. return
  6493. if title == _("Tools Database"):
  6494. # disconnect the signals from the table widget in tab
  6495. self.tools_db_tab.ui_disconnect()
  6496. if self.tools_db_changed_flag is True:
  6497. msgbox = QtWidgets.QMessageBox()
  6498. msgbox.setText(_("One or more Tools are edited.\n"
  6499. "Do you want to update the Tools Database?"))
  6500. msgbox.setWindowTitle(_("Save Tools Database"))
  6501. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6502. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6503. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6504. msgbox.setDefaultButton(bt_yes)
  6505. msgbox.exec_()
  6506. response = msgbox.clickedButton()
  6507. if response == bt_yes:
  6508. self.tools_db_tab.on_save_tools_db()
  6509. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  6510. else:
  6511. self.tools_db_changed_flag = False
  6512. self.inform.emit('')
  6513. return
  6514. self.tools_db_tab.deleteLater()
  6515. if title == _("Code Editor"):
  6516. self.toggle_codeeditor = False
  6517. if title == _("Bookmarks Manager"):
  6518. self.book_dialog_tab.rebuild_actions()
  6519. self.book_dialog_tab.deleteLater()
  6520. def on_flipy(self):
  6521. self.report_usage("on_flipy()")
  6522. obj_list = self.collection.get_selected()
  6523. xminlist = []
  6524. yminlist = []
  6525. xmaxlist = []
  6526. ymaxlist = []
  6527. if not obj_list:
  6528. self.inform.emit('[WARNING_NOTCL] %s' %
  6529. _("No object selected to Flip on Y axis."))
  6530. else:
  6531. try:
  6532. # first get a bounding box to fit all
  6533. for obj in obj_list:
  6534. xmin, ymin, xmax, ymax = obj.bounds()
  6535. xminlist.append(xmin)
  6536. yminlist.append(ymin)
  6537. xmaxlist.append(xmax)
  6538. ymaxlist.append(ymax)
  6539. # get the minimum x,y and maximum x,y for all objects selected
  6540. xminimal = min(xminlist)
  6541. yminimal = min(yminlist)
  6542. xmaximal = max(xmaxlist)
  6543. ymaximal = max(ymaxlist)
  6544. px = 0.5 * (xminimal + xmaximal)
  6545. py = 0.5 * (yminimal + ymaximal)
  6546. # execute mirroring
  6547. for obj in obj_list:
  6548. obj.mirror('X', [px, py])
  6549. obj.plot()
  6550. self.object_changed.emit(obj)
  6551. self.inform.emit('[success] %s' %
  6552. _("Flip on Y axis done."))
  6553. except Exception as e:
  6554. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  6555. return
  6556. def on_flipx(self):
  6557. self.report_usage("on_flipx()")
  6558. obj_list = self.collection.get_selected()
  6559. xminlist = []
  6560. yminlist = []
  6561. xmaxlist = []
  6562. ymaxlist = []
  6563. if not obj_list:
  6564. self.inform.emit('[WARNING_NOTCL] %s' %
  6565. _("No object selected to Flip on X axis."))
  6566. else:
  6567. try:
  6568. # first get a bounding box to fit all
  6569. for obj in obj_list:
  6570. xmin, ymin, xmax, ymax = obj.bounds()
  6571. xminlist.append(xmin)
  6572. yminlist.append(ymin)
  6573. xmaxlist.append(xmax)
  6574. ymaxlist.append(ymax)
  6575. # get the minimum x,y and maximum x,y for all objects selected
  6576. xminimal = min(xminlist)
  6577. yminimal = min(yminlist)
  6578. xmaximal = max(xmaxlist)
  6579. ymaximal = max(ymaxlist)
  6580. px = 0.5 * (xminimal + xmaximal)
  6581. py = 0.5 * (yminimal + ymaximal)
  6582. # execute mirroring
  6583. for obj in obj_list:
  6584. obj.mirror('Y', [px, py])
  6585. obj.plot()
  6586. self.object_changed.emit(obj)
  6587. self.inform.emit('[success] %s' %
  6588. _("Flip on X axis done."))
  6589. except Exception as e:
  6590. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  6591. return
  6592. def on_rotate(self, silent=False, preset=None):
  6593. self.report_usage("on_rotate()")
  6594. obj_list = self.collection.get_selected()
  6595. xminlist = []
  6596. yminlist = []
  6597. xmaxlist = []
  6598. ymaxlist = []
  6599. if not obj_list:
  6600. self.inform.emit('[WARNING_NOTCL] %s' %
  6601. _("No object selected to Rotate."))
  6602. else:
  6603. if silent is False:
  6604. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6605. min=-360, max=360, decimals=4,
  6606. init_val=float(self.defaults['tools_transform_rotate']))
  6607. num, ok = rotatebox.get_value()
  6608. else:
  6609. num = preset
  6610. ok = True
  6611. if ok:
  6612. try:
  6613. # first get a bounding box to fit all
  6614. for obj in obj_list:
  6615. xmin, ymin, xmax, ymax = obj.bounds()
  6616. xminlist.append(xmin)
  6617. yminlist.append(ymin)
  6618. xmaxlist.append(xmax)
  6619. ymaxlist.append(ymax)
  6620. # get the minimum x,y and maximum x,y for all objects selected
  6621. xminimal = min(xminlist)
  6622. yminimal = min(yminlist)
  6623. xmaximal = max(xmaxlist)
  6624. ymaximal = max(ymaxlist)
  6625. px = 0.5 * (xminimal + xmaximal)
  6626. py = 0.5 * (yminimal + ymaximal)
  6627. for sel_obj in obj_list:
  6628. sel_obj.rotate(-float(num), point=(px, py))
  6629. sel_obj.plot()
  6630. self.object_changed.emit(sel_obj)
  6631. self.inform.emit('[success] %s' %
  6632. _("Rotation done."))
  6633. except Exception as e:
  6634. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  6635. return
  6636. def on_skewx(self):
  6637. self.report_usage("on_skewx()")
  6638. obj_list = self.collection.get_selected()
  6639. xminlist = []
  6640. yminlist = []
  6641. if not obj_list:
  6642. self.inform.emit('[WARNING_NOTCL] %s' %
  6643. _("No object selected to Skew/Shear on X axis."))
  6644. else:
  6645. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6646. min=-360, max=360, decimals=4,
  6647. init_val=float(self.defaults['tools_transform_skew_x']))
  6648. num, ok = skewxbox.get_value()
  6649. if ok:
  6650. # first get a bounding box to fit all
  6651. for obj in obj_list:
  6652. xmin, ymin, xmax, ymax = obj.bounds()
  6653. xminlist.append(xmin)
  6654. yminlist.append(ymin)
  6655. # get the minimum x,y and maximum x,y for all objects selected
  6656. xminimal = min(xminlist)
  6657. yminimal = min(yminlist)
  6658. for obj in obj_list:
  6659. obj.skew(num, 0, point=(xminimal, yminimal))
  6660. obj.plot()
  6661. self.object_changed.emit(obj)
  6662. self.inform.emit('[success] %s' %
  6663. _("Skew on X axis done."))
  6664. def on_skewy(self):
  6665. self.report_usage("on_skewy()")
  6666. obj_list = self.collection.get_selected()
  6667. xminlist = []
  6668. yminlist = []
  6669. if not obj_list:
  6670. self.inform.emit('[WARNING_NOTCL] %s' %
  6671. _("No object selected to Skew/Shear on Y axis."))
  6672. else:
  6673. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6674. min=-360, max=360, decimals=4,
  6675. init_val=float(self.defaults['tools_transform_skew_y']))
  6676. num, ok = skewybox.get_value()
  6677. if ok:
  6678. # first get a bounding box to fit all
  6679. for obj in obj_list:
  6680. xmin, ymin, xmax, ymax = obj.bounds()
  6681. xminlist.append(xmin)
  6682. yminlist.append(ymin)
  6683. # get the minimum x,y and maximum x,y for all objects selected
  6684. xminimal = min(xminlist)
  6685. yminimal = min(yminlist)
  6686. for obj in obj_list:
  6687. obj.skew(0, num, point=(xminimal, yminimal))
  6688. obj.plot()
  6689. self.object_changed.emit(obj)
  6690. self.inform.emit('[success] %s' %
  6691. _("Skew on Y axis done."))
  6692. def on_plots_updated(self):
  6693. """
  6694. Callback used to report when the plots have changed.
  6695. Adjust axes and zooms to fit.
  6696. :return: None
  6697. """
  6698. if self.is_legacy is False:
  6699. self.plotcanvas.update() # TODO: Need update canvas?
  6700. else:
  6701. self.plotcanvas.auto_adjust_axes()
  6702. self.on_zoom_fit(None)
  6703. self.collection.update_view()
  6704. # self.inform.emit(_("Plots updated ..."))
  6705. # TODO: Rework toolbar 'clear', 'replot' functions
  6706. def on_toolbar_replot(self):
  6707. """
  6708. Callback for toolbar button. Re-plots all objects.
  6709. :return: None
  6710. """
  6711. self.report_usage("on_toolbar_replot")
  6712. self.log.debug("on_toolbar_replot()")
  6713. try:
  6714. self.collection.get_active().read_form()
  6715. except AttributeError:
  6716. self.log.debug("on_toolbar_replot(): AttributeError")
  6717. pass
  6718. self.plot_all()
  6719. def on_row_activated(self, index):
  6720. if index.isValid():
  6721. if index.internalPointer().parent_item != self.collection.root_item:
  6722. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6723. self.collection.on_item_activated(index)
  6724. def on_row_selected(self, obj_name):
  6725. # this is a special string; when received it will make all entries unchecked
  6726. # it mean we clicked outside of the items and deselected all
  6727. if obj_name == 'none':
  6728. for act in self.ui.menuobjects.actions():
  6729. act.setChecked(False)
  6730. return
  6731. # get the name of the selected objects and add them to a list
  6732. name_list = list()
  6733. for obj in self.collection.get_selected():
  6734. name_list.append(obj.options['name'])
  6735. # set all actions as unchecked but the ones selected make them checked
  6736. for act in self.ui.menuobjects.actions():
  6737. act.setChecked(False)
  6738. if act.text() in name_list:
  6739. act.setChecked(True)
  6740. def on_collection_updated(self, obj, state, old_name):
  6741. """
  6742. Create a menu from the object loaded in the collection.
  6743. TODO: should use the collection model to do this
  6744. :param obj: object that was changd (added, deleted, renamed)
  6745. :param state: what was done with the objectCand be: added, deleted, delete_all, renamed
  6746. :param old_name: the old name of the object before the action that triggered this slot happened
  6747. :return: None
  6748. """
  6749. icon_files = {
  6750. "gerber": "share/flatcam_icon16.png",
  6751. "excellon": "share/drill16.png",
  6752. "cncjob": "share/cnc16.png",
  6753. "geometry": "share/geometry16.png",
  6754. "script": "share/script_new16.png",
  6755. "document": "share/notes16_1.png"
  6756. }
  6757. if state == 'append':
  6758. for act in self.ui.menuobjects.actions():
  6759. try:
  6760. act.triggered.disconnect()
  6761. except TypeError:
  6762. pass
  6763. self.ui.menuobjects.clear()
  6764. gerber_list = list()
  6765. exc_list = list()
  6766. cncjob_list = list()
  6767. geo_list = list()
  6768. script_list = list()
  6769. doc_list = list()
  6770. for name in self.collection.get_names():
  6771. obj_named = self.collection.get_by_name(name)
  6772. if obj_named.kind == 'gerber':
  6773. gerber_list.append(name)
  6774. elif obj_named.kind == 'excellon':
  6775. exc_list.append(name)
  6776. elif obj_named.kind == 'cncjob':
  6777. cncjob_list.append(name)
  6778. elif obj_named.kind == 'geometry':
  6779. geo_list.append(name)
  6780. elif obj_named.kind == 'script':
  6781. script_list.append(name)
  6782. elif obj_named.kind == 'document':
  6783. doc_list.append(name)
  6784. def add_act(o_name):
  6785. obj_for_icon = self.collection.get_by_name(o_name)
  6786. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6787. add_action.setCheckable(True)
  6788. add_action.setText(o_name)
  6789. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  6790. add_action.triggered.connect(
  6791. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  6792. self.collection.set_inactive(o_name))
  6793. self.ui.menuobjects.addAction(add_action)
  6794. for name in gerber_list:
  6795. add_act(name)
  6796. self.ui.menuobjects.addSeparator()
  6797. for name in exc_list:
  6798. add_act(name)
  6799. self.ui.menuobjects.addSeparator()
  6800. for name in cncjob_list:
  6801. add_act(name)
  6802. self.ui.menuobjects.addSeparator()
  6803. for name in geo_list:
  6804. add_act(name)
  6805. self.ui.menuobjects.addSeparator()
  6806. for name in script_list:
  6807. add_act(name)
  6808. self.ui.menuobjects.addSeparator()
  6809. for name in doc_list:
  6810. add_act(name)
  6811. self.ui.menuobjects.addSeparator()
  6812. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  6813. QtGui.QIcon('share/select_all.png'),
  6814. _('Select All')
  6815. )
  6816. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  6817. QtGui.QIcon('share/deselect_all32.png'),
  6818. _('Deselect All')
  6819. )
  6820. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  6821. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  6822. elif state == 'delete':
  6823. for act in self.ui.menuobjects.actions():
  6824. if act.text() == obj.options['name']:
  6825. try:
  6826. act.triggered.disconnect()
  6827. except TypeError:
  6828. pass
  6829. self.ui.menuobjects.removeAction(act)
  6830. break
  6831. elif state == 'rename':
  6832. for act in self.ui.menuobjects.actions():
  6833. if act.text() == old_name:
  6834. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6835. add_action.setText(obj.options['name'])
  6836. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  6837. add_action.triggered.connect(
  6838. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  6839. self.collection.set_inactive(obj.options['name']))
  6840. self.ui.menuobjects.insertAction(act, add_action)
  6841. try:
  6842. act.triggered.disconnect()
  6843. except TypeError:
  6844. pass
  6845. self.ui.menuobjects.removeAction(act)
  6846. break
  6847. elif state == 'delete_all':
  6848. for act in self.ui.menuobjects.actions():
  6849. try:
  6850. act.triggered.disconnect()
  6851. except TypeError:
  6852. pass
  6853. self.ui.menuobjects.clear()
  6854. self.ui.menuobjects.addSeparator()
  6855. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  6856. QtGui.QIcon('share/select_all.png'),
  6857. _('Select All')
  6858. )
  6859. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  6860. QtGui.QIcon('share/deselect_all32.png'),
  6861. _('Deselect All')
  6862. )
  6863. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  6864. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  6865. def on_objects_selection(self, on_off):
  6866. obj_list = self.collection.get_names()
  6867. if on_off is True:
  6868. self.collection.set_all_active()
  6869. for act in self.ui.menuobjects.actions():
  6870. try:
  6871. act.setChecked(True)
  6872. except Exception:
  6873. pass
  6874. if obj_list:
  6875. self.inform.emit('[selected] %s' % _("All objects are selected."))
  6876. else:
  6877. self.collection.set_all_inactive()
  6878. for act in self.ui.menuobjects.actions():
  6879. try:
  6880. act.setChecked(False)
  6881. except Exception:
  6882. pass
  6883. if obj_list:
  6884. self.inform.emit('%s' % _("Objects selection is cleared."))
  6885. else:
  6886. self.inform.emit('')
  6887. def grid_status(self):
  6888. if self.ui.grid_snap_btn.isChecked():
  6889. return True
  6890. else:
  6891. return False
  6892. def populate_cmenu_grids(self):
  6893. units = self.defaults['units'].lower()
  6894. self.ui.cmenu_gridmenu.clear()
  6895. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  6896. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  6897. grid_toggle.setCheckable(True)
  6898. if self.grid_status() == True:
  6899. grid_toggle.setChecked(True)
  6900. else:
  6901. grid_toggle.setChecked(False)
  6902. self.ui.cmenu_gridmenu.addSeparator()
  6903. for grid in sorted_list:
  6904. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  6905. action.triggered.connect(self.set_grid)
  6906. self.ui.cmenu_gridmenu.addSeparator()
  6907. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  6908. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  6909. grid_add.triggered.connect(self.on_grid_add)
  6910. grid_delete.triggered.connect(self.on_grid_delete)
  6911. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  6912. def set_grid(self):
  6913. self.ui.grid_gap_x_entry.setText(self.sender().text())
  6914. self.ui.grid_gap_y_entry.setText(self.sender().text())
  6915. def on_grid_add(self):
  6916. # ## Current application units in lower Case
  6917. units = self.defaults['units'].lower()
  6918. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  6919. text=_('Enter a Grid Value:'),
  6920. min=0.0000, max=99.9999, decimals=4)
  6921. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  6922. val, ok = grid_add_popup.get_value()
  6923. if ok:
  6924. if float(val) == 0:
  6925. self.inform.emit('[WARNING_NOTCL] %s' %
  6926. _("Please enter a grid value with non-zero value, in Float format."))
  6927. return
  6928. else:
  6929. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  6930. self.defaults["global_grid_context_menu"][str(units)].append(val)
  6931. self.inform.emit('[success] %s...' %
  6932. _("New Grid added"))
  6933. else:
  6934. self.inform.emit('[WARNING_NOTCL] %s...' %
  6935. _("Grid already exists"))
  6936. else:
  6937. self.inform.emit('[WARNING_NOTCL] %s...' %
  6938. _("Adding New Grid cancelled"))
  6939. def on_grid_delete(self):
  6940. # ## Current application units in lower Case
  6941. units = self.defaults['units'].lower()
  6942. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  6943. text='Enter a Grid Value:',
  6944. min=0.0000, max=99.9999, decimals=4)
  6945. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  6946. val, ok = grid_del_popup.get_value()
  6947. if ok:
  6948. if float(val) == 0:
  6949. self.inform.emit('[WARNING_NOTCL] %s' %
  6950. _("Please enter a grid value with non-zero value, in Float format."))
  6951. return
  6952. else:
  6953. try:
  6954. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  6955. except ValueError:
  6956. self.inform.emit('[ERROR_NOTCL]%s...' %
  6957. _(" Grid Value does not exist"))
  6958. return
  6959. self.inform.emit('[success] %s...' %
  6960. _("Grid Value deleted"))
  6961. else:
  6962. self.inform.emit('[WARNING_NOTCL] %s...' %
  6963. _("Delete Grid value cancelled"))
  6964. def on_shortcut_list(self):
  6965. self.report_usage("on_shortcut_list()")
  6966. # add the tab if it was closed
  6967. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  6968. # delete the absolute and relative position and messages in the infobar
  6969. self.ui.position_label.setText("")
  6970. self.ui.rel_position_label.setText("")
  6971. # Switch plot_area to preferences page
  6972. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  6973. # self.ui.show()
  6974. def on_select_tab(self, name):
  6975. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  6976. if self.ui.splitter.sizes()[0] == 0:
  6977. self.ui.splitter.setSizes([1, 1])
  6978. else:
  6979. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  6980. self.ui.splitter.setSizes([0, 1])
  6981. if name == 'project':
  6982. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6983. elif name == 'selected':
  6984. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6985. elif name == 'tool':
  6986. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  6987. def on_copy_name(self):
  6988. self.report_usage("on_copy_name()")
  6989. obj = self.collection.get_active()
  6990. try:
  6991. name = obj.options["name"]
  6992. except AttributeError:
  6993. log.debug("on_copy_name() --> No object selected to copy it's name")
  6994. self.inform.emit('[WARNING_NOTCL]%s' %
  6995. _(" No object selected to copy it's name"))
  6996. return
  6997. self.clipboard.setText(name)
  6998. self.inform.emit(_("Name copied on clipboard ..."))
  6999. def on_mouse_click_over_plot(self, event):
  7000. """
  7001. Default actions are:
  7002. :param event: Contains information about the event, like which button
  7003. was clicked, the pixel coordinates and the axes coordinates.
  7004. :return: None
  7005. """
  7006. self.pos = []
  7007. if self.is_legacy is False:
  7008. event_pos = event.pos
  7009. if self.defaults["global_pan_button"] == '2':
  7010. pan_button = 2
  7011. else:
  7012. pan_button = 3
  7013. # Set the mouse button for panning
  7014. self.plotcanvas.view.camera.pan_button_setting = pan_button
  7015. else:
  7016. event_pos = (event.xdata, event.ydata)
  7017. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7018. if self.defaults["global_pan_button"] == '2':
  7019. pan_button = 3
  7020. else:
  7021. pan_button = 2
  7022. # So it can receive key presses
  7023. self.plotcanvas.native.setFocus()
  7024. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7025. if self.grid_status() == True:
  7026. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  7027. else:
  7028. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  7029. try:
  7030. if event.button == 1:
  7031. # Reset here the relative coordinates so there is a new reference on the click position
  7032. if self.rel_point1 is None:
  7033. self.rel_point1 = self.pos
  7034. else:
  7035. self.rel_point2 = copy(self.rel_point1)
  7036. self.rel_point1 = self.pos
  7037. self.on_mouse_move_over_plot(event, origin_click=True)
  7038. except Exception as e:
  7039. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  7040. def on_mouse_double_click_over_plot(self, event):
  7041. if event.button == 1:
  7042. self.doubleclick = True
  7043. def on_mouse_move_over_plot(self, event, origin_click=None):
  7044. """
  7045. Callback for the mouse motion event over the plot.
  7046. :param event: Contains information about the event.
  7047. :param origin_click
  7048. :return: None
  7049. """
  7050. if self.is_legacy is False:
  7051. event_pos = event.pos
  7052. if self.defaults["global_pan_button"] == '2':
  7053. pan_button = 2
  7054. else:
  7055. pan_button = 3
  7056. self.event_is_dragging = event.is_dragging
  7057. else:
  7058. event_pos = (event.xdata, event.ydata)
  7059. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7060. if self.defaults["global_pan_button"] == '2':
  7061. pan_button = 3
  7062. else:
  7063. pan_button = 2
  7064. self.event_is_dragging = self.plotcanvas.is_dragging
  7065. # So it can receive key presses
  7066. self.plotcanvas.native.setFocus()
  7067. self.pos_jump = event_pos
  7068. self.ui.popMenu.mouse_is_panning = False
  7069. if not origin_click:
  7070. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  7071. if event.button == pan_button and self.event_is_dragging == 1:
  7072. self.ui.popMenu.mouse_is_panning = True
  7073. return
  7074. if self.rel_point1 is not None:
  7075. try: # May fail in case mouse not within axes
  7076. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7077. if self.grid_status() == True:
  7078. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  7079. # Update cursor
  7080. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  7081. symbol='++', edge_color=self.cursor_color_3D,
  7082. size=self.defaults["global_cursor_size"])
  7083. else:
  7084. pos = (pos_canvas[0], pos_canvas[1])
  7085. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  7086. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  7087. dx = pos[0] - float(self.rel_point1[0])
  7088. dy = pos[1] - float(self.rel_point1[1])
  7089. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  7090. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  7091. self.mouse = [pos[0], pos[1]]
  7092. # if the mouse is moved and the LMB is clicked then the action is a selection
  7093. if self.event_is_dragging == 1 and event.button == 1:
  7094. self.delete_selection_shape()
  7095. if dx < 0:
  7096. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  7097. face_color=self.defaults['global_alt_sel_fill'])
  7098. self.selection_type = False
  7099. elif dx > 0:
  7100. self.draw_moving_selection_shape(self.pos, pos)
  7101. self.selection_type = True
  7102. else:
  7103. self.selection_type = None
  7104. # hover effect - enabled in Preferences -> General -> GUI Settings
  7105. if self.defaults['global_hover']:
  7106. for obj in self.collection.get_list():
  7107. try:
  7108. # select the object(s) only if it is enabled (plotted)
  7109. if obj.options['plot']:
  7110. if obj not in self.collection.get_selected():
  7111. poly_obj = Polygon(
  7112. [(obj.options['xmin'], obj.options['ymin']),
  7113. (obj.options['xmax'], obj.options['ymin']),
  7114. (obj.options['xmax'], obj.options['ymax']),
  7115. (obj.options['xmin'], obj.options['ymax'])]
  7116. )
  7117. if Point(pos).within(poly_obj):
  7118. if obj.isHovering is False:
  7119. obj.isHovering = True
  7120. obj.notHovering = True
  7121. # create the selection box around the selected object
  7122. self.draw_hover_shape(obj, color='#d1e0e0FF')
  7123. else:
  7124. if obj.notHovering is True:
  7125. obj.notHovering = False
  7126. obj.isHovering = False
  7127. self.delete_hover_shape()
  7128. except Exception:
  7129. # the Exception here will happen if we try to select on screen and we have an
  7130. # newly (and empty) just created Geometry or Excellon object that do not have the
  7131. # xmin, xmax, ymin, ymax options.
  7132. # In this case poly_obj creation (see above) will fail
  7133. pass
  7134. except Exception:
  7135. self.ui.position_label.setText("")
  7136. self.ui.rel_position_label.setText("")
  7137. self.mouse = None
  7138. def on_mouse_click_release_over_plot(self, event):
  7139. """
  7140. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  7141. and has been registered in ''self.__init__()''.
  7142. :param event: contains information about the event.
  7143. :return:
  7144. """
  7145. if self.is_legacy is False:
  7146. event_pos = event.pos
  7147. right_button = 2
  7148. else:
  7149. event_pos = (event.xdata, event.ydata)
  7150. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7151. right_button = 3
  7152. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7153. if self.grid_status() == True:
  7154. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  7155. else:
  7156. pos = (pos_canvas[0], pos_canvas[1])
  7157. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  7158. # canvas menu
  7159. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  7160. self.cursor = QtGui.QCursor()
  7161. self.populate_cmenu_grids()
  7162. self.ui.popMenu.popup(self.cursor.pos())
  7163. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  7164. # selection and then select a type of selection ("enclosing" or "touching")
  7165. if event.button == 1: # left click
  7166. modifiers = QtWidgets.QApplication.keyboardModifiers()
  7167. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  7168. if modifiers == QtCore.Qt.ShiftModifier:
  7169. # do not auto open the Project Tab
  7170. self.click_noproject = True
  7171. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  7172. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  7173. return
  7174. if self.doubleclick is True:
  7175. self.doubleclick = False
  7176. if self.collection.get_selected():
  7177. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  7178. if self.ui.splitter.sizes()[0] == 0:
  7179. self.ui.splitter.setSizes([1, 1])
  7180. try:
  7181. # delete the selection shape(S) as it may be in the way
  7182. self.delete_selection_shape()
  7183. self.delete_hover_shape()
  7184. except Exception as e:
  7185. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  7186. return
  7187. else:
  7188. if self.selection_type is not None:
  7189. try:
  7190. self.selection_area_handler(self.pos, pos, self.selection_type)
  7191. self.selection_type = None
  7192. except Exception as e:
  7193. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  7194. return
  7195. else:
  7196. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  7197. if key_modifier == QtCore.Qt.ShiftModifier:
  7198. mod_key = 'Shift'
  7199. elif key_modifier == QtCore.Qt.ControlModifier:
  7200. mod_key = 'Control'
  7201. else:
  7202. mod_key = None
  7203. try:
  7204. if mod_key == self.defaults["global_mselect_key"]:
  7205. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  7206. # deselect, and if it's not selected then it will be selected
  7207. # If there is no active command (self.command_active is None) then we check if we clicked
  7208. # on a object by checking the bounding limits against mouse click position
  7209. if self.command_active is None:
  7210. self.select_objects(key='CTRL')
  7211. self.delete_hover_shape()
  7212. else:
  7213. # If there is no active command (self.command_active is None) then we check if we clicked
  7214. # on a object by checking the bounding limits against mouse click position
  7215. if self.command_active is None:
  7216. self.select_objects()
  7217. self.delete_hover_shape()
  7218. except Exception as e:
  7219. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  7220. return
  7221. def selection_area_handler(self, start_pos, end_pos, sel_type):
  7222. """
  7223. :param start_pos: mouse position when the selection LMB click was done
  7224. :param end_pos: mouse position when the left mouse button is released
  7225. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  7226. :return:
  7227. """
  7228. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  7229. # delete previous selection shape
  7230. self.delete_selection_shape()
  7231. # make all objects inactive
  7232. self.collection.set_all_inactive()
  7233. for obj in self.collection.get_list():
  7234. try:
  7235. # select the object(s) only if it is enabled (plotted)
  7236. if obj.options['plot']:
  7237. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  7238. (obj.options['xmax'], obj.options['ymin']),
  7239. (obj.options['xmax'], obj.options['ymax']),
  7240. (obj.options['xmin'], obj.options['ymax'])])
  7241. if sel_type is True:
  7242. if poly_obj.within(poly_selection):
  7243. # create the selection box around the selected object
  7244. if self.defaults['global_selection_shape'] is True:
  7245. self.draw_selection_shape(obj)
  7246. self.collection.set_active(obj.options['name'])
  7247. else:
  7248. if poly_selection.intersects(poly_obj):
  7249. # create the selection box around the selected object
  7250. if self.defaults['global_selection_shape'] is True:
  7251. self.draw_selection_shape(obj)
  7252. self.collection.set_active(obj.options['name'])
  7253. except Exception as e:
  7254. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  7255. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  7256. # In this case poly_obj creation (see above) will fail
  7257. log.debug("App.selection_area_handler() --> %s" % str(e))
  7258. def select_objects(self, key=None):
  7259. """
  7260. Will select objects clicked on canvas
  7261. :param key: for future use in cumulative selection
  7262. :return:
  7263. """
  7264. # list where we store the overlapped objects under our mouse left click position
  7265. objects_under_the_click_list = []
  7266. # Populate the list with the overlapped objects on the click position
  7267. curr_x, curr_y = self.pos
  7268. for obj in self.all_objects_list:
  7269. # FlatCAMScript and FlatCAMDocument objects can't be selected
  7270. if isinstance(obj, FlatCAMScript) or isinstance(obj, FlatCAMDocument):
  7271. continue
  7272. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  7273. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  7274. if obj.options['name'] not in objects_under_the_click_list:
  7275. if obj.options['plot']:
  7276. # add objects to the objects_under_the_click list only if the object is plotted
  7277. # (active and not disabled)
  7278. objects_under_the_click_list.append(obj.options['name'])
  7279. try:
  7280. if objects_under_the_click_list:
  7281. curr_sel_obj = self.collection.get_active()
  7282. # case when there is only an object under the click and we toggle it
  7283. if len(objects_under_the_click_list) == 1:
  7284. if curr_sel_obj is None:
  7285. self.collection.set_active(objects_under_the_click_list[0])
  7286. curr_sel_obj = self.collection.get_active()
  7287. # create the selection box around the selected object
  7288. if self.defaults['global_selection_shape'] is True:
  7289. self.draw_selection_shape(curr_sel_obj)
  7290. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  7291. self.on_objects_selection(False)
  7292. self.delete_selection_shape()
  7293. self.collection.set_active(objects_under_the_click_list[0])
  7294. curr_sel_obj = self.collection.get_active()
  7295. # create the selection box around the selected object
  7296. if self.defaults['global_selection_shape'] is True:
  7297. self.draw_selection_shape(curr_sel_obj)
  7298. self.selected_message(curr_sel_obj=curr_sel_obj)
  7299. else:
  7300. self.on_objects_selection(False)
  7301. self.delete_selection_shape()
  7302. if self.call_source != 'app':
  7303. self.call_source = 'app'
  7304. self.selected_message(curr_sel_obj=curr_sel_obj)
  7305. else:
  7306. # If there is no selected object
  7307. # make active the first element of the overlapped objects list
  7308. if self.collection.get_active() is None:
  7309. self.collection.set_active(objects_under_the_click_list[0])
  7310. name_sel_obj = self.collection.get_active().options['name']
  7311. # In case that there is a selected object but it is not in the overlapped object list
  7312. # make that object inactive and activate the first element in the overlapped object list
  7313. if name_sel_obj not in objects_under_the_click_list:
  7314. self.collection.set_inactive(name_sel_obj)
  7315. name_sel_obj = objects_under_the_click_list[0]
  7316. self.collection.set_active(name_sel_obj)
  7317. else:
  7318. sel_idx = objects_under_the_click_list.index(name_sel_obj)
  7319. self.collection.set_all_inactive()
  7320. self.collection.set_active(objects_under_the_click_list[(sel_idx + 1) %
  7321. len(objects_under_the_click_list)])
  7322. curr_sel_obj = self.collection.get_active()
  7323. # delete the possible selection box around a possible selected object
  7324. self.delete_selection_shape()
  7325. # create the selection box around the selected object
  7326. if self.defaults['global_selection_shape'] is True:
  7327. self.draw_selection_shape(curr_sel_obj)
  7328. self.selected_message(curr_sel_obj=curr_sel_obj)
  7329. else:
  7330. # deselect everything
  7331. self.on_objects_selection(False)
  7332. # delete the possible selection box around a possible selected object
  7333. self.delete_selection_shape()
  7334. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  7335. # only when working on App
  7336. if self.call_source == 'app':
  7337. if self.click_noproject is False:
  7338. # if the Tool Tab is in focus don't change focus to Project Tab
  7339. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  7340. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7341. else:
  7342. # restore auto open the Project Tab
  7343. self.click_noproject = False
  7344. # delete any text in the status bar, implicitly the last object name that was selected
  7345. # self.inform.emit("")
  7346. else:
  7347. self.call_source = 'app'
  7348. except Exception as e:
  7349. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  7350. def selected_message(self, curr_sel_obj):
  7351. if curr_sel_obj:
  7352. if curr_sel_obj.kind == 'gerber':
  7353. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7354. color='green', name=str(curr_sel_obj.options['name'])))
  7355. elif curr_sel_obj.kind == 'excellon':
  7356. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7357. color='brown', name=str(curr_sel_obj.options['name'])))
  7358. elif curr_sel_obj.kind == 'cncjob':
  7359. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7360. color='blue', name=str(curr_sel_obj.options['name'])))
  7361. elif curr_sel_obj.kind == 'geometry':
  7362. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7363. color='red', name=str(curr_sel_obj.options['name'])))
  7364. def delete_hover_shape(self):
  7365. self.hover_shapes.clear()
  7366. self.hover_shapes.redraw()
  7367. def draw_hover_shape(self, sel_obj, color=None):
  7368. """
  7369. :param sel_obj: the object for which the hover shape must be drawn
  7370. :return:
  7371. """
  7372. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7373. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7374. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7375. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7376. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  7377. if self.defaults['units'].upper() == 'MM':
  7378. hover_rect = hover_rect.buffer(-0.1)
  7379. hover_rect = hover_rect.buffer(0.2)
  7380. else:
  7381. hover_rect = hover_rect.buffer(-0.00393)
  7382. hover_rect = hover_rect.buffer(0.00787)
  7383. # if color:
  7384. # face = Color(color)
  7385. # face.alpha = 0.2
  7386. # outline = Color(color, alpha=0.8)
  7387. # else:
  7388. # face = Color(self.defaults['global_sel_fill'])
  7389. # face.alpha = 0.2
  7390. # outline = self.defaults['global_sel_line']
  7391. if color:
  7392. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7393. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7394. else:
  7395. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7396. outline = self.defaults['global_sel_line']
  7397. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  7398. if self.is_legacy is True:
  7399. self.hover_shapes.redraw()
  7400. def delete_selection_shape(self):
  7401. self.move_tool.sel_shapes.clear()
  7402. self.move_tool.sel_shapes.redraw()
  7403. def draw_selection_shape(self, sel_obj, color=None):
  7404. """
  7405. :param sel_obj: the object for which the selection shape must be drawn
  7406. :return:
  7407. """
  7408. if sel_obj is None:
  7409. return
  7410. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7411. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7412. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7413. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7414. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7415. if self.defaults['units'].upper() == 'MM':
  7416. sel_rect = sel_rect.buffer(-0.1)
  7417. sel_rect = sel_rect.buffer(0.2)
  7418. else:
  7419. sel_rect = sel_rect.buffer(-0.00393)
  7420. sel_rect = sel_rect.buffer(0.00787)
  7421. if color:
  7422. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7423. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7424. else:
  7425. if self.is_legacy is False:
  7426. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7427. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  7428. else:
  7429. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  7430. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  7431. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  7432. color=outline,
  7433. face_color=face,
  7434. update=True,
  7435. layer=0,
  7436. tolerance=None))
  7437. if self.is_legacy is True:
  7438. self.move_tool.sel_shapes.redraw()
  7439. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  7440. """
  7441. :param old_coords: old coordinates
  7442. :param coords: new coordinates
  7443. :return:
  7444. """
  7445. if 'color' in kwargs:
  7446. color = kwargs['color']
  7447. else:
  7448. color = self.defaults['global_sel_line']
  7449. if 'face_color' in kwargs:
  7450. face_color = kwargs['face_color']
  7451. else:
  7452. face_color = self.defaults['global_sel_fill']
  7453. if 'face_alpha' in kwargs:
  7454. face_alpha = kwargs['face_alpha']
  7455. else:
  7456. face_alpha = 0.3
  7457. x0, y0 = old_coords
  7458. x1, y1 = coords
  7459. pt1 = (x0, y0)
  7460. pt2 = (x1, y0)
  7461. pt3 = (x1, y1)
  7462. pt4 = (x0, y1)
  7463. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7464. # color_t = Color(face_color)
  7465. # color_t.alpha = face_alpha
  7466. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  7467. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  7468. layer=0, tolerance=None)
  7469. if self.is_legacy is True:
  7470. self.move_tool.sel_shapes.redraw()
  7471. def on_file_new_click(self):
  7472. if self.collection.get_list() and self.should_we_save:
  7473. msgbox = QtWidgets.QMessageBox()
  7474. # msgbox.setText("<B>Save changes ...</B>")
  7475. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7476. "Creating a New project will delete them.\n"
  7477. "Do you want to Save the project?"))
  7478. msgbox.setWindowTitle(_("Save changes"))
  7479. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  7480. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7481. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7482. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7483. msgbox.setDefaultButton(bt_yes)
  7484. msgbox.exec_()
  7485. response = msgbox.clickedButton()
  7486. if response == bt_yes:
  7487. self.on_file_saveprojectas()
  7488. elif response == bt_cancel:
  7489. return
  7490. elif response == bt_no:
  7491. self.on_file_new()
  7492. else:
  7493. self.on_file_new()
  7494. self.inform.emit('[success] %s...' %
  7495. _("New Project created"))
  7496. def on_file_new(self, cli=None):
  7497. """
  7498. Callback for menu item File -> New. Returns the application to its
  7499. startup state. This method is thread-safe.
  7500. :return: None
  7501. """
  7502. self.report_usage("on_file_new")
  7503. # Remove everything from memory
  7504. App.log.debug("on_file_new()")
  7505. if self.call_source != 'app':
  7506. self.editor2object(cleanup=True)
  7507. # ## EDITOR section
  7508. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  7509. self.exc_editor = FlatCAMExcEditor(self)
  7510. self.grb_editor = FlatCAMGrbEditor(self)
  7511. # Clear pool
  7512. self.clear_pool()
  7513. for obj in self.collection.get_list():
  7514. # delete shapes left drawn from mark shape_collections, if any
  7515. if isinstance(obj, FlatCAMGerber):
  7516. try:
  7517. obj.mark_shapes.enabled = False
  7518. obj.mark_shapes.clear(update=True)
  7519. except AttributeError:
  7520. pass
  7521. # also delete annotation shapes, if any
  7522. elif isinstance(obj, FlatCAMCNCjob):
  7523. try:
  7524. obj.annotation.enabled = False
  7525. obj.annotation.clear(update=True)
  7526. except AttributeError:
  7527. pass
  7528. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7529. self.init_tcl()
  7530. self.delete_selection_shape()
  7531. self.collection.delete_all()
  7532. self.setup_component_editor()
  7533. # Clear project filename
  7534. self.project_filename = None
  7535. # Load the application defaults
  7536. self.load_defaults(filename='current_defaults')
  7537. # Re-fresh project options
  7538. self.on_options_app2project()
  7539. # Init Tools
  7540. self.init_tools()
  7541. if cli is None:
  7542. # Close any Tabs opened in the Plot Tab Area section
  7543. for index in range(self.ui.plot_tab_area.count()):
  7544. self.ui.plot_tab_area.closeTab(index)
  7545. # for whatever reason previous command does not close the last tab so I do it manually
  7546. self.ui.plot_tab_area.closeTab(0)
  7547. # # And then add again the Plot Area
  7548. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  7549. self.ui.plot_tab_area.protectTab(0)
  7550. # take the focus of the Notebook on Project Tab.
  7551. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7552. self.set_ui_title(name=_("New Project - Not saved"))
  7553. def obj_properties(self):
  7554. """
  7555. Will launch the object Properties Tool
  7556. :return:
  7557. """
  7558. self.report_usage("obj_properties()")
  7559. self.properties_tool.run(toggle=False)
  7560. def on_project_context_save(self):
  7561. """
  7562. Wrapper, will save the object function of it's type
  7563. :return:
  7564. """
  7565. obj = self.collection.get_active()
  7566. if type(obj) == FlatCAMGeometry:
  7567. self.on_file_exportdxf()
  7568. elif type(obj) == FlatCAMExcellon:
  7569. self.on_file_saveexcellon()
  7570. elif type(obj) == FlatCAMCNCjob:
  7571. obj.on_exportgcode_button_click()
  7572. elif type(obj) == FlatCAMGerber:
  7573. self.on_file_savegerber()
  7574. elif type(obj) == FlatCAMScript:
  7575. self.on_file_savescript()
  7576. elif type(obj) == FlatCAMDocument:
  7577. self.on_file_savedocument()
  7578. def obj_move(self):
  7579. self.report_usage("obj_move()")
  7580. self.move_tool.run(toggle=False)
  7581. def on_fileopengerber(self, signal: bool = None, name=None):
  7582. """
  7583. File menu callback for opening a Gerber.
  7584. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7585. :return: None
  7586. """
  7587. self.report_usage("on_fileopengerber")
  7588. App.log.debug("on_fileopengerber()")
  7589. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  7590. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  7591. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  7592. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  7593. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  7594. "*.mil);;" \
  7595. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  7596. "Allegro Files (*.art);;" \
  7597. "Mentor Files (*.pho *.gdo);;" \
  7598. "All Files (*.*)"
  7599. if name is None:
  7600. try:
  7601. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  7602. directory=self.get_last_folder(),
  7603. filter=_filter_)
  7604. except TypeError:
  7605. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  7606. filenames = [str(filename) for filename in filenames]
  7607. else:
  7608. filenames = [name]
  7609. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7610. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7611. _("Opening Gerber file.")),
  7612. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7613. color=QtGui.QColor("gray"))
  7614. if len(filenames) == 0:
  7615. self.inform.emit('[WARNING_NOTCL] %s' %
  7616. _("Open Gerber cancelled."))
  7617. else:
  7618. for filename in filenames:
  7619. if filename != '':
  7620. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  7621. def on_fileopenexcellon(self, signal: bool = None, name=None):
  7622. """
  7623. File menu callback for opening an Excellon file.
  7624. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7625. :return: None
  7626. """
  7627. self.report_usage("on_fileopenexcellon")
  7628. App.log.debug("on_fileopenexcellon()")
  7629. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  7630. "All Files (*.*)"
  7631. if name is None:
  7632. try:
  7633. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  7634. directory=self.get_last_folder(),
  7635. filter=_filter_)
  7636. except TypeError:
  7637. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  7638. filenames = [str(filename) for filename in filenames]
  7639. else:
  7640. filenames = [str(name)]
  7641. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7642. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7643. _("Opening Excellon file.")),
  7644. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7645. color=QtGui.QColor("gray"))
  7646. if len(filenames) == 0:
  7647. self.inform.emit('[WARNING_NOTCL]%s' %
  7648. _(" Open Excellon cancelled."))
  7649. else:
  7650. for filename in filenames:
  7651. if filename != '':
  7652. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  7653. def on_fileopengcode(self, signal: bool = None, name=None):
  7654. """
  7655. File menu call back for opening gcode.
  7656. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7657. :return: None
  7658. """
  7659. self.report_usage("on_fileopengcode")
  7660. App.log.debug("on_fileopengcode()")
  7661. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  7662. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  7663. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  7664. "All Files (*.*)"
  7665. if name is None:
  7666. try:
  7667. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  7668. directory=self.get_last_folder(),
  7669. filter=_filter_)
  7670. except TypeError:
  7671. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  7672. filenames = [str(filename) for filename in filenames]
  7673. else:
  7674. filenames = [name]
  7675. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7676. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7677. _("Opening G-Code file.")),
  7678. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7679. color=QtGui.QColor("gray"))
  7680. if len(filenames) == 0:
  7681. self.inform.emit('[WARNING_NOTCL] %s' %
  7682. _("Open G-Code cancelled."))
  7683. else:
  7684. for filename in filenames:
  7685. if filename != '':
  7686. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  7687. def on_file_openproject(self, signal: bool = None):
  7688. """
  7689. File menu callback for opening a project.
  7690. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7691. :return: None
  7692. """
  7693. self.report_usage("on_file_openproject")
  7694. App.log.debug("on_file_openproject()")
  7695. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  7696. try:
  7697. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  7698. directory=self.get_last_folder(), filter=_filter_)
  7699. except TypeError:
  7700. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  7701. # The Qt methods above will return a QString which can cause problems later.
  7702. # So far json.dump() will fail to serialize it.
  7703. # TODO: Improve the serialization methods and remove this fix.
  7704. filename = str(filename)
  7705. if filename == "":
  7706. self.inform.emit('[WARNING_NOTCL] %s' %
  7707. _("Open Project cancelled."))
  7708. else:
  7709. # self.worker_task.emit({'fcn': self.open_project,
  7710. # 'params': [filename]})
  7711. # The above was failing because open_project() is not
  7712. # thread safe. The new_project()
  7713. self.open_project(filename)
  7714. def on_file_openconfig(self, signal: bool = None):
  7715. """
  7716. File menu callback for opening a config file.
  7717. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7718. :return: None
  7719. """
  7720. self.report_usage("on_file_openconfig")
  7721. App.log.debug("on_file_openconfig()")
  7722. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  7723. try:
  7724. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7725. directory=self.data_path, filter=_filter_)
  7726. except TypeError:
  7727. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7728. filter=_filter_)
  7729. if filename == "":
  7730. self.inform.emit('[WARNING_NOTCL] %s' %
  7731. _("Open Config cancelled."))
  7732. else:
  7733. self.open_config_file(filename)
  7734. def on_file_exportsvg(self):
  7735. """
  7736. Callback for menu item File->Export SVG.
  7737. :return: None
  7738. """
  7739. self.report_usage("on_file_exportsvg")
  7740. App.log.debug("on_file_exportsvg()")
  7741. obj = self.collection.get_active()
  7742. if obj is None:
  7743. self.inform.emit('[WARNING_NOTCL] %s' %
  7744. _("No object selected."))
  7745. msg = _("Please Select a Geometry object to export")
  7746. msgbox = QtWidgets.QMessageBox()
  7747. msgbox.setInformativeText(msg)
  7748. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7749. msgbox.setDefaultButton(bt_ok)
  7750. msgbox.exec_()
  7751. return
  7752. # Check for more compatible types and add as required
  7753. if (not isinstance(obj, FlatCAMGeometry)
  7754. and not isinstance(obj, FlatCAMGerber)
  7755. and not isinstance(obj, FlatCAMCNCjob)
  7756. and not isinstance(obj, FlatCAMExcellon)):
  7757. msg = '[ERROR_NOTCL] %s' % \
  7758. _("Only Geometry, Gerber and CNCJob objects can be used.")
  7759. msgbox = QtWidgets.QMessageBox()
  7760. msgbox.setInformativeText(msg)
  7761. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7762. msgbox.setDefaultButton(bt_ok)
  7763. msgbox.exec_()
  7764. return
  7765. name = obj.options["name"]
  7766. _filter = "SVG File (*.svg);;All Files (*.*)"
  7767. try:
  7768. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7769. caption=_("Export SVG"),
  7770. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  7771. filter=_filter)
  7772. except TypeError:
  7773. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  7774. filename = str(filename)
  7775. if filename == "":
  7776. self.inform.emit('[WARNING_NOTCL]%s' %
  7777. _(" Export SVG cancelled."))
  7778. return
  7779. else:
  7780. self.export_svg(name, filename)
  7781. if self.defaults["global_open_style"] is False:
  7782. self.file_opened.emit("SVG", filename)
  7783. self.file_saved.emit("SVG", filename)
  7784. def on_file_exportpng(self):
  7785. self.report_usage("on_file_exportpng")
  7786. App.log.debug("on_file_exportpng()")
  7787. self.date = str(datetime.today()).rpartition('.')[0]
  7788. self.date = ''.join(c for c in self.date if c not in ':-')
  7789. self.date = self.date.replace(' ', '_')
  7790. if self.is_legacy is False:
  7791. image = _screenshot()
  7792. data = np.asarray(image)
  7793. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  7794. self.inform.emit('[[WARNING_NOTCL]] %s' %
  7795. _('Data must be a 3D array with last dimension 3 or 4'))
  7796. return
  7797. filter_ = "PNG File (*.png);;All Files (*.*)"
  7798. try:
  7799. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7800. caption=_("Export PNG Image"),
  7801. directory=self.get_last_save_folder() + '/png_' + self.date,
  7802. filter=filter_)
  7803. except TypeError:
  7804. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  7805. filename = str(filename)
  7806. if filename == "":
  7807. self.inform.emit(_("Export PNG cancelled."))
  7808. return
  7809. else:
  7810. if self.is_legacy is False:
  7811. write_png(filename, data)
  7812. else:
  7813. self.plotcanvas.figure.savefig(filename)
  7814. if self.defaults["global_open_style"] is False:
  7815. self.file_opened.emit("png", filename)
  7816. self.file_saved.emit("png", filename)
  7817. def on_file_savegerber(self):
  7818. """
  7819. Callback for menu item in Project context menu.
  7820. :return: None
  7821. """
  7822. self.report_usage("on_file_savegerber")
  7823. App.log.debug("on_file_savegerber()")
  7824. obj = self.collection.get_active()
  7825. if obj is None:
  7826. self.inform.emit('[WARNING_NOTCL] %s' %
  7827. _("No object selected. Please select an Gerber object to export."))
  7828. return
  7829. # Check for more compatible types and add as required
  7830. if not isinstance(obj, FlatCAMGerber):
  7831. self.inform.emit('[ERROR_NOTCL] %s' %
  7832. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7833. return
  7834. name = self.collection.get_active().options["name"]
  7835. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  7836. try:
  7837. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7838. caption="Save Gerber source file",
  7839. directory=self.get_last_save_folder() + '/' + name,
  7840. filter=_filter)
  7841. except TypeError:
  7842. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  7843. filename = str(filename)
  7844. if filename == "":
  7845. self.inform.emit('[WARNING_NOTCL] %s' %
  7846. _("Save Gerber source file cancelled."))
  7847. return
  7848. else:
  7849. self.save_source_file(name, filename)
  7850. if self.defaults["global_open_style"] is False:
  7851. self.file_opened.emit("Gerber", filename)
  7852. self.file_saved.emit("Gerber", filename)
  7853. def on_file_savescript(self):
  7854. """
  7855. Callback for menu item in Project context menu.
  7856. :return: None
  7857. """
  7858. self.report_usage("on_file_savescript")
  7859. App.log.debug("on_file_savescript()")
  7860. obj = self.collection.get_active()
  7861. if obj is None:
  7862. self.inform.emit('[WARNING_NOTCL] %s' %
  7863. _("No object selected. Please select an Script object to export."))
  7864. return
  7865. # Check for more compatible types and add as required
  7866. if not isinstance(obj, FlatCAMScript):
  7867. self.inform.emit('[ERROR_NOTCL] %s' %
  7868. _("Failed. Only Script objects can be saved as TCL Script files..."))
  7869. return
  7870. name = self.collection.get_active().options["name"]
  7871. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  7872. try:
  7873. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7874. caption="Save Script source file",
  7875. directory=self.get_last_save_folder() + '/' + name,
  7876. filter=_filter)
  7877. except TypeError:
  7878. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Script source file"), filter=_filter)
  7879. filename = str(filename)
  7880. if filename == "":
  7881. self.inform.emit('[WARNING_NOTCL] %s' %
  7882. _("Save Script source file cancelled."))
  7883. return
  7884. else:
  7885. self.save_source_file(name, filename)
  7886. if self.defaults["global_open_style"] is False:
  7887. self.file_opened.emit("Script", filename)
  7888. self.file_saved.emit("Script", filename)
  7889. def on_file_savedocument(self):
  7890. """
  7891. Callback for menu item in Project context menu.
  7892. :return: None
  7893. """
  7894. self.report_usage("on_file_savedocument")
  7895. App.log.debug("on_file_savedocument()")
  7896. obj = self.collection.get_active()
  7897. if obj is None:
  7898. self.inform.emit('[WARNING_NOTCL] %s' %
  7899. _("No object selected. Please select an Document object to export."))
  7900. return
  7901. # Check for more compatible types and add as required
  7902. if not isinstance(obj, FlatCAMScript):
  7903. self.inform.emit('[ERROR_NOTCL] %s' %
  7904. _("Failed. Only Document objects can be saved as Document files..."))
  7905. return
  7906. name = self.collection.get_active().options["name"]
  7907. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  7908. try:
  7909. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7910. caption="Save Document source file",
  7911. directory=self.get_last_save_folder() + '/' + name,
  7912. filter=_filter)
  7913. except TypeError:
  7914. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Document source file"), filter=_filter)
  7915. filename = str(filename)
  7916. if filename == "":
  7917. self.inform.emit('[WARNING_NOTCL] %s' %
  7918. _("Save Document source file cancelled."))
  7919. return
  7920. else:
  7921. self.save_source_file(name, filename)
  7922. if self.defaults["global_open_style"] is False:
  7923. self.file_opened.emit("Document", filename)
  7924. self.file_saved.emit("Document", filename)
  7925. def on_file_saveexcellon(self):
  7926. """
  7927. Callback for menu item in project context menu.
  7928. :return: None
  7929. """
  7930. self.report_usage("on_file_saveexcellon")
  7931. App.log.debug("on_file_saveexcellon()")
  7932. obj = self.collection.get_active()
  7933. if obj is None:
  7934. self.inform.emit('[WARNING_NOTCL] %s' %
  7935. _("No object selected. Please select an Excellon object to export."))
  7936. return
  7937. # Check for more compatible types and add as required
  7938. if not isinstance(obj, FlatCAMExcellon):
  7939. self.inform.emit('[ERROR_NOTCL] %s' %
  7940. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7941. return
  7942. name = self.collection.get_active().options["name"]
  7943. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7944. try:
  7945. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7946. caption=_("Save Excellon source file"),
  7947. directory=self.get_last_save_folder() + '/' + name,
  7948. filter=_filter)
  7949. except TypeError:
  7950. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  7951. filename = str(filename)
  7952. if filename == "":
  7953. self.inform.emit('[WARNING_NOTCL] %s' %
  7954. _("Saving Excellon source file cancelled."))
  7955. return
  7956. else:
  7957. self.save_source_file(name, filename)
  7958. if self.defaults["global_open_style"] is False:
  7959. self.file_opened.emit("Excellon", filename)
  7960. self.file_saved.emit("Excellon", filename)
  7961. def on_file_exportexcellon(self):
  7962. """
  7963. Callback for menu item File->Export->Excellon.
  7964. :return: None
  7965. """
  7966. self.report_usage("on_file_exportexcellon")
  7967. App.log.debug("on_file_exportexcellon()")
  7968. obj = self.collection.get_active()
  7969. if obj is None:
  7970. self.inform.emit('[WARNING_NOTCL] %s' %
  7971. _("No object selected. Please Select an Excellon object to export."))
  7972. return
  7973. # Check for more compatible types and add as required
  7974. if not isinstance(obj, FlatCAMExcellon):
  7975. self.inform.emit('[ERROR_NOTCL] %s' %
  7976. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7977. return
  7978. name = self.collection.get_active().options["name"]
  7979. _filter = self.defaults["excellon_save_filters"]
  7980. try:
  7981. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7982. caption=_("Export Excellon"),
  7983. directory=self.get_last_save_folder() + '/' + name,
  7984. filter=_filter)
  7985. except TypeError:
  7986. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  7987. filename = str(filename)
  7988. if filename == "":
  7989. self.inform.emit('[WARNING_NOTCL] %s' %
  7990. _("Export Excellon cancelled."))
  7991. return
  7992. else:
  7993. used_extension = filename.rpartition('.')[2]
  7994. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  7995. self.export_excellon(name, filename)
  7996. if self.defaults["global_open_style"] is False:
  7997. self.file_opened.emit("Excellon", filename)
  7998. self.file_saved.emit("Excellon", filename)
  7999. def on_file_exportgerber(self):
  8000. """
  8001. Callback for menu item File->Export->Gerber.
  8002. :return: None
  8003. """
  8004. self.report_usage("on_file_exportgerber")
  8005. App.log.debug("on_file_exportgerber()")
  8006. obj = self.collection.get_active()
  8007. if obj is None:
  8008. self.inform.emit('[WARNING_NOTCL] %s' %
  8009. _("No object selected. Please Select an Gerber object to export."))
  8010. return
  8011. # Check for more compatible types and add as required
  8012. if not isinstance(obj, FlatCAMGerber):
  8013. self.inform.emit('[ERROR_NOTCL] %s' %
  8014. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  8015. return
  8016. name = self.collection.get_active().options["name"]
  8017. _filter_ = self.defaults['gerber_save_filters']
  8018. try:
  8019. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8020. caption=_("Export Gerber"),
  8021. directory=self.get_last_save_folder() + '/' + name,
  8022. filter=_filter_)
  8023. except TypeError:
  8024. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  8025. filename = str(filename)
  8026. if filename == "":
  8027. self.inform.emit('[WARNING_NOTCL] %s' %
  8028. _("Export Gerber cancelled."))
  8029. return
  8030. else:
  8031. used_extension = filename.rpartition('.')[2]
  8032. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  8033. self.export_gerber(name, filename)
  8034. if self.defaults["global_open_style"] is False:
  8035. self.file_opened.emit("Gerber", filename)
  8036. self.file_saved.emit("Gerber", filename)
  8037. def on_file_exportdxf(self):
  8038. """
  8039. Callback for menu item File->Export DXF.
  8040. :return: None
  8041. """
  8042. self.report_usage("on_file_exportdxf")
  8043. App.log.debug("on_file_exportdxf()")
  8044. obj = self.collection.get_active()
  8045. if obj is None:
  8046. self.inform.emit('[WARNING_NOTCL] %s' %
  8047. _("No object selected."))
  8048. msg = _("Please Select a Geometry object to export")
  8049. msgbox = QtWidgets.QMessageBox()
  8050. msgbox.setInformativeText(msg)
  8051. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8052. msgbox.setDefaultButton(bt_ok)
  8053. msgbox.exec_()
  8054. return
  8055. # Check for more compatible types and add as required
  8056. if not isinstance(obj, FlatCAMGeometry):
  8057. msg = '[ERROR_NOTCL] %s' % \
  8058. _("Only Geometry objects can be used.")
  8059. msgbox = QtWidgets.QMessageBox()
  8060. msgbox.setInformativeText(msg)
  8061. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8062. msgbox.setDefaultButton(bt_ok)
  8063. msgbox.exec_()
  8064. return
  8065. name = self.collection.get_active().options["name"]
  8066. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  8067. try:
  8068. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8069. caption=_("Export DXF"),
  8070. directory=self.get_last_save_folder() + '/' + name,
  8071. filter=_filter_)
  8072. except TypeError:
  8073. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  8074. filter=_filter_)
  8075. filename = str(filename)
  8076. if filename == "":
  8077. self.inform.emit('[WARNING_NOTCL] %s' %
  8078. _("Export DXF cancelled."))
  8079. return
  8080. else:
  8081. self.export_dxf(name, filename)
  8082. if self.defaults["global_open_style"] is False:
  8083. self.file_opened.emit("DXF", filename)
  8084. self.file_saved.emit("DXF", filename)
  8085. def on_file_importsvg(self, type_of_obj):
  8086. """
  8087. Callback for menu item File->Import SVG.
  8088. :param type_of_obj: to import the SVG as Geometry or as Gerber
  8089. :type type_of_obj: str
  8090. :return: None
  8091. """
  8092. self.report_usage("on_file_importsvg")
  8093. App.log.debug("on_file_importsvg()")
  8094. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  8095. try:
  8096. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  8097. directory=self.get_last_folder(), filter=_filter_)
  8098. except TypeError:
  8099. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  8100. filter=_filter_)
  8101. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  8102. type_of_obj = "geometry"
  8103. filenames = [str(filename) for filename in filenames]
  8104. if len(filenames) == 0:
  8105. self.inform.emit('[WARNING_NOTCL] %s' %
  8106. _("Open SVG cancelled."))
  8107. else:
  8108. for filename in filenames:
  8109. if filename != '':
  8110. self.worker_task.emit({'fcn': self.import_svg,
  8111. 'params': [filename, type_of_obj]})
  8112. def on_file_importdxf(self, type_of_obj):
  8113. """
  8114. Callback for menu item File->Import DXF.
  8115. :param type_of_obj: to import the DXF as Geometry or as Gerber
  8116. :type type_of_obj: str
  8117. :return: None
  8118. """
  8119. self.report_usage("on_file_importdxf")
  8120. App.log.debug("on_file_importdxf()")
  8121. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  8122. try:
  8123. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  8124. directory=self.get_last_folder(),
  8125. filter=_filter_)
  8126. except TypeError:
  8127. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  8128. filter=_filter_)
  8129. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  8130. type_of_obj = "geometry"
  8131. filenames = [str(filename) for filename in filenames]
  8132. if len(filenames) == 0:
  8133. self.inform.emit('[WARNING_NOTCL] %s' %
  8134. _("Open DXF cancelled."))
  8135. else:
  8136. for filename in filenames:
  8137. if filename != '':
  8138. self.worker_task.emit({'fcn': self.import_dxf,
  8139. 'params': [filename, type_of_obj]})
  8140. # ###############################################################################################################
  8141. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  8142. # ###############################################################################################################
  8143. def init_code_editor(self, name):
  8144. self.text_editor_tab = TextEditor(app=self)
  8145. # add the tab if it was closed
  8146. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  8147. self.text_editor_tab.setObjectName('text_editor_tab')
  8148. # delete the absolute and relative position and messages in the infobar
  8149. self.ui.position_label.setText("")
  8150. self.ui.rel_position_label.setText("")
  8151. # first clear previous text in text editor (if any)
  8152. self.text_editor_tab.code_editor.clear()
  8153. self.text_editor_tab.code_editor.setReadOnly(False)
  8154. self.toggle_codeeditor = True
  8155. self.text_editor_tab.code_editor.completer_enable = False
  8156. self.text_editor_tab.buttonRun.hide()
  8157. # make sure to keep a reference to the code editor
  8158. self.reference_code_editor = self.text_editor_tab.code_editor
  8159. # Switch plot_area to CNCJob tab
  8160. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  8161. def on_view_source(self):
  8162. """
  8163. Called when the user wants to see the source file of the selected object
  8164. :return:
  8165. """
  8166. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  8167. self.proc_container.view.set_busy(_("Loading..."))
  8168. try:
  8169. obj = self.collection.get_active()
  8170. except Exception as e:
  8171. log.debug("App.on_view_source() --> %s" % str(e))
  8172. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  8173. return 'fail'
  8174. if obj is None:
  8175. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  8176. return 'fail'
  8177. flt = "All Files (*.*)"
  8178. if obj.kind == 'gerber':
  8179. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  8180. elif obj.kind == 'excellon':
  8181. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  8182. elif obj.kind == 'cncjob':
  8183. "GCode Files (*.NC);;All Files (*.*)"
  8184. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  8185. # add the tab if it was closed
  8186. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  8187. self.source_editor_tab.setObjectName('source_editor_tab')
  8188. # delete the absolute and relative position and messages in the infobar
  8189. self.ui.position_label.setText("")
  8190. self.ui.rel_position_label.setText("")
  8191. # first clear previous text in text editor (if any)
  8192. self.source_editor_tab.code_editor.clear()
  8193. self.source_editor_tab.code_editor.setReadOnly(False)
  8194. self.source_editor_tab.code_editor.completer_enable = False
  8195. self.source_editor_tab.buttonRun.hide()
  8196. # Switch plot_area to CNCJob tab
  8197. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  8198. try:
  8199. self.source_editor_tab.buttonOpen.clicked.disconnect()
  8200. except TypeError:
  8201. pass
  8202. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  8203. try:
  8204. self.source_editor_tab.buttonSave.clicked.disconnect()
  8205. except TypeError:
  8206. pass
  8207. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  8208. # then append the text from GCode to the text editor
  8209. if obj.kind == 'cncjob':
  8210. try:
  8211. file = obj.export_gcode(
  8212. preamble=self.defaults["cncjob_prepend"],
  8213. postamble=self.defaults["cncjob_append"],
  8214. to_file=True)
  8215. if file == 'fail':
  8216. return 'fail'
  8217. except AttributeError:
  8218. self.inform.emit('[WARNING_NOTCL] %s' %
  8219. _("There is no selected object for which to see it's source file code."))
  8220. return 'fail'
  8221. else:
  8222. try:
  8223. file = StringIO(obj.source_file)
  8224. except (AttributeError, TypeError):
  8225. self.inform.emit('[WARNING_NOTCL] %s' %
  8226. _("There is no selected object for which to see it's source file code."))
  8227. return 'fail'
  8228. self.source_editor_tab.t_frame.hide()
  8229. try:
  8230. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  8231. # for line in file:
  8232. # QtWidgets.QApplication.processEvents()
  8233. # proc_line = str(line).strip('\n')
  8234. # self.source_editor_tab.code_editor.append(proc_line)
  8235. except Exception as e:
  8236. log.debug('App.on_view_source() -->%s' % str(e))
  8237. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  8238. return
  8239. self.source_editor_tab.handleTextChanged()
  8240. self.source_editor_tab.t_frame.show()
  8241. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  8242. self.proc_container.view.set_idle()
  8243. # self.ui.show()
  8244. def on_toggle_code_editor(self):
  8245. self.report_usage("on_toggle_code_editor()")
  8246. if self.toggle_codeeditor is False:
  8247. self.init_code_editor(name=_("Code Editor"))
  8248. self.text_editor_tab.buttonOpen.clicked.disconnect()
  8249. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  8250. self.text_editor_tab.buttonSave.clicked.disconnect()
  8251. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  8252. else:
  8253. for idx in range(self.ui.plot_tab_area.count()):
  8254. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  8255. self.ui.plot_tab_area.closeTab(idx)
  8256. break
  8257. self.toggle_codeeditor = False
  8258. def on_code_editor_close(self):
  8259. print("closed")
  8260. self.toggle_codeeditor = False
  8261. def on_filenewscript(self, silent=False, name=None, text=None):
  8262. """
  8263. Will create a new script file and open it in the Code Editor
  8264. :param silent: if True will not display status messages
  8265. :param name: if specified will be the name of the new script
  8266. :param text: pass a source file to the newly created script to be loaded in it
  8267. :return: None
  8268. """
  8269. if silent is False:
  8270. self.inform.emit('[success] %s' %
  8271. _("New TCL script file created in Code Editor."))
  8272. # delete the absolute and relative position and messages in the infobar
  8273. self.ui.position_label.setText("")
  8274. self.ui.rel_position_label.setText("")
  8275. if name is not None:
  8276. self.new_script_object(name=name, text=text)
  8277. else:
  8278. self.new_script_object(text=text)
  8279. # script_text = script_obj.source_file
  8280. #
  8281. # self.proc_container.view.set_busy(_("Loading..."))
  8282. # script_obj.script_editor_tab.t_frame.hide()
  8283. #
  8284. # script_obj.script_editor_tab.t_frame.show()
  8285. # self.proc_container.view.set_idle()
  8286. def on_fileopenscript(self, name=None, silent=False):
  8287. """
  8288. Will open a Tcl script file into the Code Editor
  8289. :param silent: if True will not display status messages
  8290. :param name: name of a Tcl script file to open
  8291. :return:
  8292. """
  8293. self.report_usage("on_fileopenscript")
  8294. App.log.debug("on_fileopenscript()")
  8295. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  8296. if name:
  8297. filenames = [name]
  8298. else:
  8299. try:
  8300. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  8301. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  8302. except TypeError:
  8303. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  8304. if len(filenames) == 0:
  8305. if silent is False:
  8306. self.inform.emit('[WARNING_NOTCL] %s' % _("Open TCL script cancelled."))
  8307. else:
  8308. for filename in filenames:
  8309. if filename != '':
  8310. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  8311. def on_filerunscript(self, name=None, silent=False):
  8312. """
  8313. File menu callback for loading and running a TCL script.
  8314. :param silent: if True will not display status messages
  8315. :param name: name of a Tcl script file to be run by FlatCAM
  8316. :return: None
  8317. """
  8318. self.report_usage("on_filerunscript")
  8319. App.log.debug("on_file_runscript()")
  8320. if name:
  8321. filename = name
  8322. if self.cmd_line_headless != 1:
  8323. self.splash.showMessage('%s: %ssec\n%s' %
  8324. (_("Canvas initialization started.\n"
  8325. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8326. _("Executing FlatCAMScript file.")
  8327. ),
  8328. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8329. color=QtGui.QColor("gray"))
  8330. else:
  8331. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  8332. try:
  8333. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  8334. directory=self.get_last_folder(), filter=_filter_)
  8335. except TypeError:
  8336. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  8337. # The Qt methods above will return a QString which can cause problems later.
  8338. # So far json.dump() will fail to serialize it.
  8339. # TODO: Improve the serialization methods and remove this fix.
  8340. filename = str(filename)
  8341. if filename == "":
  8342. if silent is False:
  8343. self.inform.emit('[WARNING_NOTCL] %s' %
  8344. _("Run TCL script cancelled."))
  8345. else:
  8346. if self.cmd_line_headless != 1:
  8347. if self.ui.shell_dock.isHidden():
  8348. self.ui.shell_dock.show()
  8349. try:
  8350. with open(filename, "r") as tcl_script:
  8351. cmd_line_shellfile_content = tcl_script.read()
  8352. if self.cmd_line_headless != 1:
  8353. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  8354. else:
  8355. self.shell._sysShell.exec_command(cmd_line_shellfile_content, no_echo=True)
  8356. if silent is False:
  8357. self.inform.emit('[success] %s' %
  8358. _("TCL script file opened in Code Editor and executed."))
  8359. except Exception as e:
  8360. log.debug("App.on_filerunscript() -> %s" % str(e))
  8361. sys.exit(2)
  8362. def on_file_saveproject(self, silent=False):
  8363. """
  8364. Callback for menu item File->Save Project. Saves the project to
  8365. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  8366. if set to None. The project is saved by calling ``self.save_project()``.
  8367. :param silent: if True will not display status messages
  8368. :return: None
  8369. """
  8370. self.report_usage("on_file_saveproject")
  8371. if self.project_filename is None:
  8372. self.on_file_saveprojectas()
  8373. else:
  8374. self.worker_task.emit({'fcn': self.save_project,
  8375. 'params': [self.project_filename, silent]})
  8376. if self.defaults["global_open_style"] is False:
  8377. self.file_opened.emit("project", self.project_filename)
  8378. self.file_saved.emit("project", self.project_filename)
  8379. self.set_ui_title(name=self.project_filename)
  8380. self.should_we_save = False
  8381. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  8382. """
  8383. Callback for menu item File->Save Project As... Opens a file
  8384. chooser and saves the project to the given file via
  8385. ``self.save_project()``.
  8386. :param make_copy if to be create a copy of the project; boolean
  8387. :param use_thread: if to be run in a separate thread; boolean
  8388. :param quit_action: if to be followed by quiting the application; boolean
  8389. :return: None
  8390. """
  8391. self.report_usage("on_file_saveprojectas")
  8392. self.date = str(datetime.today()).rpartition('.')[0]
  8393. self.date = ''.join(c for c in self.date if c not in ':-')
  8394. self.date = self.date.replace(' ', '_')
  8395. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  8396. try:
  8397. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8398. caption=_("Save Project As ..."),
  8399. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  8400. filter=filter_)
  8401. except TypeError:
  8402. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  8403. filename = str(filename)
  8404. if filename == '':
  8405. self.inform.emit('[WARNING_NOTCL] %s' %
  8406. _("Save Project cancelled."))
  8407. return
  8408. try:
  8409. f = open(filename, 'r')
  8410. f.close()
  8411. except IOError:
  8412. pass
  8413. if use_thread is True:
  8414. self.worker_task.emit({'fcn': self.save_project,
  8415. 'params': [filename, quit_action]})
  8416. else:
  8417. self.save_project(filename, quit_action)
  8418. # self.save_project(filename)
  8419. if self.defaults["global_open_style"] is False:
  8420. self.file_opened.emit("project", filename)
  8421. self.file_saved.emit("project", filename)
  8422. if not make_copy:
  8423. self.project_filename = filename
  8424. self.set_ui_title(name=self.project_filename)
  8425. self.should_we_save = False
  8426. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  8427. """
  8428. Exports a Geometry Object to an SVG file.
  8429. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8430. :param filename: Path to the SVG file to save to.
  8431. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  8432. :return:
  8433. """
  8434. self.report_usage("export_svg()")
  8435. if filename is None:
  8436. filename = self.defaults["global_last_save_folder"]
  8437. self.log.debug("export_svg()")
  8438. try:
  8439. obj = self.collection.get_by_name(str(obj_name))
  8440. except Exception:
  8441. # TODO: The return behavior has not been established... should raise exception?
  8442. return "Could not retrieve object: %s" % obj_name
  8443. with self.proc_container.new(_("Exporting SVG")) as proc:
  8444. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  8445. # Determine bounding area for svg export
  8446. bounds = obj.bounds()
  8447. size = obj.size()
  8448. # Convert everything to strings for use in the xml doc
  8449. svgwidth = str(size[0])
  8450. svgheight = str(size[1])
  8451. minx = str(bounds[0])
  8452. miny = str(bounds[1] - size[1])
  8453. uom = obj.units.lower()
  8454. # Add a SVG Header and footer to the svg output from shapely
  8455. # The transform flips the Y Axis so that everything renders
  8456. # properly within svg apps such as inkscape
  8457. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8458. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8459. svg_header += 'width="' + svgwidth + uom + '" '
  8460. svg_header += 'height="' + svgheight + uom + '" '
  8461. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  8462. svg_header += '<g transform="scale(1,-1)">'
  8463. svg_footer = '</g> </svg>'
  8464. svg_elem = svg_header + exported_svg + svg_footer
  8465. # Parse the xml through a xml parser just to add line feeds
  8466. # and to make it look more pretty for the output
  8467. svgcode = parse_xml_string(svg_elem)
  8468. svgcode = svgcode.toprettyxml()
  8469. try:
  8470. with open(filename, 'w') as fp:
  8471. fp.write(svgcode)
  8472. except PermissionError:
  8473. self.inform.emit('[WARNING] %s' %
  8474. _("Permission denied, saving not possible.\n"
  8475. "Most likely another app is holding the file open and not accessible."))
  8476. return 'fail'
  8477. if self.defaults["global_open_style"] is False:
  8478. self.file_opened.emit("SVG", filename)
  8479. self.file_saved.emit("SVG", filename)
  8480. self.inform.emit('[success] %s: %s' %
  8481. (_("SVG file exported to"), filename))
  8482. def save_source_file(self, obj_name, filename, use_thread=True):
  8483. """
  8484. Exports a FlatCAM Object to an Gerber/Excellon file.
  8485. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8486. :param filename: Path to the Gerber file to save to.
  8487. :param use_thread: if to be run in a separate thread
  8488. :return:
  8489. """
  8490. self.report_usage("save source file()")
  8491. if filename is None:
  8492. filename = self.defaults["global_last_save_folder"]
  8493. self.log.debug("save source file()")
  8494. obj = self.collection.get_by_name(obj_name)
  8495. file_string = StringIO(obj.source_file)
  8496. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8497. if file_string.getvalue() == '':
  8498. self.inform.emit('[ERROR_NOTCL] %s' %
  8499. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  8500. return 'fail'
  8501. try:
  8502. with open(filename, 'w') as file:
  8503. file.writelines('G04*\n')
  8504. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8505. (obj.kind.upper(), str(self.version), str(self.version_date)))
  8506. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8507. file.writelines('G04 Created on : %s*\n' % time_string)
  8508. for line in file_string:
  8509. file.writelines(line)
  8510. except PermissionError:
  8511. self.inform.emit('[WARNING] %s' %
  8512. _("Permission denied, saving not possible.\n"
  8513. "Most likely another app is holding the file open and not accessible."))
  8514. return 'fail'
  8515. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  8516. """
  8517. Exports a Excellon Object to an Excellon file.
  8518. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  8519. :param filename: Path to the Excellon file to save to.
  8520. :param local_use:
  8521. :param use_thread: if to be run in a separate thread
  8522. :return:
  8523. """
  8524. self.report_usage("export_excellon()")
  8525. if filename is None:
  8526. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  8527. self.log.debug("export_excellon()")
  8528. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  8529. self.defaults["excellon_exp_decimals"]
  8530. )
  8531. if local_use is None:
  8532. try:
  8533. obj = self.collection.get_by_name(str(obj_name))
  8534. except Exception:
  8535. # TODO: The return behavior has not been established... should raise exception?
  8536. return "Could not retrieve object: %s" % obj_name
  8537. else:
  8538. obj = local_use
  8539. if not isinstance(obj, FlatCAMExcellon):
  8540. self.inform.emit('[ERROR_NOTCL] %s' %
  8541. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  8542. return
  8543. # updated units
  8544. eunits = self.defaults["excellon_exp_units"]
  8545. ewhole = self.defaults["excellon_exp_integer"]
  8546. efract = self.defaults["excellon_exp_decimals"]
  8547. ezeros = self.defaults["excellon_exp_zeros"]
  8548. eformat = self.defaults["excellon_exp_format"]
  8549. slot_type = self.defaults["excellon_exp_slot_type"]
  8550. fc_units = self.defaults['units'].upper()
  8551. if fc_units == 'MM':
  8552. factor = 1 if eunits == 'METRIC' else 0.03937
  8553. else:
  8554. factor = 25.4 if eunits == 'METRIC' else 1
  8555. def make_excellon():
  8556. try:
  8557. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8558. header = 'M48\n'
  8559. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  8560. (str(self.version), str(self.version_date))
  8561. header += ';Filename: %s' % str(obj_name) + '\n'
  8562. header += ';Created on : %s' % time_str + '\n'
  8563. if eformat == 'dec':
  8564. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  8565. header += eunits + '\n'
  8566. for tool in obj.tools:
  8567. if eunits == 'METRIC':
  8568. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8569. tool=str(tool),
  8570. dec=2)
  8571. else:
  8572. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8573. tool=str(tool),
  8574. dec=4)
  8575. else:
  8576. if ezeros == 'LZ':
  8577. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8578. form='ndec', e_zeros='LZ', factor=factor,
  8579. slot_type=slot_type)
  8580. header += '%s,%s\n' % (eunits, 'LZ')
  8581. header += format_exc
  8582. for tool in obj.tools:
  8583. if eunits == 'METRIC':
  8584. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8585. tool=str(tool),
  8586. dec=2)
  8587. else:
  8588. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8589. tool=str(tool),
  8590. dec=4)
  8591. else:
  8592. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8593. form='ndec', e_zeros='TZ', factor=factor,
  8594. slot_type=slot_type)
  8595. header += '%s,%s\n' % (eunits, 'TZ')
  8596. header += format_exc
  8597. for tool in obj.tools:
  8598. if eunits == 'METRIC':
  8599. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8600. tool=str(tool),
  8601. dec=2)
  8602. else:
  8603. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8604. tool=str(tool),
  8605. dec=4)
  8606. header += '%\n'
  8607. footer = 'M30\n'
  8608. exported_excellon = header
  8609. exported_excellon += excellon_code
  8610. exported_excellon += footer
  8611. if local_use is None:
  8612. try:
  8613. with open(filename, 'w') as fp:
  8614. fp.write(exported_excellon)
  8615. except PermissionError:
  8616. self.inform.emit('[WARNING] %s' %
  8617. _("Permission denied, saving not possible.\n"
  8618. "Most likely another app is holding the file open and not accessible."))
  8619. return 'fail'
  8620. if self.defaults["global_open_style"] is False:
  8621. self.file_opened.emit("Excellon", filename)
  8622. self.file_saved.emit("Excellon", filename)
  8623. self.inform.emit('[success] %s: %s' %
  8624. (_("Excellon file exported to"), filename))
  8625. else:
  8626. return exported_excellon
  8627. except Exception as e:
  8628. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  8629. return 'fail'
  8630. if use_thread is True:
  8631. with self.proc_container.new(_("Exporting Excellon")) as proc:
  8632. def job_thread_exc(app_obj):
  8633. ret = make_excellon()
  8634. if ret == 'fail':
  8635. self.inform.emit('[ERROR_NOTCL] %s' %
  8636. _('Could not export Excellon file.'))
  8637. return
  8638. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8639. else:
  8640. ret = make_excellon()
  8641. if ret == 'fail':
  8642. self.inform.emit('[ERROR_NOTCL] %s' %
  8643. _('Could not export Excellon file.'))
  8644. return 'fail'
  8645. if local_use is not None:
  8646. return ret
  8647. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  8648. """
  8649. Exports a Gerber Object to an Gerber file.
  8650. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  8651. :param filename: Path to the Gerber file to save to.
  8652. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8653. When not None, the value will be the actual Gerber object for which to create the Gerber code
  8654. :param use_thread: if to be run in a separate thread
  8655. :return:
  8656. """
  8657. self.report_usage("export_gerber()")
  8658. if filename is None:
  8659. filename = self.defaults["global_last_save_folder"]
  8660. self.log.debug("export_gerber()")
  8661. if local_use is None:
  8662. try:
  8663. obj = self.collection.get_by_name(str(obj_name))
  8664. except Exception:
  8665. # TODO: The return behavior has not been established... should raise exception?
  8666. return "Could not retrieve object: %s" % obj_name
  8667. else:
  8668. obj = local_use
  8669. # updated units
  8670. gunits = self.defaults["gerber_exp_units"]
  8671. gwhole = self.defaults["gerber_exp_integer"]
  8672. gfract = self.defaults["gerber_exp_decimals"]
  8673. gzeros = self.defaults["gerber_exp_zeros"]
  8674. fc_units = self.defaults['units'].upper()
  8675. if fc_units == 'MM':
  8676. factor = 1 if gunits == 'MM' else 0.03937
  8677. else:
  8678. factor = 25.4 if gunits == 'MM' else 1
  8679. def make_gerber():
  8680. try:
  8681. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8682. header = 'G04*\n'
  8683. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  8684. (str(self.version), str(self.version_date))
  8685. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  8686. header += 'G04 Created on : %s*' % time_str + '\n'
  8687. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  8688. header += "%MO{units}*%\n".format(units=gunits)
  8689. for apid in obj.apertures:
  8690. if obj.apertures[apid]['type'] == 'C':
  8691. header += "%ADD{apid}{type},{size}*%\n".format(
  8692. apid=str(apid),
  8693. type='C',
  8694. size=(factor * obj.apertures[apid]['size'])
  8695. )
  8696. elif obj.apertures[apid]['type'] == 'R':
  8697. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8698. apid=str(apid),
  8699. type='R',
  8700. width=(factor * obj.apertures[apid]['width']),
  8701. height=(factor * obj.apertures[apid]['height'])
  8702. )
  8703. elif obj.apertures[apid]['type'] == 'O':
  8704. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8705. apid=str(apid),
  8706. type='O',
  8707. width=(factor * obj.apertures[apid]['width']),
  8708. height=(factor * obj.apertures[apid]['height'])
  8709. )
  8710. header += '\n'
  8711. # obsolete units but some software may need it
  8712. if gunits == 'IN':
  8713. header += 'G70*\n'
  8714. else:
  8715. header += 'G71*\n'
  8716. # Absolute Mode
  8717. header += 'G90*\n'
  8718. header += 'G01*\n'
  8719. # positive polarity
  8720. header += '%LPD*%\n'
  8721. footer = 'M02*\n'
  8722. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8723. exported_gerber = header
  8724. exported_gerber += gerber_code
  8725. exported_gerber += footer
  8726. if local_use is None:
  8727. try:
  8728. with open(filename, 'w') as fp:
  8729. fp.write(exported_gerber)
  8730. except PermissionError:
  8731. self.inform.emit('[WARNING] %s' %
  8732. _("Permission denied, saving not possible.\n"
  8733. "Most likely another app is holding the file open and not accessible."))
  8734. return 'fail'
  8735. if self.defaults["global_open_style"] is False:
  8736. self.file_opened.emit("Gerber", filename)
  8737. self.file_saved.emit("Gerber", filename)
  8738. self.inform.emit('[success] %s: %s' %
  8739. (_("Gerber file exported to"), filename))
  8740. else:
  8741. return exported_gerber
  8742. except Exception as e:
  8743. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8744. return 'fail'
  8745. if use_thread is True:
  8746. with self.proc_container.new(_("Exporting Gerber")) as proc:
  8747. def job_thread_grb(app_obj):
  8748. ret = make_gerber()
  8749. if ret == 'fail':
  8750. self.inform.emit('[ERROR_NOTCL] %s' %
  8751. _('Could not export Gerber file.'))
  8752. return
  8753. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8754. else:
  8755. ret = make_gerber()
  8756. if ret == 'fail':
  8757. self.inform.emit('[ERROR_NOTCL] %s' %
  8758. _('Could not export Gerber file.'))
  8759. return 'fail'
  8760. if local_use is not None:
  8761. return ret
  8762. def export_dxf(self, obj_name, filename, use_thread=True):
  8763. """
  8764. Exports a Geometry Object to an DXF file.
  8765. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8766. :param filename: Path to the DXF file to save to.
  8767. :param use_thread: if to be run in a separate thread
  8768. :return:
  8769. """
  8770. self.report_usage("export_dxf()")
  8771. if filename is None:
  8772. filename = self.defaults["global_last_save_folder"]
  8773. self.log.debug("export_dxf()")
  8774. try:
  8775. obj = self.collection.get_by_name(str(obj_name))
  8776. except Exception:
  8777. # TODO: The return behavior has not been established... should raise exception?
  8778. return "Could not retrieve object: %s" % obj_name
  8779. def make_dxf():
  8780. try:
  8781. dxf_code = obj.export_dxf()
  8782. dxf_code.saveas(filename)
  8783. if self.defaults["global_open_style"] is False:
  8784. self.file_opened.emit("DXF", filename)
  8785. self.file_saved.emit("DXF", filename)
  8786. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  8787. except Exception:
  8788. return 'fail'
  8789. if use_thread is True:
  8790. with self.proc_container.new(_("Exporting DXF")) as proc:
  8791. def job_thread_exc(app_obj):
  8792. ret_dxf_val = make_dxf()
  8793. if ret_dxf_val == 'fail':
  8794. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8795. return
  8796. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8797. else:
  8798. ret = make_dxf()
  8799. if ret == 'fail':
  8800. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8801. return
  8802. def import_svg(self, filename, geo_type='geometry', outname=None):
  8803. """
  8804. Adds a new Geometry Object to the projects and populates
  8805. it with shapes extracted from the SVG file.
  8806. :param filename: Path to the SVG file.
  8807. :param geo_type: Type of FlatCAM object that will be created from SVG
  8808. :param outname:
  8809. :return:
  8810. """
  8811. self.report_usage("import_svg()")
  8812. log.debug("App.import_svg()")
  8813. obj_type = ""
  8814. if geo_type is None or geo_type == "geometry":
  8815. obj_type = "geometry"
  8816. elif geo_type == "gerber":
  8817. obj_type = "gerber"
  8818. else:
  8819. self.inform.emit('[ERROR_NOTCL] %s' %
  8820. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8821. return
  8822. units = self.defaults['units'].upper()
  8823. def obj_init(geo_obj, app_obj):
  8824. geo_obj.import_svg(filename, obj_type, units=units)
  8825. geo_obj.multigeo = False
  8826. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  8827. with self.proc_container.new(_("Importing SVG")) as proc:
  8828. # Object name
  8829. name = outname or filename.split('/')[-1].split('\\')[-1]
  8830. self.new_object(obj_type, name, obj_init, autoselected=False)
  8831. # Register recent file
  8832. self.file_opened.emit("svg", filename)
  8833. # GUI feedback
  8834. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8835. def import_dxf(self, filename, geo_type='geometry', outname=None):
  8836. """
  8837. Adds a new Geometry Object to the projects and populates
  8838. it with shapes extracted from the DXF file.
  8839. :param filename: Path to the DXF file.
  8840. :param geo_type: Type of FlatCAM object that will be created from DXF
  8841. :param outname:
  8842. :type putname: str
  8843. :return:
  8844. """
  8845. self.report_usage("import_dxf()")
  8846. obj_type = ""
  8847. if geo_type is None or geo_type == "geometry":
  8848. obj_type = "geometry"
  8849. elif geo_type == "gerber":
  8850. obj_type = geo_type
  8851. else:
  8852. self.inform.emit('[ERROR_NOTCL] %s' %
  8853. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8854. return
  8855. units = self.defaults['units'].upper()
  8856. def obj_init(geo_obj, app_obj):
  8857. geo_obj.import_dxf(filename, obj_type, units=units)
  8858. geo_obj.multigeo = False
  8859. with self.proc_container.new(_("Importing DXF")) as proc:
  8860. # Object name
  8861. name = outname or filename.split('/')[-1].split('\\')[-1]
  8862. self.new_object(obj_type, name, obj_init, autoselected=False)
  8863. self.progress.emit(20)
  8864. # Register recent file
  8865. self.file_opened.emit("dxf", filename)
  8866. # GUI feedback
  8867. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8868. self.progress.emit(100)
  8869. def open_gerber(self, filename, outname=None):
  8870. """
  8871. Opens a Gerber file, parses it and creates a new object for
  8872. it in the program. Thread-safe.
  8873. :param outname: Name of the resulting object. None causes the
  8874. name to be that of the file.
  8875. :param filename: Gerber file filename
  8876. :type filename: str
  8877. :return: None
  8878. """
  8879. # How the object should be initialized
  8880. def obj_init(gerber_obj, app_obj):
  8881. assert isinstance(gerber_obj, FlatCAMGerber), \
  8882. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  8883. # Opening the file happens here
  8884. try:
  8885. gerber_obj.parse_file(filename)
  8886. except IOError:
  8887. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8888. return "fail"
  8889. except ParseError as err:
  8890. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8891. app_obj.log.error(str(err))
  8892. return "fail"
  8893. except Exception as e:
  8894. log.debug("App.open_gerber() --> %s" % str(e))
  8895. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8896. msg += traceback.format_exc()
  8897. app_obj.inform.emit(msg)
  8898. return "fail"
  8899. if gerber_obj.is_empty():
  8900. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  8901. _("Object is not Gerber file or empty. Aborting object creation."))
  8902. return "fail"
  8903. App.log.debug("open_gerber()")
  8904. with self.proc_container.new(_("Opening Gerber")) as proc:
  8905. # Object name
  8906. name = outname or filename.split('/')[-1].split('\\')[-1]
  8907. # # ## Object creation # ##
  8908. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  8909. if ret == 'fail':
  8910. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open Gerber failed. Probable not a Gerber file.'))
  8911. return 'fail'
  8912. # Register recent file
  8913. self.file_opened.emit("gerber", filename)
  8914. # GUI feedback
  8915. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8916. def open_excellon(self, filename, outname=None, plot=True):
  8917. """
  8918. Opens an Excellon file, parses it and creates a new object for
  8919. it in the program. Thread-safe.
  8920. :param outname: Name of the resulting object. None causes the
  8921. name to be that of the file.
  8922. :param filename: Excellon file filename
  8923. :type filename: str
  8924. :return: None
  8925. """
  8926. App.log.debug("open_excellon()")
  8927. # How the object should be initialized
  8928. def obj_init(excellon_obj, app_obj):
  8929. # self.progress.emit(20)
  8930. try:
  8931. ret = excellon_obj.parse_file(filename=filename)
  8932. if ret == "fail":
  8933. log.debug("Excellon parsing failed.")
  8934. self.inform.emit('[ERROR_NOTCL] %s' %
  8935. _("This is not Excellon file."))
  8936. return "fail"
  8937. except IOError:
  8938. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8939. (_("Cannot open file"), filename))
  8940. log.debug("Could not open Excellon object.")
  8941. self.progress.emit(0) # TODO: self and app_bjj mixed
  8942. return "fail"
  8943. except Exception:
  8944. msg = '[ERROR_NOTCL] %s' % \
  8945. _("An internal error has occurred. See shell.\n")
  8946. msg += traceback.format_exc()
  8947. app_obj.inform.emit(msg)
  8948. return "fail"
  8949. ret = excellon_obj.create_geometry()
  8950. if ret == 'fail':
  8951. log.debug("Could not create geometry for Excellon object.")
  8952. return "fail"
  8953. for tool in excellon_obj.tools:
  8954. if excellon_obj.tools[tool]['solid_geometry']:
  8955. return
  8956. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8957. (_("No geometry found in file"), filename))
  8958. return "fail"
  8959. with self.proc_container.new(_("Opening Excellon.")):
  8960. # Object name
  8961. name = outname or filename.split('/')[-1].split('\\')[-1]
  8962. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8963. if ret_val == 'fail':
  8964. self.inform.emit('[ERROR_NOTCL] %s' %
  8965. _('Open Excellon file failed. Probable not an Excellon file.'))
  8966. return
  8967. # Register recent file
  8968. self.file_opened.emit("excellon", filename)
  8969. # GUI feedback
  8970. self.inform.emit('[success] %s: %s' %
  8971. (_("Opened"), filename))
  8972. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True):
  8973. """
  8974. Opens a G-gcode file, parses it and creates a new object for
  8975. it in the program. Thread-safe.
  8976. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8977. :param filename: G-code file filename
  8978. :type filename: str
  8979. :return: None
  8980. """
  8981. App.log.debug("open_gcode()")
  8982. # How the object should be initialized
  8983. def obj_init(job_obj, app_obj_):
  8984. """
  8985. :param job_obj: the resulting object
  8986. :type app_obj_: App
  8987. """
  8988. assert isinstance(app_obj_, App), \
  8989. "Initializer expected App, got %s" % type(app_obj_)
  8990. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  8991. try:
  8992. f = open(filename)
  8993. gcode = f.read()
  8994. f.close()
  8995. except IOError:
  8996. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  8997. (_("Failed to open"), filename))
  8998. return "fail"
  8999. job_obj.gcode = gcode
  9000. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  9001. if gcode_ret == "fail":
  9002. self.inform.emit('[ERROR_NOTCL] %s' %
  9003. _("This is not GCODE"))
  9004. return "fail"
  9005. job_obj.create_geometry()
  9006. with self.proc_container.new(_("Opening G-Code.")):
  9007. # Object name
  9008. name = outname or filename.split('/')[-1].split('\\')[-1]
  9009. # New object creation and file processing
  9010. obj_ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  9011. if obj_ret == 'fail':
  9012. self.inform.emit('[ERROR_NOTCL] %s' %
  9013. _("Failed to create CNCJob Object. Probable not a GCode file. "
  9014. "Try to load it from File menu.\n "
  9015. "Attempting to create a FlatCAM CNCJob Object from "
  9016. "G-Code file failed during processing"))
  9017. return "fail"
  9018. # Register recent file
  9019. self.file_opened.emit("cncjob", filename)
  9020. # GUI feedback
  9021. self.inform.emit('[success] %s: %s' %
  9022. (_("Opened"), filename))
  9023. def open_script(self, filename, outname=None, silent=False):
  9024. """
  9025. Opens a Script file, parses it and creates a new object for
  9026. it in the program. Thread-safe.
  9027. :param outname: Name of the resulting object. None causes the name to be that of the file.
  9028. :param filename: Script file filename
  9029. :type filename: str
  9030. :return: None
  9031. """
  9032. App.log.debug("open_script()")
  9033. with self.proc_container.new(_("Opening TCL Script...")):
  9034. try:
  9035. with open(filename, "r") as opened_script:
  9036. script_content = opened_script.readlines()
  9037. script_content = ''.join(script_content)
  9038. if silent is False:
  9039. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  9040. except Exception as e:
  9041. log.debug("App.open_script() -> %s" % str(e))
  9042. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to open TCL Script."))
  9043. return
  9044. # Object name
  9045. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  9046. # New object creation and file processing
  9047. self.on_filenewscript(name=script_name, text=script_content)
  9048. # Register recent file
  9049. self.file_opened.emit("script", filename)
  9050. # GUI feedback
  9051. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9052. def open_config_file(self, filename, run_from_arg=None):
  9053. """
  9054. Loads a config file from the specified file.
  9055. :param filename: Name of the file from which to load.
  9056. :type filename: str
  9057. :return: None
  9058. """
  9059. App.log.debug("Opening config file: " + filename)
  9060. if run_from_arg:
  9061. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  9062. "Canvas initialization finished in"), '%.2f' % self.used_time,
  9063. _("Opening FlatCAM Config file.")),
  9064. alignment=Qt.AlignBottom | Qt.AlignLeft,
  9065. color=QtGui.QColor("gray"))
  9066. # # add the tab if it was closed
  9067. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  9068. # # first clear previous text in text editor (if any)
  9069. # self.ui.text_editor_tab.code_editor.clear()
  9070. #
  9071. # # Switch plot_area to CNCJob tab
  9072. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  9073. # close the Code editor if already open
  9074. if self.toggle_codeeditor:
  9075. self.on_toggle_code_editor()
  9076. self.on_toggle_code_editor()
  9077. try:
  9078. if filename:
  9079. f = QtCore.QFile(filename)
  9080. if f.open(QtCore.QIODevice.ReadOnly):
  9081. stream = QtCore.QTextStream(f)
  9082. code_edited = stream.readAll()
  9083. self.text_editor_tab.code_editor.setPlainText(code_edited)
  9084. f.close()
  9085. except IOError:
  9086. App.log.error("Failed to open config file: %s" % filename)
  9087. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9088. (_("Failed to open config file"), filename))
  9089. return
  9090. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  9091. """
  9092. Loads a project from the specified file.
  9093. 1) Loads and parses file
  9094. 2) Registers the file as recently opened.
  9095. 3) Calls on_file_new()
  9096. 4) Updates options
  9097. 5) Calls new_object() with the object's from_dict() as init method.
  9098. 6) Calls plot_all() if plot=True
  9099. :param filename: Name of the file from which to load.
  9100. :type filename: str
  9101. :param run_from_arg: True if run for arguments
  9102. :param plot: If True plot all objects in the project
  9103. :param cli: run from command line
  9104. :return: None
  9105. """
  9106. App.log.debug("Opening project: " + filename)
  9107. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9108. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9109. if cli is None:
  9110. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  9111. if run_from_arg:
  9112. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  9113. "Canvas initialization finished in"), '%.2f' % self.used_time,
  9114. _("Opening FlatCAM Project file.")),
  9115. alignment=Qt.AlignBottom | Qt.AlignLeft,
  9116. color=QtGui.QColor("gray"))
  9117. # Open and parse an uncompressed Project file
  9118. try:
  9119. f = open(filename, 'r')
  9120. except IOError:
  9121. App.log.error("Failed to open project file: %s" % filename)
  9122. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9123. (_("Failed to open project file"), filename))
  9124. return
  9125. try:
  9126. d = json.load(f, object_hook=dict2obj)
  9127. except Exception as e:
  9128. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  9129. (filename, str(e)))
  9130. f.close()
  9131. # Open and parse a compressed Project file
  9132. try:
  9133. with lzma.open(filename) as f:
  9134. file_content = f.read().decode('utf-8')
  9135. d = json.loads(file_content, object_hook=dict2obj)
  9136. except Exception as e:
  9137. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  9138. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9139. (_("Failed to open project file"), filename))
  9140. return
  9141. # Clear the current project
  9142. # # NOT THREAD SAFE # ##
  9143. if run_from_arg is True:
  9144. pass
  9145. elif cli is True:
  9146. self.delete_selection_shape()
  9147. else:
  9148. self.on_file_new()
  9149. # Project options
  9150. self.options.update(d['options'])
  9151. self.project_filename = filename
  9152. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9153. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9154. if cli is None:
  9155. self.set_screen_units(self.options["units"])
  9156. # Re create objects
  9157. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  9158. for obj in d['objs']:
  9159. def obj_init(obj_inst, app_inst):
  9160. obj_inst.from_dict(obj)
  9161. App.log.debug("Recreating from opened project an %s object: %s" %
  9162. (obj['kind'].capitalize(), obj['options']['name']))
  9163. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9164. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9165. if cli is None:
  9166. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  9167. obj['kind'].upper(),
  9168. obj['options']['name']
  9169. )
  9170. )
  9171. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  9172. self.inform.emit('[success] %s: %s' %
  9173. (_("Project loaded from"), filename))
  9174. self.should_we_save = False
  9175. self.file_opened.emit("project", filename)
  9176. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9177. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9178. if cli is None:
  9179. self.set_ui_title(name=self.project_filename)
  9180. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  9181. def propagate_defaults(self, silent=False):
  9182. """
  9183. This method is used to set default values in classes. It's
  9184. an alternative to project options but allows the use
  9185. of values invisible to the user.
  9186. :return: None
  9187. """
  9188. if silent is False:
  9189. self.log.debug("propagate_defaults()")
  9190. # Which objects to update the given parameters.
  9191. routes = {
  9192. "global_zdownrate": CNCjob,
  9193. "excellon_zeros": Excellon,
  9194. "excellon_format_upper_in": Excellon,
  9195. "excellon_format_lower_in": Excellon,
  9196. "excellon_format_upper_mm": Excellon,
  9197. "excellon_format_lower_mm": Excellon,
  9198. "excellon_units": Excellon,
  9199. "gerber_use_buffer_for_union": Gerber,
  9200. "geometry_multidepth": Geometry
  9201. }
  9202. for param in routes:
  9203. if param in routes[param].defaults:
  9204. try:
  9205. routes[param].defaults[param] = self.defaults[param]
  9206. if silent is False:
  9207. self.log.debug(" " + param + " OK")
  9208. except KeyError:
  9209. if silent is False:
  9210. self.log.debug("FlatCAMApp.propagate_defaults() --> ERROR: " + param + " not in defaults.")
  9211. else:
  9212. # Try extracting the name:
  9213. # classname_param here is param in the object
  9214. if param.find(routes[param].__name__.lower() + "_") == 0:
  9215. p = param[len(routes[param].__name__) + 1:]
  9216. if p in routes[param].defaults:
  9217. routes[param].defaults[p] = self.defaults[param]
  9218. if silent is False:
  9219. self.log.debug(" " + param + " OK!")
  9220. def plot_all(self, zoom=True):
  9221. """
  9222. Re-generates all plots from all objects.
  9223. :return: None
  9224. """
  9225. self.log.debug("Plot_all()")
  9226. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  9227. for obj in self.collection.get_list():
  9228. def worker_task(obj):
  9229. with self.proc_container.new("Plotting"):
  9230. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  9231. if zoom:
  9232. self.object_plotted.emit(obj)
  9233. # Send to worker
  9234. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  9235. def register_folder(self, filename):
  9236. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  9237. def register_save_folder(self, filename):
  9238. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  9239. def set_progress_bar(self, percentage, text=""):
  9240. self.ui.progress_bar.setValue(int(percentage))
  9241. def setup_shell(self):
  9242. """
  9243. Creates shell functions. Runs once at startup.
  9244. :return: None
  9245. """
  9246. self.log.debug("setup_shell()")
  9247. def shelp(p=None):
  9248. if not p:
  9249. return _("Available commands:\n") + \
  9250. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  9251. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  9252. if p not in commands:
  9253. return "Unknown command: %s" % p
  9254. return commands[p]["help"]
  9255. # --- Migrated to new architecture ---
  9256. # def options(name):
  9257. # ops = self.collection.get_by_name(str(name)).options
  9258. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  9259. def h(*args):
  9260. """
  9261. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  9262. and standalone parameters into list.
  9263. """
  9264. kwa = {}
  9265. a = []
  9266. n = len(args)
  9267. name = None
  9268. for i in range(n):
  9269. match = re.search(r'^-([a-zA-Z].*)', args[i])
  9270. if match:
  9271. assert name is None
  9272. name = match.group(1)
  9273. continue
  9274. if name is None:
  9275. a.append(args[i])
  9276. else:
  9277. kwa[name] = args[i]
  9278. name = None
  9279. return a, kwa
  9280. @contextmanager
  9281. def wait_signal(signal, timeout=10000):
  9282. """
  9283. Block loop until signal emitted, timeout (ms) elapses
  9284. or unhandled exception happens in a thread.
  9285. :param timeout: time after which the loop is exited
  9286. :param signal: Signal to wait for.
  9287. """
  9288. loop = QtCore.QEventLoop()
  9289. # Normal termination
  9290. signal.connect(loop.quit)
  9291. # Termination by exception in thread
  9292. self.thread_exception.connect(loop.quit)
  9293. status = {'timed_out': False}
  9294. def report_quit():
  9295. status['timed_out'] = True
  9296. loop.quit()
  9297. yield
  9298. # Temporarily change how exceptions are managed.
  9299. oeh = sys.excepthook
  9300. ex = []
  9301. def except_hook(type_, value, traceback_):
  9302. ex.append(value)
  9303. oeh(type_, value, traceback_)
  9304. sys.excepthook = except_hook
  9305. # Terminate on timeout
  9306. if timeout is not None:
  9307. QtCore.QTimer.singleShot(timeout, report_quit)
  9308. # # ## Block ## ##
  9309. loop.exec_()
  9310. # Restore exception management
  9311. sys.excepthook = oeh
  9312. if ex:
  9313. self.raiseTclError(str(ex[0]))
  9314. if status['timed_out']:
  9315. raise Exception('Timed out!')
  9316. def make_docs():
  9317. output = ''
  9318. import collections
  9319. od = collections.OrderedDict(sorted(commands.items()))
  9320. for cmd_, val in od.items():
  9321. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  9322. t = val['help']
  9323. usage_i = t.find('>')
  9324. if usage_i < 0:
  9325. expl = t
  9326. output += expl + '\n\n'
  9327. continue
  9328. expl = t[:usage_i - 1]
  9329. output += expl + '\n\n'
  9330. end_usage_i = t[usage_i:].find('\n')
  9331. if end_usage_i < 0:
  9332. end_usage_i = len(t[usage_i:])
  9333. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  9334. else:
  9335. extras = t[usage_i+end_usage_i+1:]
  9336. parts = [s.strip() for s in extras.split('\n')]
  9337. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  9338. for p in parts:
  9339. output += ' ' + p + '\n\n'
  9340. return output
  9341. '''
  9342. Howto implement TCL shell commands:
  9343. All parameters passed to command should be possible to set as None and test it afterwards.
  9344. This is because we need to see error caused in tcl,
  9345. if None value as default parameter is not allowed TCL will return empty error.
  9346. Use:
  9347. def mycommand(name=None,...):
  9348. Test it like this:
  9349. if name is None:
  9350. self.raise_tcl_error('Argument name is missing.')
  9351. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  9352. otherwise we will miss it and processing will silently continue.
  9353. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  9354. which is catched in exec_command and displayed in TCL shell console with red background.
  9355. Error in console is displayed with TCL trace.
  9356. This behavior works only within main thread,
  9357. errors with promissed tasks can be catched and detected only with log.
  9358. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  9359. TCL shell.
  9360. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  9361. '''
  9362. commands = {
  9363. 'help': {
  9364. 'fcn': shelp,
  9365. 'help': _("Shows list of commands.")
  9366. },
  9367. }
  9368. # Import/overwrite tcl commands as objects of TclCommand descendants
  9369. # This modifies the variable 'commands'.
  9370. tclCommands.register_all_commands(self, commands)
  9371. # Add commands to the tcl interpreter
  9372. for cmd in commands:
  9373. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  9374. # Make the tcl puts function return instead of print to stdout
  9375. self.tcl.eval('''
  9376. rename puts original_puts
  9377. proc puts {args} {
  9378. if {[llength $args] == 1} {
  9379. return "[lindex $args 0]"
  9380. } else {
  9381. eval original_puts $args
  9382. }
  9383. }
  9384. ''')
  9385. def setup_recent_items(self):
  9386. # TODO: Move this to constructor
  9387. icons = {
  9388. "gerber": "share/flatcam_icon16.png",
  9389. "excellon": "share/drill16.png",
  9390. 'geometry': "share/geometry16.png",
  9391. "cncjob": "share/cnc16.png",
  9392. "script": "share/script_new24.png",
  9393. "document": "share/notes16_1.png",
  9394. "project": "share/project16.png",
  9395. "svg": "share/geometry16.png",
  9396. "dxf": "share/dxf16.png",
  9397. "pdf": "share/pdf32.png",
  9398. "image": "share/image16.png"
  9399. }
  9400. openers = {
  9401. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  9402. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  9403. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  9404. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  9405. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  9406. "document": None,
  9407. 'project': self.open_project,
  9408. 'svg': self.import_svg,
  9409. 'dxf': self.import_dxf,
  9410. 'image': self.image_tool.import_image,
  9411. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  9412. }
  9413. # Open recent file for files
  9414. try:
  9415. f = open(self.data_path + '/recent.json')
  9416. except IOError:
  9417. App.log.error("Failed to load recent item list.")
  9418. self.inform.emit('[ERROR_NOTCL] %s' %
  9419. _("Failed to load recent item list."))
  9420. return
  9421. try:
  9422. self.recent = json.load(f)
  9423. except json.scanner.JSONDecodeError:
  9424. App.log.error("Failed to parse recent item list.")
  9425. self.inform.emit('[ERROR_NOTCL] %s' %
  9426. _("Failed to parse recent item list."))
  9427. f.close()
  9428. return
  9429. f.close()
  9430. # Open recent file for projects
  9431. try:
  9432. fp = open(self.data_path + '/recent_projects.json')
  9433. except IOError:
  9434. App.log.error("Failed to load recent project item list.")
  9435. self.inform.emit('[ERROR_NOTCL] %s' %
  9436. _("Failed to load recent projects item list."))
  9437. return
  9438. try:
  9439. self.recent_projects = json.load(fp)
  9440. except json.scanner.JSONDecodeError:
  9441. App.log.error("Failed to parse recent project item list.")
  9442. self.inform.emit('[ERROR_NOTCL] %s' %
  9443. _("Failed to parse recent project item list."))
  9444. fp.close()
  9445. return
  9446. fp.close()
  9447. # Closure needed to create callbacks in a loop.
  9448. # Otherwise late binding occurs.
  9449. def make_callback(func, fname):
  9450. def opener():
  9451. func(fname)
  9452. return opener
  9453. def reset_recent_files():
  9454. # Reset menu
  9455. self.ui.recent.clear()
  9456. self.recent = []
  9457. try:
  9458. ff = open(self.data_path + '/recent.json', 'w')
  9459. except IOError:
  9460. App.log.error("Failed to open recent items file for writing.")
  9461. return
  9462. json.dump(self.recent, ff)
  9463. def reset_recent_projects():
  9464. # Reset menu
  9465. self.ui.recent_projects.clear()
  9466. self.recent_projects = []
  9467. try:
  9468. fp = open(self.data_path + '/recent_projects.json', 'w')
  9469. except IOError:
  9470. App.log.error("Failed to open recent projects items file for writing.")
  9471. return
  9472. json.dump(self.recent, fp)
  9473. # Reset menu
  9474. self.ui.recent.clear()
  9475. self.ui.recent_projects.clear()
  9476. # Create menu items for projects
  9477. for recent in self.recent_projects:
  9478. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9479. if recent['kind'] == 'project':
  9480. try:
  9481. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9482. # Attach callback
  9483. o = make_callback(openers[recent["kind"]], recent['filename'])
  9484. action.triggered.connect(o)
  9485. self.ui.recent_projects.addAction(action)
  9486. except KeyError:
  9487. App.log.error("Unsupported file type: %s" % recent["kind"])
  9488. # Last action in Recent Files menu is one that Clear the content
  9489. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent projects")), self)
  9490. clear_action_proj.triggered.connect(reset_recent_projects)
  9491. self.ui.recent_projects.addSeparator()
  9492. self.ui.recent_projects.addAction(clear_action_proj)
  9493. # Create menu items for files
  9494. for recent in self.recent:
  9495. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9496. if recent['kind'] != 'project':
  9497. try:
  9498. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9499. # Attach callback
  9500. o = make_callback(openers[recent["kind"]], recent['filename'])
  9501. action.triggered.connect(o)
  9502. self.ui.recent.addAction(action)
  9503. except KeyError:
  9504. App.log.error("Unsupported file type: %s" % recent["kind"])
  9505. # Last action in Recent Files menu is one that Clear the content
  9506. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  9507. clear_action.triggered.connect(reset_recent_files)
  9508. self.ui.recent.addSeparator()
  9509. self.ui.recent.addAction(clear_action)
  9510. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  9511. # self.ui.menufilerecent.set_submenu(recent_menu)
  9512. # recent_menu.show_all()
  9513. # self.ui.recent.show()
  9514. self.log.debug("Recent items list has been populated.")
  9515. def setup_component_editor(self):
  9516. # label = QtWidgets.QLabel("Choose an item from Project")
  9517. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  9518. sel_title = QtWidgets.QTextEdit(
  9519. _('<b>Shortcut Key List</b>'))
  9520. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  9521. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  9522. settings = QSettings("Open Source", "FlatCAM")
  9523. if settings.contains("notebook_font_size"):
  9524. fsize = settings.value('notebook_font_size', type=int)
  9525. else:
  9526. fsize = 12
  9527. tsize = fsize + int(fsize / 2)
  9528. # selected_text = (_('''
  9529. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  9530. #
  9531. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  9532. # The normal flow when working in FlatCAM is the following:</span></p>
  9533. #
  9534. # <ol>
  9535. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  9536. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  9537. # even dragging and dropping the files on the GUI.<br />
  9538. # <br />
  9539. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  9540. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  9541. # &nbsp;</li>
  9542. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  9543. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  9544. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  9545. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  9546. # <br />
  9547. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  9548. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  9549. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  9550. # it even if it was out of focus.<br />
  9551. # <br />
  9552. # You can change the parameters in this screen and the flow direction is like this:<br />
  9553. # <br />
  9554. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  9555. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  9556. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  9557. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  9558. # </ol>
  9559. #
  9560. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  9561. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  9562. # <strong>F3</strong>.</span></p>
  9563. #
  9564. # ''').format(fsize=fsize, tsize=tsize))
  9565. selected_text = '''
  9566. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  9567. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  9568. {s1}</span></p>
  9569. <ol>
  9570. <li><span style="font-size:{fsize}px">{s2}<br />
  9571. <br />
  9572. {s3}</span><br />
  9573. &nbsp;</li>
  9574. <li><span style="font-size:{fsize}px">{s4}<br />
  9575. &nbsp;</li>
  9576. <br />
  9577. <li><span style="font-size:{fsize}px">{s5}<br />
  9578. &nbsp;</li>
  9579. <br />
  9580. <li><span style="font-size:{fsize}px">{s6}<br />
  9581. <br />
  9582. {s7}</span></li>
  9583. </ol>
  9584. <p><span style="font-size:{fsize}px">{s8}</span></p>
  9585. '''.format(
  9586. title=_("Selected Tab - Choose an Item from Project Tab"),
  9587. subtitle=_("Details"),
  9588. s1=_("The normal flow when working in FlatCAM is the following:"),
  9589. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  9590. "using either the toolbars, key shortcuts or even dragging and dropping the "
  9591. "files on the GUI."),
  9592. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  9593. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  9594. "actions offered within the app."),
  9595. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  9596. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  9597. "SELECTED TAB will be updated with the object properties according to its kind: "
  9598. "Gerber, Excellon, Geometry or CNCJob object."),
  9599. s5=_("If the selection of the object is done on the canvas by single click instead, "
  9600. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  9601. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  9602. "the SELECTED TAB and populate it even if it was out of focus."),
  9603. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  9604. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  9605. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  9606. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  9607. "(again, done in SELECTED TAB) --> Save GCode."),
  9608. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  9609. "or through its own key shortcut: <b>F3</b>."),
  9610. tsize=tsize,
  9611. fsize=fsize
  9612. )
  9613. sel_title.setText(selected_text)
  9614. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  9615. self.ui.selected_scroll_area.setWidget(sel_title)
  9616. def setup_obj_classes(self):
  9617. """
  9618. Sets up application specifics on the FlatCAMObj class.
  9619. :return: None
  9620. """
  9621. FlatCAMObj.app = self
  9622. ObjectCollection.app = self
  9623. Gerber.app = self
  9624. Excellon.app = self
  9625. Geometry.app = self
  9626. CNCjob.app = self
  9627. FCProcess.app = self
  9628. FCProcessContainer.app = self
  9629. def version_check(self):
  9630. """
  9631. Checks for the latest version of the program. Alerts the
  9632. user if theirs is outdated. This method is meant to be run
  9633. in a separate thread.
  9634. :return: None
  9635. """
  9636. self.log.debug("version_check()")
  9637. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  9638. full_url = App.version_url + \
  9639. "?s=" + str(self.defaults['global_serial']) + \
  9640. "&v=" + str(self.version) + \
  9641. "&os=" + str(self.os) + \
  9642. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  9643. else:
  9644. # no_stats dict; just so it won't break things on website
  9645. no_ststs_dict = {}
  9646. no_ststs_dict["global_ststs"] = {}
  9647. full_url = App.version_url + \
  9648. "?s=" + str(self.defaults['global_serial']) + \
  9649. "&v=" + str(self.version) + \
  9650. "&os=" + str(self.os) + \
  9651. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  9652. App.log.debug("Checking for updates @ %s" % full_url)
  9653. # ## Get the data
  9654. try:
  9655. f = urllib.request.urlopen(full_url)
  9656. except Exception:
  9657. # App.log.warning("Failed checking for latest version. Could not connect.")
  9658. self.log.warning("Failed checking for latest version. Could not connect.")
  9659. self.inform.emit('[WARNING_NOTCL] %s' %
  9660. _("Failed checking for latest version. Could not connect."))
  9661. return
  9662. try:
  9663. data = json.load(f)
  9664. except Exception as e:
  9665. App.log.error("Could not parse information about latest version.")
  9666. self.inform.emit('[ERROR_NOTCL] %s' %
  9667. _("Could not parse information about latest version."))
  9668. App.log.debug("json.load(): %s" % str(e))
  9669. f.close()
  9670. return
  9671. f.close()
  9672. # ## Latest version?
  9673. if self.version >= data["version"]:
  9674. App.log.debug("FlatCAM is up to date!")
  9675. self.inform.emit('[success] %s' %
  9676. _("FlatCAM is up to date!"))
  9677. return
  9678. App.log.debug("Newer version available.")
  9679. self.message.emit(
  9680. _("Newer Version Available"),
  9681. _("There is a newer version of FlatCAM available for download:\n\n") +
  9682. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  9683. _("info")
  9684. )
  9685. def on_plotcanvas_setup(self, container=None):
  9686. """
  9687. This is doing the setup for the plot area (VisPy canvas)
  9688. :param container: widget where to install the canvas
  9689. :return: None
  9690. """
  9691. if container:
  9692. plot_container = container
  9693. else:
  9694. plot_container = self.ui.right_layout
  9695. if self.is_legacy is False:
  9696. self.plotcanvas = PlotCanvas(plot_container, self)
  9697. else:
  9698. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  9699. # So it can receive key presses
  9700. self.plotcanvas.native.setFocus()
  9701. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  9702. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  9703. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  9704. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  9705. # Keys over plot enabled
  9706. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  9707. if self.defaults['global_cursor_type'] == 'small':
  9708. self.app_cursor = self.plotcanvas.new_cursor()
  9709. else:
  9710. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  9711. if self.ui.grid_snap_btn.isChecked():
  9712. self.app_cursor.enabled = True
  9713. else:
  9714. self.app_cursor.enabled = False
  9715. if self.is_legacy is False:
  9716. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  9717. else:
  9718. # will use the default Matplotlib axes
  9719. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  9720. def on_zoom_fit(self, event):
  9721. """
  9722. Callback for zoom-out request. This can be either from the corresponding
  9723. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  9724. with axes limits from the geometry bounds of all objects.
  9725. :param event: Ignored.
  9726. :return: None
  9727. """
  9728. if self.is_legacy is False:
  9729. self.plotcanvas.fit_view()
  9730. else:
  9731. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  9732. width = xmax - xmin
  9733. height = ymax - ymin
  9734. xmin -= 0.05 * width
  9735. xmax += 0.05 * width
  9736. ymin -= 0.05 * height
  9737. ymax += 0.05 * height
  9738. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  9739. def on_zoom_in(self):
  9740. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  9741. def on_zoom_out(self):
  9742. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  9743. def disable_all_plots(self):
  9744. self.report_usage("disable_all_plots()")
  9745. self.disable_plots(self.collection.get_list())
  9746. self.inform.emit('[success] %s' %
  9747. _("All plots disabled."))
  9748. def disable_other_plots(self):
  9749. self.report_usage("disable_other_plots()")
  9750. self.disable_plots(self.collection.get_non_selected())
  9751. self.inform.emit('[success] %s' %
  9752. _("All non selected plots disabled."))
  9753. def enable_all_plots(self):
  9754. self.report_usage("enable_all_plots()")
  9755. self.enable_plots(self.collection.get_list())
  9756. self.inform.emit('[success] %s' %
  9757. _("All plots enabled."))
  9758. def on_enable_sel_plots(self):
  9759. log.debug("App.on_enable_sel_plot()")
  9760. object_list = self.collection.get_selected()
  9761. self.enable_plots(objects=object_list)
  9762. self.inform.emit('[success] %s' %
  9763. _("Selected plots enabled..."))
  9764. def on_disable_sel_plots(self):
  9765. log.debug("App.on_disable_sel_plot()")
  9766. # self.inform.emit(_("Disabling plots ..."))
  9767. object_list = self.collection.get_selected()
  9768. self.disable_plots(objects=object_list)
  9769. self.inform.emit('[success] %s' %
  9770. _("Selected plots disabled..."))
  9771. def enable_plots(self, objects):
  9772. """
  9773. Disables plots
  9774. :param objects: list of Objects to be enabled
  9775. :return:
  9776. """
  9777. log.debug("Enabling plots ...")
  9778. # self.inform.emit(_("Working ..."))
  9779. for obj in objects:
  9780. if obj.options['plot'] is False:
  9781. obj.options.set_change_callback(lambda x: None)
  9782. obj.options['plot'] = True
  9783. obj.options.set_change_callback(obj.on_options_change)
  9784. def worker_task(objs):
  9785. with self.proc_container.new(_("Enabling plots ...")):
  9786. for obj in objs:
  9787. # obj.options['plot'] = True
  9788. if isinstance(obj, FlatCAMCNCjob):
  9789. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  9790. else:
  9791. obj.plot(visible=True)
  9792. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9793. # self.plots_updated.emit()
  9794. def disable_plots(self, objects):
  9795. """
  9796. Disables plots
  9797. :param objects: list of Objects to be disabled
  9798. :return:
  9799. """
  9800. # if no objects selected then do nothing
  9801. if not self.collection.get_selected():
  9802. return
  9803. log.debug("Disabling plots ...")
  9804. # self.inform.emit(_("Working ..."))
  9805. for obj in objects:
  9806. if obj.options['plot'] is True:
  9807. obj.options.set_change_callback(lambda x: None)
  9808. obj.options['plot'] = False
  9809. obj.options.set_change_callback(obj.on_options_change)
  9810. try:
  9811. self.delete_selection_shape()
  9812. except Exception as e:
  9813. log.debug("App.disable_plots() --> %s" % str(e))
  9814. # self.plots_updated.emit()
  9815. def worker_task(objs):
  9816. with self.proc_container.new(_("Disabling plots ...")):
  9817. for obj in objs:
  9818. # obj.options['plot'] = True
  9819. if isinstance(obj, FlatCAMCNCjob):
  9820. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  9821. else:
  9822. obj.plot(visible=False)
  9823. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9824. def toggle_plots(self, objects):
  9825. """
  9826. Toggle plots visibility
  9827. :param objects: list of Objects for which to be toggled the visibility
  9828. :return:
  9829. """
  9830. # if no objects selected then do nothing
  9831. if not self.collection.get_selected():
  9832. return
  9833. log.debug("Toggling plots ...")
  9834. self.inform.emit(_("Working ..."))
  9835. for obj in objects:
  9836. if obj.options['plot'] is False:
  9837. obj.options['plot'] = True
  9838. else:
  9839. obj.options['plot'] = False
  9840. self.plots_updated.emit()
  9841. def clear_plots(self):
  9842. objects = self.collection.get_list()
  9843. for obj in objects:
  9844. obj.clear(obj == objects[-1])
  9845. # Clear pool to free memory
  9846. self.clear_pool()
  9847. def generate_cnc_job(self, objects):
  9848. self.report_usage("generate_cnc_job()")
  9849. # for obj in objects:
  9850. # obj.generatecncjob()
  9851. for obj in objects:
  9852. obj.on_generatecnc_button_click()
  9853. def save_project(self, filename, quit_action=False, silent=False):
  9854. """
  9855. Saves the current project to the specified file.
  9856. :param filename: Name of the file in which to save.
  9857. :type filename: str
  9858. :param quit_action: if the project saving will be followed by an app quit; boolean
  9859. :param silent: if True will not display status messages
  9860. :return: None
  9861. """
  9862. self.log.debug("save_project()")
  9863. self.save_in_progress = True
  9864. with self.proc_container.new(_("Saving FlatCAM Project")):
  9865. # Capture the latest changes
  9866. # Current object
  9867. try:
  9868. self.collection.get_active().read_form()
  9869. except Exception as e:
  9870. self.log.debug("There was no active object. %s" % str(e))
  9871. pass
  9872. # Serialize the whole project
  9873. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  9874. "options": self.options,
  9875. "version": self.version}
  9876. if self.defaults["global_save_compressed"] is True:
  9877. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  9878. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  9879. # # Write
  9880. f.write(g)
  9881. self.inform.emit('[success] %s: %s' %
  9882. (_("Project saved to"), filename))
  9883. else:
  9884. # Open file
  9885. try:
  9886. f = open(filename, 'w')
  9887. except IOError:
  9888. App.log.error("Failed to open file for saving: %s", filename)
  9889. return
  9890. # Write
  9891. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  9892. f.close()
  9893. # verification of the saved project
  9894. # Open and parse
  9895. try:
  9896. saved_f = open(filename, 'r')
  9897. except IOError:
  9898. if silent is False:
  9899. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9900. (_("Failed to verify project file"), filename, _("Retry to save it."))
  9901. )
  9902. return
  9903. try:
  9904. saved_d = json.load(saved_f, object_hook=dict2obj)
  9905. except Exception:
  9906. if silent is False:
  9907. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9908. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9909. )
  9910. f.close()
  9911. return
  9912. saved_f.close()
  9913. if silent is False:
  9914. if 'version' in saved_d:
  9915. self.inform.emit('[success] %s: %s' %
  9916. (_("Project saved to"), filename))
  9917. else:
  9918. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9919. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9920. )
  9921. tb_settings = QSettings("Open Source", "FlatCAM")
  9922. lock_state = self.ui.lock_action.isChecked()
  9923. tb_settings.setValue('toolbar_lock', lock_state)
  9924. # This will write the setting to the platform specific storage.
  9925. del tb_settings
  9926. # if quit:
  9927. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  9928. # t.start()
  9929. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  9930. def start_delayed_quit(self, delay, filename, should_quit=None):
  9931. """
  9932. :param delay: period of checking if project file size is more than zero; in seconds
  9933. :param filename: the name of the project file to be checked periodically for size more than zero
  9934. :param should_quit: if the task finished will be followed by an app quit; boolean
  9935. :return:
  9936. """
  9937. to_quit = should_quit
  9938. self.save_timer = QtCore.QTimer()
  9939. self.save_timer.setInterval(delay)
  9940. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  9941. self.save_timer.start()
  9942. def check_project_file_size(self, filename, should_quit=None):
  9943. """
  9944. :param filename: the name of the project file to be checked periodically for size more than zero
  9945. :param should_quit: will quit the app if True; boolean
  9946. :return:
  9947. """
  9948. try:
  9949. if os.stat(filename).st_size > 0:
  9950. self.save_in_progress = False
  9951. self.save_timer.stop()
  9952. if should_quit:
  9953. self.app_quit.emit()
  9954. except Exception:
  9955. traceback.print_exc()
  9956. def on_plotarea_tab_closed(self, tab_idx):
  9957. widget = self.ui.plot_tab_area.widget(tab_idx)
  9958. if widget is not None:
  9959. widget.deleteLater()
  9960. self.ui.plot_tab_area.removeTab(tab_idx)
  9961. def on_options_app2project(self):
  9962. """
  9963. Callback for Options->Transfer Options->App=>Project. Copies options
  9964. from application defaults to project defaults.
  9965. :return: None
  9966. """
  9967. self.report_usage("on_options_app2project")
  9968. self.defaults_read_form()
  9969. self.options.update(self.defaults)
  9970. # self.options_write_form()
  9971. class ArgsThread(QtCore.QObject):
  9972. open_signal = pyqtSignal(list)
  9973. start = pyqtSignal()
  9974. if sys.platform == 'win32':
  9975. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  9976. else:
  9977. address = ('/tmp/testipc', 'AF_UNIX')
  9978. def __init__(self):
  9979. super(ArgsThread, self).__init__()
  9980. self.start.connect(self.run)
  9981. def my_loop(self, address):
  9982. try:
  9983. listener = Listener(*address)
  9984. while True:
  9985. conn = listener.accept()
  9986. self.serve(conn)
  9987. except socket.error:
  9988. conn = Client(*address)
  9989. conn.send(sys.argv)
  9990. conn.send('close')
  9991. # close the current instance only if there are args
  9992. if len(sys.argv) > 1:
  9993. sys.exit()
  9994. def serve(self, conn):
  9995. while True:
  9996. msg = conn.recv()
  9997. if msg == 'close':
  9998. break
  9999. self.open_signal.emit(msg)
  10000. conn.close()
  10001. # the decorator is a must; without it this technique will not work unless the start signal is connected
  10002. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  10003. @pyqtSlot()
  10004. def run(self):
  10005. self.my_loop(self.address)
  10006. class GracefulException(Exception):
  10007. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  10008. def __init__(self):
  10009. super().__init__()
  10010. def __str__(self):
  10011. return '\n\n%s' % _("The user requested a graceful exit of the current task.")
  10012. # end of file