FlatCAMApp.py 541 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ###########################################################
  8. import urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import webbrowser
  12. import getopt
  13. import random
  14. import simplejson as json
  15. import lzma
  16. import threading
  17. import shutil
  18. from stat import S_IREAD, S_IRGRP, S_IROTH
  19. import subprocess
  20. import ctypes
  21. import tkinter as tk
  22. from PyQt5 import QtPrintSupport
  23. from contextlib import contextmanager
  24. import gc
  25. from xml.dom.minidom import parseString as parse_xml_string
  26. from multiprocessing.connection import Listener, Client
  27. from multiprocessing import Pool, cpu_count
  28. import socket
  29. from array import array
  30. import vispy.scene as scene
  31. # #######################################
  32. # # Imports part of FlatCAM ##
  33. # #######################################
  34. from ObjectCollection import *
  35. from FlatCAMObj import *
  36. from camlib import to_dict, dict2obj, ET, ParseError
  37. from flatcamGUI.PlotCanvas import *
  38. from flatcamGUI.PlotCanvasLegacy import *
  39. from flatcamGUI.FlatCAMGUI import *
  40. from FlatCAMCommon import LoudDict, BookmarkManager, ToolsDB
  41. from FlatCAMPostProc import load_postprocessors
  42. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  43. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  44. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  45. from flatcamEditors.FlatCAMTextEditor import TextEditor
  46. from FlatCAMProcess import *
  47. from FlatCAMWorkerStack import WorkerStack
  48. # from flatcamGUI.VisPyVisuals import Color
  49. from vispy.gloo.util import _screenshot
  50. from vispy.io import write_png
  51. from flatcamTools import *
  52. import tclCommands
  53. import gettext
  54. import FlatCAMTranslation as fcTranslate
  55. import builtins
  56. if sys.platform == 'win32':
  57. import winreg
  58. fcTranslate.apply_language('strings')
  59. if '_' not in builtins.__dict__:
  60. _ = gettext.gettext
  61. class App(QtCore.QObject):
  62. # ########################################
  63. # # App ###
  64. # ########################################
  65. """
  66. The main application class. The constructor starts the GUI.
  67. """
  68. # Get Cmd Line Options
  69. cmd_line_shellfile = ''
  70. cmd_line_shellvar = ''
  71. cmd_line_headless = None
  72. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  73. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  74. "FlatCam.py --headless=1"
  75. try:
  76. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  77. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  78. "shellvar=",
  79. "headless=",
  80. "multiprocessing-fork="])
  81. except getopt.GetoptError:
  82. print(cmd_line_help)
  83. sys.exit(2)
  84. for opt, arg in cmd_line_options:
  85. if opt == '-h':
  86. print(cmd_line_help)
  87. sys.exit()
  88. elif opt == '--shellfile':
  89. cmd_line_shellfile = arg
  90. elif opt == '--shellvar':
  91. cmd_line_shellvar = arg
  92. elif opt == '--headless':
  93. try:
  94. cmd_line_headless = eval(arg)
  95. except NameError:
  96. pass
  97. # ## Logging ###
  98. log = logging.getLogger('base')
  99. log.setLevel(logging.DEBUG)
  100. # log.setLevel(logging.WARNING)
  101. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  102. handler = logging.StreamHandler()
  103. handler.setFormatter(formatter)
  104. log.addHandler(handler)
  105. # ##########################################################################
  106. # ################## Version and VERSION DATE ##############################
  107. # ##########################################################################
  108. version = 8.99
  109. version_date = "2019/11/30"
  110. beta = True
  111. engine = '3D'
  112. # current date now
  113. date = str(datetime.today()).rpartition('.')[0]
  114. date = ''.join(c for c in date if c not in ':-')
  115. date = date.replace(' ', '_')
  116. # URL for update checks and statistics
  117. version_url = "http://flatcam.org/version"
  118. # App URL
  119. app_url = "http://flatcam.org"
  120. # Manual URL
  121. manual_url = "http://flatcam.org/manual/index.html"
  122. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  123. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  124. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  125. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  126. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  127. # this variable will hold the project status
  128. # if True it will mean that the project was modified and not saved
  129. should_we_save = False
  130. # flag is True if saving action has been triggered
  131. save_in_progress = False
  132. # ###########################################################################
  133. # ############################# Signals ################################
  134. # ###########################################################################
  135. # Inform the user
  136. # Handled by:
  137. # * App.info() --> Print on the status bar
  138. inform = QtCore.pyqtSignal(str)
  139. app_quit = QtCore.pyqtSignal()
  140. # General purpose background task
  141. worker_task = QtCore.pyqtSignal(dict)
  142. # File opened
  143. # Handled by:
  144. # * register_folder()
  145. # * register_recent()
  146. # Note: Setting the parameters to unicode does not seem
  147. # to have an effect. Then are received as Qstring
  148. # anyway.
  149. # File type and filename
  150. file_opened = QtCore.pyqtSignal(str, str)
  151. # File type and filename
  152. file_saved = QtCore.pyqtSignal(str, str)
  153. # Percentage of progress
  154. progress = QtCore.pyqtSignal(int)
  155. plots_updated = QtCore.pyqtSignal()
  156. # Emitted by new_object() and passes the new object as argument, plot flag.
  157. # on_object_created() adds the object to the collection, plots on appropriate flag
  158. # and emits new_object_available.
  159. object_created = QtCore.pyqtSignal(object, bool, bool)
  160. # Emitted when a object has been changed (like scaled, mirrored)
  161. object_changed = QtCore.pyqtSignal(object)
  162. # Emitted after object has been plotted.
  163. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  164. object_plotted = QtCore.pyqtSignal(object)
  165. # Emitted when a new object has been added or deleted from/to the collection
  166. object_status_changed = QtCore.pyqtSignal(object, str, str)
  167. message = QtCore.pyqtSignal(str, str, str)
  168. # Emmited when shell command is finished(one command only)
  169. shell_command_finished = QtCore.pyqtSignal(object)
  170. # Emitted when multiprocess pool has been recreated
  171. pool_recreated = QtCore.pyqtSignal(object)
  172. # Emitted when an unhandled exception happens
  173. # in the worker task.
  174. thread_exception = QtCore.pyqtSignal(object)
  175. # used to signal that there are arguments for the app
  176. args_at_startup = QtCore.pyqtSignal(list)
  177. # a reusable signal to replot a list of objects
  178. # should be disconnected after use so it can be reused
  179. replot_signal = pyqtSignal(list)
  180. def __init__(self, user_defaults=True):
  181. """
  182. Starts the application.
  183. :return: app
  184. :rtype: App
  185. """
  186. App.log.info("FlatCAM Starting...")
  187. self.main_thread = QtWidgets.QApplication.instance().thread()
  188. # ############################################################################
  189. # # ################# OS-specific ############################################
  190. # ############################################################################
  191. portable = False
  192. # Folder for user settings.
  193. if sys.platform == 'win32':
  194. # #########################################################################
  195. # Setup the listening thread for another instance launching with args #####
  196. # #########################################################################
  197. # make sure the thread is stored by using a self. otherwise it's garbage collected
  198. self.th = QtCore.QThread()
  199. self.th.start(priority=QtCore.QThread.LowestPriority)
  200. self.new_launch = ArgsThread()
  201. self.new_launch.open_signal[list].connect(self.on_startup_args)
  202. self.new_launch.moveToThread(self.th)
  203. self.new_launch.start.emit()
  204. from win32com.shell import shell, shellcon
  205. if platform.architecture()[0] == '32bit':
  206. App.log.debug("Win32!")
  207. else:
  208. App.log.debug("Win64!")
  209. # #########################################################################
  210. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  211. # #########################################################################
  212. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  213. try:
  214. with open(config_file, 'r'):
  215. pass
  216. except FileNotFoundError:
  217. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  218. try:
  219. with open(config_file, 'r') as f:
  220. try:
  221. for line in f:
  222. param = str(line).replace('\n', '').rpartition('=')
  223. if param[0] == 'portable':
  224. try:
  225. portable = eval(param[2])
  226. except NameError:
  227. portable = False
  228. if param[0] == 'headless':
  229. if param[2].lower() == 'true':
  230. self.cmd_line_headless = 1
  231. else:
  232. self.cmd_line_headless = None
  233. except Exception as e:
  234. log.debug('App.__init__() -->%s' % str(e))
  235. return
  236. except FileNotFoundError as e:
  237. log.debug(str(e))
  238. pass
  239. if portable is False:
  240. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  241. else:
  242. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  243. self.os = 'windows'
  244. else: # Linux/Unix/MacOS
  245. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  246. self.os = 'unix'
  247. # ##########################################################################
  248. # ################## Setup folders and files ###############################
  249. # ##########################################################################
  250. if not os.path.exists(self.data_path):
  251. os.makedirs(self.data_path)
  252. App.log.debug('Created data folder: ' + self.data_path)
  253. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  254. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  255. self.postprocessorpaths = os.path.join(self.data_path, 'postprocessors')
  256. if not os.path.exists(self.postprocessorpaths):
  257. os.makedirs(self.postprocessorpaths)
  258. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  259. # create tools_db.FlatConfig file if there is none
  260. try:
  261. f = open(self.data_path + '/tools_db.FlatConfig')
  262. f.close()
  263. except IOError:
  264. App.log.debug('Creating empty tool_db.FlatConfig')
  265. f = open(self.data_path + '/tools_db.FlatConfig', 'w')
  266. json.dump({}, f)
  267. f.close()
  268. # create current_defaults.FlatConfig file if there is none
  269. try:
  270. f = open(self.data_path + '/current_defaults.FlatConfig')
  271. f.close()
  272. except IOError:
  273. App.log.debug('Creating empty current_defaults.FlatConfig')
  274. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  275. json.dump({}, f)
  276. f.close()
  277. # create factory_defaults.FlatConfig file if there is none
  278. try:
  279. f = open(self.data_path + '/factory_defaults.FlatConfig')
  280. f.close()
  281. except IOError:
  282. App.log.debug('Creating empty factory_defaults.FlatConfig')
  283. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  284. json.dump({}, f)
  285. f.close()
  286. # create a recent files json file if there is none
  287. try:
  288. f = open(self.data_path + '/recent.json')
  289. f.close()
  290. except IOError:
  291. App.log.debug('Creating empty recent.json')
  292. f = open(self.data_path + '/recent.json', 'w')
  293. json.dump([], f)
  294. f.close()
  295. # create a recent projects json file if there is none
  296. try:
  297. fp = open(self.data_path + '/recent_projects.json')
  298. fp.close()
  299. except IOError:
  300. App.log.debug('Creating empty recent_projects.json')
  301. fp = open(self.data_path + '/recent_projects.json', 'w')
  302. json.dump([], fp)
  303. fp.close()
  304. # Application directory. CHDIR to it. Otherwise, trying to load
  305. # GUI icons will fail as their path is relative.
  306. # This will fail under cx_freeze ...
  307. self.app_home = os.path.dirname(os.path.realpath(__file__))
  308. App.log.debug("Application path is " + self.app_home)
  309. App.log.debug("Started in " + os.getcwd())
  310. # cx_freeze workaround
  311. if os.path.isfile(self.app_home):
  312. self.app_home = os.path.dirname(self.app_home)
  313. os.chdir(self.app_home)
  314. # #################################################################################
  315. # #################### DEFAULTS - PREFERENCES STORAGE #############################
  316. # #################################################################################
  317. self.defaults = LoudDict()
  318. self.defaults.update({
  319. # Global APP Preferences
  320. "first_run": True,
  321. "units": "IN",
  322. "global_serial": 0,
  323. "global_stats": {},
  324. "global_tabs_detachable": True,
  325. "global_graphic_engine": '3D',
  326. "global_app_level": 'b',
  327. "global_portable": False,
  328. "global_language": 'English',
  329. "global_version_check": True,
  330. "global_send_stats": True,
  331. "global_pan_button": '2',
  332. "global_mselect_key": 'Control',
  333. "global_project_at_startup": False,
  334. "global_systray_icon": True,
  335. "global_project_autohide": True,
  336. "global_toggle_tooltips": True,
  337. "global_worker_number": 2,
  338. "global_tolerance": 0.0002,
  339. "global_open_style": True,
  340. "global_delete_confirmation": True,
  341. "global_compression_level": 3,
  342. "global_save_compressed": True,
  343. "global_machinist_setting": False,
  344. # Global GUI Preferences
  345. "global_gridx": 0.0393701,
  346. "global_gridy": 0.0393701,
  347. "global_snap_max": 0.001968504,
  348. "global_workspace": False,
  349. "global_workspaceT": "A4",
  350. "global_workspace_orientation": 'p',
  351. "global_grid_context_menu": {
  352. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  353. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  354. },
  355. "global_plot_fill": '#BBF268BF',
  356. "global_plot_line": '#006E20BF',
  357. "global_sel_fill": '#a5a5ffbf',
  358. "global_sel_line": '#0000ffbf',
  359. "global_alt_sel_fill": '#BBF268BF',
  360. "global_alt_sel_line": '#006E20BF',
  361. "global_draw_color": '#FF0000',
  362. "global_sel_draw_color": '#0000FF',
  363. "global_proj_item_color": '#000000',
  364. "global_proj_item_dis_color": '#b7b7cb',
  365. "global_activity_icon": 'Ball green',
  366. "global_toolbar_view": 511,
  367. "global_background_timeout": 300000, # Default value is 5 minutes
  368. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  369. # (python trace only for unknown errors),
  370. # 1 = show trace(show trace always),
  371. # 2 = (For the future).
  372. # Persistence
  373. "global_last_folder": None,
  374. "global_last_save_folder": None,
  375. # Default window geometry
  376. "global_def_win_x": 100,
  377. "global_def_win_y": 100,
  378. "global_def_win_w": 1024,
  379. "global_def_win_h": 650,
  380. "global_def_notebook_width": 1,
  381. # Constants...
  382. "global_defaults_save_period_ms": 20000, # Time between default saves.
  383. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  384. "global_shell_at_startup": False, # Show the shell at startup.
  385. "global_recent_limit": 10, # Max. items in recent list.
  386. "global_bookmarks": dict(),
  387. "global_bookmarks_limit": 10,
  388. "fit_key": 'V',
  389. "zoom_out_key": '-',
  390. "zoom_in_key": '=',
  391. "grid_toggle_key": 'G',
  392. "global_zoom_ratio": 1.5,
  393. "global_point_clipboard_format": "(%.4f, %.4f)",
  394. "global_zdownrate": None,
  395. # General GUI Settings
  396. "global_theme": 'white',
  397. "global_hover": False,
  398. "global_selection_shape": True,
  399. "global_layout": "compact",
  400. "global_cursor_type": "small",
  401. "global_cursor_size": 20,
  402. # Gerber General
  403. "gerber_plot": True,
  404. "gerber_solid": True,
  405. "gerber_multicolored": False,
  406. "gerber_circle_steps": 128,
  407. "gerber_use_buffer_for_union": True,
  408. "gerber_def_units": 'IN',
  409. "gerber_def_zeros": 'L',
  410. "gerber_save_filters": "Gerber File (*.gbr);;Gerber File (*.bot);;Gerber File (*.bsm);;"
  411. "Gerber File (*.cmp);;Gerber File (*.crc);;Gerber File (*.crs);;"
  412. "Gerber File (*.gb0);;Gerber File (*.gb1);;Gerber File (*.gb2);;"
  413. "Gerber File (*.gb3);;Gerber File (*.gb4);;Gerber File (*.gb5);;"
  414. "Gerber File (*.gb6);;Gerber File (*.gb7);;Gerber File (*.gb8);;"
  415. "Gerber File (*.gb9);;Gerber File (*.gbd);;Gerber File (*.gbl);;"
  416. "Gerber File (*.gbo);;Gerber File (*.gbp);;Gerber File (*.gbs);;"
  417. "Gerber File (*.gdo);;Gerber File (*.ger);;Gerber File (*.gko);;"
  418. "Gerber File (*.gm1);;Gerber File (*.gm2);;Gerber File (*.gm3);;"
  419. "Gerber File (*.grb);;Gerber File (*.gtl);;Gerber File (*.gto);;"
  420. "Gerber File (*.gtp);;Gerber File (*.gts);;Gerber File (*.ly15);;"
  421. "Gerber File (*.ly2);;Gerber File (*.mil);;Gerber File (*.pho);;"
  422. "Gerber File (*.plc);;Gerber File (*.pls);;Gerber File (*.smb);;"
  423. "Gerber File (*.smt);;Gerber File (*.sol);;Gerber File (*.spb);;"
  424. "Gerber File (*.spt);;Gerber File (*.ssb);;Gerber File (*.sst);;"
  425. "Gerber File (*.stc);;Gerber File (*.sts);;Gerber File (*.top);;"
  426. "Gerber File (*.tsm);;Gerber File (*.art)"
  427. "All Files (*.*)",
  428. # Gerber Options
  429. "gerber_isotooldia": 0.00787402,
  430. "gerber_isopasses": 1,
  431. "gerber_isooverlap": 0.00393701,
  432. "gerber_milling_type": "cl",
  433. "gerber_combine_passes": False,
  434. "gerber_iso_scope": 'all',
  435. "gerber_noncoppermargin": 0.00393701,
  436. "gerber_noncopperrounded": False,
  437. "gerber_bboxmargin": 0.00393701,
  438. "gerber_bboxrounded": False,
  439. # Gerber Advanced Options
  440. "gerber_aperture_display": False,
  441. "gerber_aperture_scale_factor": 1.0,
  442. "gerber_aperture_buffer_factor": 0.0,
  443. "gerber_follow": False,
  444. "gerber_tool_type": 'circular',
  445. "gerber_vtipdia": 0.1,
  446. "gerber_vtipangle": 30,
  447. "gerber_vcutz": -0.05,
  448. "gerber_iso_type": "full",
  449. "gerber_buffering": "full",
  450. "gerber_simplification": False,
  451. "gerber_simp_tolerance": 0.0005,
  452. # Gerber Export
  453. "gerber_exp_units": 'IN',
  454. "gerber_exp_integer": 2,
  455. "gerber_exp_decimals": 4,
  456. "gerber_exp_zeros": 'L',
  457. # Gerber Editor
  458. "gerber_editor_sel_limit": 30,
  459. "gerber_editor_newcode": 10,
  460. "gerber_editor_newsize": 0.031496,
  461. "gerber_editor_newtype": 'C',
  462. "gerber_editor_newdim": "0.5, 0.5",
  463. "gerber_editor_array_size": 5,
  464. "gerber_editor_lin_axis": 'X',
  465. "gerber_editor_lin_pitch": 0.1,
  466. "gerber_editor_lin_angle": 0.0,
  467. "gerber_editor_circ_dir": 'CW',
  468. "gerber_editor_circ_angle": 0.0,
  469. "gerber_editor_scale_f": 1.0,
  470. "gerber_editor_buff_f": 0.01,
  471. "gerber_editor_ma_low": 0.0,
  472. "gerber_editor_ma_high": 1.0,
  473. # Excellon General
  474. "excellon_plot": True,
  475. "excellon_solid": True,
  476. "excellon_format_upper_in": 2,
  477. "excellon_format_lower_in": 4,
  478. "excellon_format_upper_mm": 3,
  479. "excellon_format_lower_mm": 3,
  480. "excellon_zeros": "L",
  481. "excellon_units": "INCH",
  482. "excellon_update": True,
  483. "excellon_optimization_type": 'B',
  484. "excellon_search_time": 3,
  485. "excellon_save_filters": "Excellon File (*.txt);;Excellon File (*.drd);;Excellon File (*.drl);;"
  486. "Excellon File (*.exc);;Excellon File (*.ncd);;Excellon File (*.tap);;"
  487. "Excellon File (*.xln);;All Files (*.*)",
  488. # Excellon Options
  489. "excellon_drillz": -0.0590551,
  490. "excellon_travelz": 0.0787402,
  491. "excellon_endz": 0.5,
  492. "excellon_feedrate": 3.14961,
  493. "excellon_spindlespeed": None,
  494. "excellon_dwell": False,
  495. "excellon_dwelltime": 1,
  496. "excellon_toolchange": False,
  497. "excellon_toolchangez": 0.5,
  498. "excellon_ppname_e": 'default',
  499. "excellon_tooldia": 0.0314961,
  500. "excellon_slot_tooldia": 0.0708661,
  501. "excellon_gcode_type": "drills",
  502. # Excellon Advanced Options
  503. "excellon_offset": 0.0,
  504. "excellon_toolchangexy": "0.0, 0.0",
  505. "excellon_startz": None,
  506. "excellon_feedrate_rapid": 31.4961,
  507. "excellon_z_pdepth": -0.02,
  508. "excellon_feedrate_probe": 3.14961,
  509. "excellon_spindledir": 'CW',
  510. "excellon_f_plunge": False,
  511. "excellon_f_retract": False,
  512. # Excellon Export
  513. "excellon_exp_units": 'INCH',
  514. "excellon_exp_format": 'ndec',
  515. "excellon_exp_integer": 2,
  516. "excellon_exp_decimals": 4,
  517. "excellon_exp_zeros": 'LZ',
  518. "excellon_exp_slot_type": 'routing',
  519. # Excellon Editor
  520. "excellon_editor_sel_limit": 30,
  521. "excellon_editor_newdia": 0.039,
  522. "excellon_editor_array_size": 5,
  523. "excellon_editor_lin_dir": 'X',
  524. "excellon_editor_lin_pitch": 0.1,
  525. "excellon_editor_lin_angle": 0.0,
  526. "excellon_editor_circ_dir": 'CW',
  527. "excellon_editor_circ_angle": 12,
  528. # Excellon Slots
  529. "excellon_editor_slot_direction": 'X',
  530. "excellon_editor_slot_angle": 0.0,
  531. "excellon_editor_slot_length": 5.0,
  532. # Excellon Slot Array
  533. "excellon_editor_slot_array_size": 5,
  534. "excellon_editor_slot_lin_dir": 'X',
  535. "excellon_editor_slot_lin_pitch": 0.1,
  536. "excellon_editor_slot_lin_angle": 0.0,
  537. "excellon_editor_slot_circ_dir": 'CW',
  538. "excellon_editor_slot_circ_angle": 0.0,
  539. # Geometry General
  540. "geometry_plot": True,
  541. "geometry_circle_steps": 128,
  542. "geometry_cnctooldia": "0.0944882",
  543. # Geometry Options
  544. "geometry_cutz": -0.0944882,
  545. "geometry_vtipdia": 0.1,
  546. "geometry_vtipangle": 30,
  547. "geometry_multidepth": False,
  548. "geometry_depthperpass": 0.0314961,
  549. "geometry_travelz": 0.0787402,
  550. "geometry_toolchange": False,
  551. "geometry_toolchangez": 0.5,
  552. "geometry_endz": 0.5,
  553. "geometry_feedrate": 3.14961,
  554. "geometry_feedrate_z": 3.14961,
  555. "geometry_spindlespeed": None,
  556. "geometry_dwell": False,
  557. "geometry_dwelltime": 1,
  558. "geometry_ppname_g": 'default',
  559. # Geometry Advanced Options
  560. "geometry_toolchangexy": "0.0, 0.0",
  561. "geometry_startz": None,
  562. "geometry_feedrate_rapid": 3.14961,
  563. "geometry_extracut": False,
  564. "geometry_z_pdepth": -0.02,
  565. "geometry_f_plunge": False,
  566. "geometry_spindledir": 'CW',
  567. "geometry_feedrate_probe": 3.14961,
  568. "geometry_segx": 0.0,
  569. "geometry_segy": 0.0,
  570. # Geometry Editor
  571. "geometry_editor_sel_limit": 30,
  572. "geometry_editor_milling_type": "cl",
  573. # CNC Job General
  574. "cncjob_plot": True,
  575. "cncjob_plot_kind": 'all',
  576. "cncjob_annotation": True,
  577. "cncjob_tooldia": 0.0393701,
  578. "cncjob_coords_type": "G90",
  579. "cncjob_coords_decimals": 4,
  580. "cncjob_fr_decimals": 2,
  581. "cncjob_steps_per_circle": 128,
  582. "cncjob_footer": False,
  583. "cncjob_line_ending": False,
  584. "cncjob_save_filters": "G-Code Files (*.nc);;G-Code Files (*.din);;G-Code Files (*.dnc);;"
  585. "G-Code Files (*.ecs);;G-Code Files (*.eia);;G-Code Files (*.fan);;"
  586. "G-Code Files (*.fgc);;G-Code Files (*.fnc);;G-Code Files (*.gc);;"
  587. "G-Code Files (*.gcd);;G-Code Files (*.gcode);;G-Code Files (*.h);;"
  588. "G-Code Files (*.hnc);;G-Code Files (*.i);;G-Code Files (*.min);;"
  589. "G-Code Files (*.mpf);;G-Code Files (*.mpr);;G-Code Files (*.cnc);;"
  590. "G-Code Files (*.ncc);;G-Code Files (*.ncg);;G-Code Files (*.ncp);;"
  591. "G-Code Files (*.ngc);;G-Code Files (*.out);;G-Code Files (*.ply);;"
  592. "G-Code Files (*.sbp);;G-Code Files (*.tap);;G-Code Files (*.xpi);;"
  593. "All Files (*.*)",
  594. # CNC Job Options
  595. "cncjob_prepend": "",
  596. "cncjob_append": "",
  597. # CNC Job Advanced Options
  598. "cncjob_toolchange_macro": "",
  599. "cncjob_toolchange_macro_enable": False,
  600. "cncjob_annotation_fontsize": 9,
  601. "cncjob_annotation_fontcolor": '#990000',
  602. # NCC Tool
  603. "tools_ncctools": "0.0393701, 0.019685",
  604. "tools_nccorder": 'rev',
  605. "tools_nccoverlap": 0.015748,
  606. "tools_nccmargin": 0.0393701,
  607. "tools_nccmethod": "seed",
  608. "tools_nccconnect": True,
  609. "tools_ncccontour": True,
  610. "tools_nccrest": False,
  611. "tools_ncc_offset_choice": False,
  612. "tools_ncc_offset_value": 0.0000,
  613. "tools_nccref": 'itself',
  614. "tools_ncc_plotting": 'normal',
  615. "tools_nccmilling_type": 'cl',
  616. "tools_ncctool_type": 'V',
  617. "tools_ncccutz": -0.001968504,
  618. "tools_ncctipdia": 0.00393701,
  619. "tools_ncctipangle": 30,
  620. "tools_nccnewdia": 0.0393701,
  621. # Cutout Tool
  622. "tools_cutouttooldia": 0.0944882,
  623. "tools_cutoutkind": "single",
  624. "tools_cutoutmargin": 0.00393701,
  625. "tools_cutoutgapsize": 0.15748,
  626. "tools_gaps_ff": "4",
  627. "tools_cutout_convexshape": False,
  628. # Paint Tool
  629. "tools_painttooldia": 0.023622,
  630. "tools_paintorder": 'rev',
  631. "tools_paintoverlap": 0.015748,
  632. "tools_paintmargin": 0.0,
  633. "tools_paintmethod": "seed",
  634. "tools_selectmethod": "all",
  635. "tools_pathconnect": True,
  636. "tools_paintcontour": True,
  637. "tools_paint_plotting": 'normal',
  638. # 2-Sided Tool
  639. "tools_2sided_mirror_axis": "X",
  640. "tools_2sided_axis_loc": "point",
  641. "tools_2sided_drilldia": 0.11811,
  642. # Film Tool
  643. "tools_film_type": 'neg',
  644. "tools_film_boundary": 0.0393701,
  645. "tools_film_scale_stroke": 0,
  646. "tools_film_color": '#000000',
  647. "tools_film_scale_cb": False,
  648. "tools_film_scale_x_entry": 1.0,
  649. "tools_film_scale_y_entry": 1.0,
  650. "tools_film_skew_cb": False,
  651. "tools_film_skew_x_entry": 0.0,
  652. "tools_film_skew_y_entry": 0.0,
  653. "tools_film_skew_ref_radio": 'bottomleft',
  654. "tools_film_mirror_cb": False,
  655. "tools_film_mirror_axis_radio": 'none',
  656. "tools_film_file_type_radio": 'svg',
  657. "tools_film_orientation": 'p',
  658. "tools_film_pagesize": 'A4',
  659. # Panel Tool
  660. "tools_panelize_spacing_columns": 0,
  661. "tools_panelize_spacing_rows": 0,
  662. "tools_panelize_columns": 1,
  663. "tools_panelize_rows": 1,
  664. "tools_panelize_constrain": False,
  665. "tools_panelize_constrainx": 200.0,
  666. "tools_panelize_constrainy": 290.0,
  667. "tools_panelize_panel_type": 'gerber',
  668. # Calculators Tool
  669. "tools_calc_vshape_tip_dia": 0.007874,
  670. "tools_calc_vshape_tip_angle": 30,
  671. "tools_calc_vshape_cut_z": 0.000787,
  672. "tools_calc_electro_length": 10.0,
  673. "tools_calc_electro_width": 10.0,
  674. "tools_calc_electro_cdensity": 13.0,
  675. "tools_calc_electro_growth": 10.0,
  676. # Transform Tool
  677. "tools_transform_rotate": 90,
  678. "tools_transform_skew_x": 0.0,
  679. "tools_transform_skew_y": 0.0,
  680. "tools_transform_scale_x": 1.0,
  681. "tools_transform_scale_y": 1.0,
  682. "tools_transform_scale_link": True,
  683. "tools_transform_scale_reference": True,
  684. "tools_transform_offset_x": 0.0,
  685. "tools_transform_offset_y": 0.0,
  686. "tools_transform_mirror_reference": False,
  687. "tools_transform_mirror_point": (0, 0),
  688. # SolderPaste Tool
  689. "tools_solderpaste_tools": "0.0393701, 0.011811",
  690. "tools_solderpaste_new": 0.011811,
  691. "tools_solderpaste_z_start": 0.00019685039,
  692. "tools_solderpaste_z_dispense": 0.00393701,
  693. "tools_solderpaste_z_stop": 0.00019685039,
  694. "tools_solderpaste_z_travel": 0.00393701,
  695. "tools_solderpaste_z_toolchange": 0.0393701,
  696. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  697. "tools_solderpaste_frxy": 3.0,
  698. "tools_solderpaste_frz": 3.0,
  699. "tools_solderpaste_frz_dispense": 0.0393701,
  700. "tools_solderpaste_speedfwd": 20,
  701. "tools_solderpaste_dwellfwd": 1,
  702. "tools_solderpaste_speedrev": 10,
  703. "tools_solderpaste_dwellrev": 1,
  704. "tools_solderpaste_pp": 'Paste_1',
  705. # Subtract Tool
  706. "tools_sub_close_paths": True,
  707. # ###################################################################################
  708. # ################################ TOOLS 2 ##########################################
  709. # ###################################################################################
  710. # Optimal Tool
  711. "tools_opt_precision": 4,
  712. # Check Rules Tool
  713. "tools_cr_trace_size": True,
  714. "tools_cr_trace_size_val": 0.01,
  715. "tools_cr_c2c": True,
  716. "tools_cr_c2c_val": 0.01,
  717. "tools_cr_c2o": True,
  718. "tools_cr_c2o_val": 0.03937,
  719. "tools_cr_s2s": True,
  720. "tools_cr_s2s_val": 0.01,
  721. "tools_cr_s2sm": True,
  722. "tools_cr_s2sm_val": 0.01,
  723. "tools_cr_s2o": True,
  724. "tools_cr_s2o_val": 0.03937,
  725. "tools_cr_sm2sm": True,
  726. "tools_cr_sm2sm_val": 0.01,
  727. "tools_cr_ri": True,
  728. "tools_cr_ri_val": 0.015,
  729. "tools_cr_h2h": True,
  730. "tools_cr_h2h_val": 0.015,
  731. "tools_cr_dh": True,
  732. "tools_cr_dh_val": 0.011811,
  733. # QRCode Tool
  734. "tools_qrcode_version": 1,
  735. "tools_qrcode_error": 'L',
  736. "tools_qrcode_box_size": 3,
  737. "tools_qrcode_border_size": 4,
  738. "tools_qrcode_qrdata": '',
  739. "tools_qrcode_polarity": 'pos',
  740. "tools_qrcode_rounded": 's',
  741. "tools_qrcode_fill_color": '#000000',
  742. "tools_qrcode_back_color": '#FFFFFF',
  743. "tools_qrcode_sel_limit": 330,
  744. # Copper Thieving Tool
  745. "tools_copper_thieving_clearance": 0.01,
  746. "tools_copper_thieving_margin": 0.039,
  747. "tools_copper_thieving_reference": 'itself',
  748. "tools_copper_thieving_box_type": 'rect',
  749. "tools_copper_thieving_circle_steps": 128,
  750. "tools_copper_thieving_fill_type": 'solid',
  751. "tools_copper_thieving_dots_dia": 0.0393701,
  752. "tools_copper_thieving_dots_spacing": 0.0787402,
  753. "tools_copper_thieving_squares_size": 0.0393701,
  754. "tools_copper_thieving_squares_spacing": 0.0787402,
  755. "tools_copper_thieving_lines_size": 0.01,
  756. "tools_copper_thieving_lines_spacing": 0.0787402,
  757. "tools_copper_thieving_rb_margin": 0.039,
  758. "tools_copper_thieving_rb_thickness": 0.039,
  759. # Fiducials Tool
  760. "tools_fiducials_dia": 0.0393701,
  761. "tools_fiducials_margin": 0.0393701,
  762. "tools_fiducials_mode": 'auto',
  763. "tools_fiducials_second_pos": 'up',
  764. "tools_fiducials_type": 'circular',
  765. "tools_fiducials_line_thickness": 0.01,
  766. # Utilities
  767. # file associations
  768. "fa_excellon": 'drd, drl, exc, ncd, tap, xln',
  769. "fa_gcode": 'cnc, din, dnc, ecs, eia, fan, fgc, fnc, gc, gcd, gcode, h, hnc, i, min, mpf, mpr, nc, ncc, '
  770. 'ncg, ncp, ngc, out, plt, ply, rol, sbp, tap, xpi',
  771. "fa_gerber": 'art, bot, bsm, cmp, crc, crs, dim, gb0, gb1, gb2, gb3, gb4, gb5, gb6, gb7, gb8, gb9, gbd, '
  772. 'gbl, gbo, gbp, gbr, gbs, gdo, ger, gko, gm1, gm2, gm3, grb, gtl, gto, gtp, gts, ly15, ly2, '
  773. 'mil, pho, plc, pls, smb, smt, sol, spb, spt, ssb, sst, stc, sts, top, tsm',
  774. # Keyword list
  775. "util_autocomplete_keywords": 'Desktop, Documents, FlatConfig, FlatPrj, Marius, My Documents, Paste_1, '
  776. 'Repetier, Roland_MDX_20, Users, Toolchange_Custom, Toolchange_Probe_MACH3, '
  777. 'Toolchange_manual, Users, all, angle_x, angle_y, axis, auto, axisoffset, '
  778. 'box, center_x, center_y, columns, combine, connect, contour, default, '
  779. 'depthperpass, dia, diatol, dist, drilled_dias, drillz, dwell, dwelltime, '
  780. 'feedrate_z, grbl_11, grbl_laser, gridoffsety, gridx, gridy, has_offset, '
  781. 'holes, hpgl, iso_type, line_xyz, margin, marlin, method, milled_dias, '
  782. 'minoffset, multidepth, name, offset, opt_type, order, outname, overlap, '
  783. 'passes, postamble, pp, ppname_e, ppname_g, preamble, radius, ref, rest, '
  784. 'rows, shellvar_, scale_factor, spacing_columns, spacing_rows, spindlespeed, '
  785. 'toolchange_xy, tooldia, use_threads, value, x, x0, x1, y, y0, y1, z_cut, '
  786. 'z_move',
  787. "script_autocompleter": True,
  788. "script_text": "",
  789. "script_plot": True,
  790. "script_source_file": "",
  791. "document_autocompleter": False,
  792. "document_text": "",
  793. "document_plot": True,
  794. "document_source_file": "",
  795. "document_font_color": '#000000',
  796. "document_sel_color": '#0055ff',
  797. "document_font_size": 6,
  798. "document_tab_size": 80,
  799. })
  800. # ############################################################
  801. # ############### Load defaults from file ####################
  802. # ############################################################
  803. if user_defaults:
  804. self.load_defaults(filename='current_defaults')
  805. # #############################################################################
  806. # ##################### CREATE MULTIPROCESSING POOL ###########################
  807. # #############################################################################
  808. self.pool = Pool(processes=cpu_count())
  809. # ##########################################################################
  810. # ################## Setting the Splash Screen #############################
  811. # ##########################################################################
  812. splash_settings = QSettings("Open Source", "FlatCAM")
  813. if splash_settings.contains("splash_screen"):
  814. show_splash = splash_settings.value("splash_screen")
  815. else:
  816. splash_settings.setValue('splash_screen', 1)
  817. # This will write the setting to the platform specific storage.
  818. del splash_settings
  819. show_splash = 1
  820. if show_splash and self.cmd_line_headless != 1:
  821. splash_pix = QtGui.QPixmap('share/splash.png')
  822. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  823. # self.splash.setMask(splash_pix.mask())
  824. # move splashscreen to the current monitor
  825. desktop = QtWidgets.QApplication.desktop()
  826. screen = desktop.screenNumber(QtGui.QCursor.pos())
  827. current_screen_center = desktop.availableGeometry(screen).center()
  828. self.splash.move(current_screen_center - self.splash.rect().center())
  829. self.splash.show()
  830. self.splash.showMessage(_("FlatCAM is initializing ..."),
  831. alignment=Qt.AlignBottom | Qt.AlignLeft,
  832. color=QtGui.QColor("gray"))
  833. else:
  834. show_splash = 0
  835. # #############################################################################
  836. # ##################### Initialize GUI ########################################
  837. # #############################################################################
  838. # FlatCAM colors used in plotting
  839. self.FC_light_green = '#BBF268BF'
  840. self.FC_dark_green = '#006E20BF'
  841. self.FC_light_blue = '#a5a5ffbf'
  842. self.FC_dark_blue = '#0000ffbf'
  843. QtCore.QObject.__init__(self)
  844. self.ui = FlatCAMGUI(self.version, self.beta, self)
  845. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  846. if theme_settings.contains("theme"):
  847. theme = theme_settings.value('theme', type=str)
  848. else:
  849. theme = 'white'
  850. if theme == 'white':
  851. self.cursor_color_3D = 'black'
  852. else:
  853. self.cursor_color_3D = 'gray'
  854. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  855. self.ui.final_save.connect(self.final_save)
  856. # restore the toolbar view
  857. self.restore_toolbar_view()
  858. # restore the GUI geometry
  859. self.restore_main_win_geom()
  860. # set FlatCAM units in the Status bar
  861. self.set_screen_units(self.defaults['units'])
  862. # #############################################################################
  863. # ######################## UPDATE PREFERENCES GUI FORMS #######################
  864. # #############################################################################
  865. # when adding entries here read the comments in the method found bellow named:
  866. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  867. self.defaults_form_fields = {
  868. # General App
  869. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  870. "global_graphic_engine": self.ui.general_defaults_form.general_app_group.ge_radio,
  871. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  872. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  873. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  874. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  875. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  876. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  877. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  878. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  879. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  880. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  881. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_spinner,
  882. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  883. "global_bookmarks_limit": self.ui.general_defaults_form.general_app_group.bm_limit_spinner,
  884. "global_machinist_setting": self.ui.general_defaults_form.general_app_group.machinist_cb,
  885. # General GUI Preferences
  886. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  887. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  888. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  889. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  890. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  891. "global_workspace_orientation": self.ui.general_defaults_form.general_gui_group.wk_orientation_radio,
  892. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  893. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  894. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  895. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  896. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  897. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  898. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  899. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  900. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  901. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  902. "global_activity_icon": self.ui.general_defaults_form.general_gui_group.activity_combo,
  903. # General GUI Settings
  904. "global_theme": self.ui.general_defaults_form.general_gui_set_group.theme_radio,
  905. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  906. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  907. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  908. "global_systray_icon": self.ui.general_defaults_form.general_gui_set_group.systray_cb,
  909. "global_shell_at_startup": self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb,
  910. "global_project_at_startup": self.ui.general_defaults_form.general_gui_set_group.project_startup_cb,
  911. "global_project_autohide": self.ui.general_defaults_form.general_gui_set_group.project_autohide_cb,
  912. "global_toggle_tooltips": self.ui.general_defaults_form.general_gui_set_group.toggle_tooltips_cb,
  913. "global_delete_confirmation": self.ui.general_defaults_form.general_gui_set_group.delete_conf_cb,
  914. "global_cursor_type": self.ui.general_defaults_form.general_gui_set_group.cursor_radio,
  915. "global_cursor_size": self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry,
  916. # Gerber General
  917. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  918. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  919. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  920. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  921. "gerber_def_units": self.ui.gerber_defaults_form.gerber_gen_group.gerber_units_radio,
  922. "gerber_def_zeros": self.ui.gerber_defaults_form.gerber_gen_group.gerber_zeros_radio,
  923. # Gerber Options
  924. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  925. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  926. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  927. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  928. "gerber_iso_scope": self.ui.gerber_defaults_form.gerber_opt_group.iso_scope_radio,
  929. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  930. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  931. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  932. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  933. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  934. # Gerber Advanced Options
  935. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  936. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  937. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  938. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  939. "gerber_tool_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.tool_type_radio,
  940. "gerber_vtipdia": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipdia_spinner,
  941. "gerber_vtipangle": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipangle_spinner,
  942. "gerber_vcutz": self.ui.gerber_defaults_form.gerber_adv_opt_group.cutz_spinner,
  943. "gerber_iso_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.iso_type_radio,
  944. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  945. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  946. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  947. # Gerber Export
  948. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  949. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  950. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  951. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  952. # Gerber Editor
  953. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  954. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  955. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  956. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  957. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  958. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  959. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  960. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  961. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  962. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  963. "gerber_editor_circ_angle":
  964. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  965. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  966. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  967. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  968. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  969. # Excellon General
  970. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  971. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  972. "excellon_format_upper_in":
  973. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  974. "excellon_format_lower_in":
  975. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  976. "excellon_format_upper_mm":
  977. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  978. "excellon_format_lower_mm":
  979. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  980. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  981. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  982. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  983. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  984. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  985. # Excellon Options
  986. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  987. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  988. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.eendz_entry,
  989. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  990. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  991. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  992. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  993. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  994. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  995. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  996. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  997. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  998. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  999. # Excellon Advanced Options
  1000. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  1001. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  1002. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  1003. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1004. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  1005. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  1006. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  1007. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  1008. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  1009. # Excellon Export
  1010. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  1011. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  1012. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  1013. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  1014. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  1015. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  1016. # Excellon Editor
  1017. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  1018. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  1019. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  1020. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  1021. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  1022. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  1023. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  1024. "excellon_editor_circ_angle":
  1025. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  1026. # Excellon Slots
  1027. "excellon_editor_slot_direction":
  1028. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  1029. "excellon_editor_slot_angle":
  1030. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  1031. "excellon_editor_slot_length":
  1032. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  1033. # Excellon Slots
  1034. "excellon_editor_slot_array_size":
  1035. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  1036. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  1037. "excellon_editor_slot_lin_pitch":
  1038. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  1039. "excellon_editor_slot_lin_angle":
  1040. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  1041. "excellon_editor_slot_circ_dir":
  1042. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  1043. "excellon_editor_slot_circ_angle":
  1044. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  1045. # Geometry General
  1046. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  1047. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  1048. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  1049. # Geometry Options
  1050. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  1051. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  1052. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  1053. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  1054. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  1055. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  1056. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  1057. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  1058. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  1059. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  1060. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.gendz_entry,
  1061. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  1062. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  1063. # Geometry Advanced Options
  1064. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  1065. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  1066. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1067. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  1068. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  1069. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  1070. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  1071. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  1072. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  1073. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  1074. # Geometry Editor
  1075. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  1076. "geometry_editor_milling_type": self.ui.geometry_defaults_form.geometry_editor_group.milling_type_radio,
  1077. # CNCJob General
  1078. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  1079. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  1080. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  1081. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  1082. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  1083. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  1084. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  1085. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  1086. "cncjob_line_ending": self.ui.cncjob_defaults_form.cncjob_gen_group.line_ending_cb,
  1087. # CNC Job Options
  1088. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  1089. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  1090. # CNC Job Advanced Options
  1091. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  1092. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  1093. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  1094. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  1095. # NCC Tool
  1096. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  1097. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  1098. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  1099. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  1100. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  1101. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  1102. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  1103. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  1104. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  1105. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  1106. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  1107. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  1108. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  1109. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  1110. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  1111. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  1112. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  1113. "tools_nccnewdia": self.ui.tools_defaults_form.tools_ncc_group.newdia_entry,
  1114. # CutOut Tool
  1115. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  1116. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  1117. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  1118. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  1119. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  1120. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  1121. # Paint Area Tool
  1122. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  1123. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  1124. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  1125. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  1126. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  1127. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  1128. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  1129. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  1130. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  1131. # 2-sided Tool
  1132. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  1133. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  1134. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  1135. # Film Tool
  1136. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  1137. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  1138. "tools_film_scale_stroke": self.ui.tools_defaults_form.tools_film_group.film_scale_stroke_entry,
  1139. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  1140. "tools_film_scale_cb": self.ui.tools_defaults_form.tools_film_group.film_scale_cb,
  1141. "tools_film_scale_x_entry": self.ui.tools_defaults_form.tools_film_group.film_scalex_entry,
  1142. "tools_film_scale_y_entry": self.ui.tools_defaults_form.tools_film_group.film_scaley_entry,
  1143. "tools_film_skew_cb": self.ui.tools_defaults_form.tools_film_group.film_skew_cb,
  1144. "tools_film_skew_x_entry": self.ui.tools_defaults_form.tools_film_group.film_skewx_entry,
  1145. "tools_film_skew_y_entry": self.ui.tools_defaults_form.tools_film_group.film_skewy_entry,
  1146. "tools_film_skew_ref_radio": self.ui.tools_defaults_form.tools_film_group.film_skew_reference,
  1147. "tools_film_mirror_cb": self.ui.tools_defaults_form.tools_film_group.film_mirror_cb,
  1148. "tools_film_mirror_axis_radio": self.ui.tools_defaults_form.tools_film_group.film_mirror_axis,
  1149. "tools_film_file_type_radio": self.ui.tools_defaults_form.tools_film_group.file_type_radio,
  1150. "tools_film_orientation": self.ui.tools_defaults_form.tools_film_group.orientation_radio,
  1151. "tools_film_pagesize": self.ui.tools_defaults_form.tools_film_group.pagesize_combo,
  1152. # Panelize Tool
  1153. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  1154. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  1155. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  1156. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  1157. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  1158. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  1159. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  1160. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  1161. # Calculators Tool
  1162. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  1163. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  1164. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  1165. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  1166. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  1167. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  1168. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  1169. # Transformations Tool
  1170. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  1171. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  1172. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  1173. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  1174. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  1175. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  1176. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  1177. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  1178. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  1179. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  1180. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  1181. # SolderPaste Dispensing Tool
  1182. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  1183. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  1184. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  1185. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  1186. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  1187. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  1188. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  1189. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  1190. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  1191. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  1192. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  1193. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  1194. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  1195. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  1196. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  1197. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  1198. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  1199. # ###################################################################################
  1200. # ################################ TOOLS 2 ##########################################
  1201. # ###################################################################################
  1202. # Optimal Tool
  1203. "tools_opt_precision": self.ui.tools2_defaults_form.tools2_optimal_group.precision_sp,
  1204. # Check Rules Tool
  1205. "tools_cr_trace_size": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_cb,
  1206. "tools_cr_trace_size_val": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_entry,
  1207. "tools_cr_c2c": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_cb,
  1208. "tools_cr_c2c_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_entry,
  1209. "tools_cr_c2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_cb,
  1210. "tools_cr_c2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_entry,
  1211. "tools_cr_s2s": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_cb,
  1212. "tools_cr_s2s_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_entry,
  1213. "tools_cr_s2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_cb,
  1214. "tools_cr_s2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_entry,
  1215. "tools_cr_s2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_cb,
  1216. "tools_cr_s2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_entry,
  1217. "tools_cr_sm2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_cb,
  1218. "tools_cr_sm2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_entry,
  1219. "tools_cr_ri": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_cb,
  1220. "tools_cr_ri_val": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_entry,
  1221. "tools_cr_h2h": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_cb,
  1222. "tools_cr_h2h_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_entry,
  1223. "tools_cr_dh": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_cb,
  1224. "tools_cr_dh_val": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_entry,
  1225. # QRCode Tool
  1226. "tools_qrcode_version": self.ui.tools2_defaults_form.tools2_qrcode_group.version_entry,
  1227. "tools_qrcode_error": self.ui.tools2_defaults_form.tools2_qrcode_group.error_radio,
  1228. "tools_qrcode_box_size": self.ui.tools2_defaults_form.tools2_qrcode_group.bsize_entry,
  1229. "tools_qrcode_border_size": self.ui.tools2_defaults_form.tools2_qrcode_group.border_size_entry,
  1230. "tools_qrcode_qrdata": self.ui.tools2_defaults_form.tools2_qrcode_group.text_data,
  1231. "tools_qrcode_polarity": self.ui.tools2_defaults_form.tools2_qrcode_group.pol_radio,
  1232. "tools_qrcode_rounded": self.ui.tools2_defaults_form.tools2_qrcode_group.bb_radio,
  1233. "tools_qrcode_fill_color": self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry,
  1234. "tools_qrcode_back_color": self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry,
  1235. "tools_qrcode_sel_limit": self.ui.tools2_defaults_form.tools2_qrcode_group.sel_limit_entry,
  1236. # Copper Thieving Tool
  1237. "tools_copper_thieving_clearance": self.ui.tools2_defaults_form.tools2_cfill_group.clearance_entry,
  1238. "tools_copper_thieving_margin": self.ui.tools2_defaults_form.tools2_cfill_group.margin_entry,
  1239. "tools_copper_thieving_reference": self.ui.tools2_defaults_form.tools2_cfill_group.reference_radio,
  1240. "tools_copper_thieving_box_type": self.ui.tools2_defaults_form.tools2_cfill_group.bbox_type_radio,
  1241. "tools_copper_thieving_circle_steps": self.ui.tools2_defaults_form.tools2_cfill_group.circlesteps_entry,
  1242. "tools_copper_thieving_fill_type": self.ui.tools2_defaults_form.tools2_cfill_group.fill_type_radio,
  1243. "tools_copper_thieving_dots_dia": self.ui.tools2_defaults_form.tools2_cfill_group.dot_dia_entry,
  1244. "tools_copper_thieving_dots_spacing": self.ui.tools2_defaults_form.tools2_cfill_group.dot_spacing_entry,
  1245. "tools_copper_thieving_squares_size": self.ui.tools2_defaults_form.tools2_cfill_group.square_size_entry,
  1246. "tools_copper_thieving_squares_spacing":
  1247. self.ui.tools2_defaults_form.tools2_cfill_group.squares_spacing_entry,
  1248. "tools_copper_thieving_lines_size": self.ui.tools2_defaults_form.tools2_cfill_group.line_size_entry,
  1249. "tools_copper_thieving_lines_spacing": self.ui.tools2_defaults_form.tools2_cfill_group.lines_spacing_entry,
  1250. "tools_copper_thieving_rb_margin": self.ui.tools2_defaults_form.tools2_cfill_group.rb_margin_entry,
  1251. "tools_copper_thieving_rb_thickness": self.ui.tools2_defaults_form.tools2_cfill_group.rb_thickness_entry,
  1252. # Fiducials Tool
  1253. "tools_fiducials_dia": self.ui.tools2_defaults_form.tools2_fiducials_group.dia_entry,
  1254. "tools_fiducials_margin": self.ui.tools2_defaults_form.tools2_fiducials_group.margin_entry,
  1255. "tools_fiducials_mode": self.ui.tools2_defaults_form.tools2_fiducials_group.mode_radio,
  1256. "tools_fiducials_second_pos": self.ui.tools2_defaults_form.tools2_fiducials_group.pos_radio,
  1257. "tools_fiducials_type": self.ui.tools2_defaults_form.tools2_fiducials_group.fid_type_radio,
  1258. "tools_fiducials_line_thickness": self.ui.tools2_defaults_form.tools2_fiducials_group.line_thickness_entry,
  1259. # Utilities
  1260. # File associations
  1261. "fa_excellon": self.ui.util_defaults_form.fa_excellon_group.exc_list_text,
  1262. "fa_gcode": self.ui.util_defaults_form.fa_gcode_group.gco_list_text,
  1263. # "fa_geometry": self.ui.util_defaults_form.fa_geometry_group.close_paths_cb,
  1264. "fa_gerber": self.ui.util_defaults_form.fa_gerber_group.grb_list_text,
  1265. "util_autocomplete_keywords": self.ui.util_defaults_form.kw_group.kw_list_text,
  1266. }
  1267. # update the Preferences GUI elements with the values in the self.defaults
  1268. self.defaults_write_form()
  1269. # When the self.defaults dictionary changes will update the Preferences GUI forms
  1270. self.defaults.set_change_callback(self.on_defaults_dict_change)
  1271. # #############################################################################
  1272. # ############################## Data #########################################
  1273. # #############################################################################
  1274. self.recent = []
  1275. self.recent_projects = []
  1276. self.clipboard = QtWidgets.QApplication.clipboard()
  1277. self.project_filename = None
  1278. self.toggle_units_ignore = False
  1279. # #############################################################################
  1280. # ########################## LOAD POSTPROCESSORS ##############################
  1281. # #############################################################################
  1282. # a dictionary that have as keys the name of the postprocessor files and the value is the class from
  1283. # the postprocessor file
  1284. self.postprocessors = load_postprocessors(self)
  1285. # make sure that always the 'default' postprocessor is the first item in the dictionary
  1286. if 'default' in self.postprocessors.keys():
  1287. new_ppp_dict = dict()
  1288. # add the 'default' name first in the dict after removing from the postprocessor's dictionary
  1289. default_pp = self.postprocessors.pop('default')
  1290. new_ppp_dict['default'] = default_pp
  1291. # then add the rest of the keys
  1292. for name, val_class in self.postprocessors.items():
  1293. new_ppp_dict[name] = val_class
  1294. # and now put back the ordered dict with 'default' key first
  1295. self.postprocessors = new_ppp_dict
  1296. for name in list(self.postprocessors.keys()):
  1297. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  1298. if name.partition('_')[0] == 'Paste':
  1299. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  1300. continue
  1301. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1302. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  1303. if name == 'hpgl':
  1304. continue
  1305. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1306. # #############################################################################
  1307. # ########################## LOAD LANGUAGES ##################################
  1308. # #############################################################################
  1309. self.languages = fcTranslate.load_languages()
  1310. for name in sorted(self.languages.values()):
  1311. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  1312. # #############################################################################
  1313. # ############################ APPLY APP LANGUAGE #############################
  1314. # #############################################################################
  1315. ret_val = fcTranslate.apply_language('strings')
  1316. if ret_val == "no language":
  1317. self.inform.emit('[ERROR] %s' %
  1318. _("Could not find the Language files. The App strings are missing."))
  1319. log.debug("Could not find the Language files. The App strings are missing.")
  1320. else:
  1321. # make the current language the current selection on the language combobox
  1322. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1323. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1324. # #############################################################################
  1325. # ########################### CREATE UNIQUE SERIAL NUMBER #####################
  1326. # #############################################################################
  1327. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1328. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1329. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  1330. self.save_defaults(silent=True, first_time=True)
  1331. self.propagate_defaults(silent=True)
  1332. # def auto_save_defaults():
  1333. # try:
  1334. # self.save_defaults(silent=True)
  1335. # self.propagate_defaults(silent=True)
  1336. # finally:
  1337. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1338. # the following lines activates automatic defaults save
  1339. # if user_defaults:
  1340. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1341. # #############################################################################
  1342. # ########################### UPDATE THE OPTIONS ##############################
  1343. # #############################################################################
  1344. self.options = LoudDict()
  1345. # ----------------------------------------------------------------------------------------------------
  1346. # Update the self.options from the self.defaults
  1347. # The self.defaults holds the application defaults while the self.options holds the object defaults
  1348. # -----------------------------------------------------------------------------------------------------
  1349. # Copy app defaults to project options
  1350. for def_key, def_val in self.defaults.items():
  1351. self.options[def_key] = deepcopy(def_val)
  1352. # self.options.update(self.defaults)
  1353. self.gen_form = None
  1354. self.ger_form = None
  1355. self.exc_form = None
  1356. self.geo_form = None
  1357. self.cnc_form = None
  1358. self.tools_form = None
  1359. self.tools2_form = None
  1360. self.fa_form = None
  1361. # Will show the Preferences GUI
  1362. self.show_preferences_gui()
  1363. # Initialize the color box's color in Preferences -> Global -> Color
  1364. self.init_color_pickers_in_preferences_gui()
  1365. # ### End of Data ####
  1366. # #############################################################################
  1367. # ######################## SETUP OBJECT COLLECTION ############################
  1368. # #############################################################################
  1369. self.collection = ObjectCollection(self)
  1370. self.ui.project_tab_layout.addWidget(self.collection.view)
  1371. # ### Adjust tabs width ## ##
  1372. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1373. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1374. self.collection.view.setMinimumWidth(290)
  1375. self.log.debug("Finished creating Object Collection.")
  1376. # #############################################################################
  1377. # ############################## SETUP Plot Area ##############################
  1378. # #############################################################################
  1379. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  1380. if self.defaults["global_graphic_engine"] == '3D':
  1381. self.is_legacy = False
  1382. else:
  1383. self.is_legacy = True
  1384. # Event signals disconnect id holders
  1385. self.mp = None
  1386. self.mm = None
  1387. self.mr = None
  1388. self.mdc = None
  1389. self.mp_zc = None
  1390. # Matplotlib axis
  1391. self.axes = None
  1392. if show_splash:
  1393. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1394. "Canvas initialization started."),
  1395. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1396. color=QtGui.QColor("gray"))
  1397. start_plot_time = time.time() # debug
  1398. self.plotcanvas = None
  1399. self.app_cursor = None
  1400. self.hover_shapes = None
  1401. # setup the PlotCanvas
  1402. self.on_plotcanvas_setup()
  1403. end_plot_time = time.time()
  1404. self.used_time = end_plot_time - start_plot_time
  1405. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1406. if show_splash:
  1407. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1408. "Canvas initialization started.\n"
  1409. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1410. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1411. color=QtGui.QColor("gray"))
  1412. self.ui.splitter.setStretchFactor(1, 2)
  1413. # #############################################################################
  1414. # ################################### SYS TRAY ################################
  1415. # #############################################################################
  1416. if self.defaults["global_systray_icon"]:
  1417. self.parent_w = QtWidgets.QWidget()
  1418. if self.cmd_line_headless == 1:
  1419. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1420. headless=True,
  1421. parent=self.parent_w)
  1422. else:
  1423. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1424. parent=self.parent_w)
  1425. # #############################################################################
  1426. # ################################## Worker SETUP #############################
  1427. # #############################################################################
  1428. if self.defaults["global_worker_number"]:
  1429. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1430. else:
  1431. self.workers = WorkerStack(workers_number=2)
  1432. self.worker_task.connect(self.workers.add_task)
  1433. self.log.debug("Finished creating Workers crew.")
  1434. # #############################################################################
  1435. # ################################# Activity Monitor ##########################
  1436. # #############################################################################
  1437. self.activity_view = FlatCAMActivityView(app=self)
  1438. self.ui.infobar.addWidget(self.activity_view)
  1439. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  1440. # #############################################################################
  1441. # ################################## Signal handling ##########################
  1442. # #############################################################################
  1443. # ################################# Custom signals ###########################
  1444. # signal for displaying messages in status bar
  1445. self.inform.connect(self.info)
  1446. # signal to be called when the app is quiting
  1447. self.app_quit.connect(self.quit_application)
  1448. self.message.connect(self.message_dialog)
  1449. self.progress.connect(self.set_progress_bar)
  1450. # signals that are emitted when object state changes
  1451. self.object_created.connect(self.on_object_created)
  1452. self.object_changed.connect(self.on_object_changed)
  1453. self.object_plotted.connect(self.on_object_plotted)
  1454. self.plots_updated.connect(self.on_plots_updated)
  1455. # signals emitted when file state change
  1456. self.file_opened.connect(self.register_recent)
  1457. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1458. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1459. # ############# Standard signals ###################
  1460. # ### Menu
  1461. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1462. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1463. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1464. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1465. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  1466. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1467. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1468. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1469. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1470. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1471. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1472. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1473. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1474. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1475. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1476. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1477. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1478. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1479. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1480. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1481. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1482. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1483. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1484. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1485. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1486. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1487. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1488. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1489. self.ui.menufile_exit.triggered.connect(self.final_save)
  1490. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1491. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1492. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1493. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1494. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1495. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1496. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1497. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1498. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1499. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1500. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1501. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1502. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1503. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1504. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1505. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1506. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1507. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1508. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1509. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1510. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1511. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1512. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1513. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1514. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1515. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1516. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1517. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1518. self.ui.menuoptions_tools_db.triggered.connect(self.on_tools_database)
  1519. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1520. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1521. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1522. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1523. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1524. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1525. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1526. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1527. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1528. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1529. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1530. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  1531. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1532. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  1533. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1534. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  1535. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1536. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1537. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1538. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1539. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1540. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1541. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1542. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1543. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1544. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1545. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1546. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1547. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1548. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1549. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1550. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1551. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1552. # ToolBar signals
  1553. self.connect_toolbar_signals()
  1554. # Notebook and Plot Tab Area signals
  1555. # make the right click on the notebook tab and plot tab area tab raise a menu
  1556. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1557. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1558. self.on_tab_setup_context_menu()
  1559. # activate initial state
  1560. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1561. # Context Menu
  1562. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1563. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1564. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1565. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1566. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1567. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1568. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1569. self.ui.clearplot.triggered.connect(self.clear_plots)
  1570. self.ui.replot.triggered.connect(self.plot_all)
  1571. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1572. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1573. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1574. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1575. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1576. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1577. # Preferences Plot Area TAB
  1578. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1579. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1580. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1581. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1582. # #############################################################################
  1583. # ######################### GUI PREFERENCES SIGNALS ###########################
  1584. # #############################################################################
  1585. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  1586. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1587. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1588. )
  1589. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1590. lambda: self.on_toggle_units(no_pref=False))
  1591. # #############################################################################
  1592. # ############################# GUI COLORS SIGNALS ############################
  1593. # #############################################################################
  1594. # Setting plot colors signals
  1595. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1596. self.on_pf_color_entry)
  1597. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1598. self.on_pf_color_button)
  1599. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1600. self.on_pf_color_spinner)
  1601. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1602. self.on_pf_color_slider)
  1603. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1604. self.on_pl_color_entry)
  1605. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1606. self.on_pl_color_button)
  1607. # Setting selection (left - right) colors signals
  1608. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1609. self.on_sf_color_entry)
  1610. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1611. self.on_sf_color_button)
  1612. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1613. self.on_sf_color_spinner)
  1614. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1615. self.on_sf_color_slider)
  1616. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1617. self.on_sl_color_entry)
  1618. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1619. self.on_sl_color_button)
  1620. # Setting selection (right - left) colors signals
  1621. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1622. self.on_alt_sf_color_entry)
  1623. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1624. self.on_alt_sf_color_button)
  1625. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1626. self.on_alt_sf_color_spinner)
  1627. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1628. self.on_alt_sf_color_slider)
  1629. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1630. self.on_alt_sl_color_entry)
  1631. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1632. self.on_alt_sl_color_button)
  1633. # Setting Editor Draw colors signals
  1634. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1635. self.on_draw_color_entry)
  1636. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1637. self.on_draw_color_button)
  1638. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1639. self.on_sel_draw_color_entry)
  1640. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1641. self.on_sel_draw_color_button)
  1642. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1643. self.on_proj_color_entry)
  1644. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1645. self.on_proj_color_button)
  1646. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1647. self.on_proj_color_dis_entry)
  1648. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1649. self.on_proj_color_dis_button)
  1650. # ############################# workspace setting signals #####################
  1651. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1652. self.ui.general_defaults_form.general_gui_group.wk_orientation_radio.activated_custom.connect(
  1653. self.on_workspace_modified
  1654. )
  1655. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1656. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1657. # #############################################################################
  1658. # ############################# GUI SETTINGS SIGNALS ##########################
  1659. # #############################################################################
  1660. self.ui.general_defaults_form.general_gui_set_group.theme_radio.activated_custom.connect(self.on_theme_change)
  1661. self.ui.general_defaults_form.general_gui_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  1662. # ########## CNC Job related signals #############
  1663. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1664. self.on_cnc_custom_parameters)
  1665. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.editingFinished.connect(
  1666. self.on_annotation_fontcolor_entry)
  1667. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.clicked.connect(
  1668. self.on_annotation_fontcolor_button)
  1669. # ########## Tools related signals #############
  1670. # Film Tool
  1671. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1672. self.on_film_color_entry)
  1673. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1674. self.on_film_color_button)
  1675. # QRCode Tool
  1676. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  1677. self.on_qrcode_fill_color_entry)
  1678. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  1679. self.on_qrcode_fill_color_button)
  1680. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  1681. self.on_qrcode_back_color_entry)
  1682. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  1683. self.on_qrcode_back_color_button)
  1684. # portability changed signal
  1685. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1686. # Object list
  1687. self.collection.view.activated.connect(self.on_row_activated)
  1688. self.collection.item_selected.connect(self.on_row_selected)
  1689. self.object_status_changed.connect(self.on_collection_updated)
  1690. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1691. self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1692. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1693. # Export Excellon parameters.
  1694. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1695. self.on_update_exc_export
  1696. )
  1697. # call it once to make sure it is updated at startup
  1698. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1699. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1700. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1701. self.on_excellon_defaults_button)
  1702. # when there are arguments at application startup this get launched
  1703. self.args_at_startup[list].connect(self.on_startup_args)
  1704. # #############################################################################
  1705. # ########################## FILE ASSOCIATIONS SIGNALS ########################
  1706. # #############################################################################
  1707. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1708. lambda: self.restore_extensions(ext_type='excellon'))
  1709. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1710. lambda: self.restore_extensions(ext_type='gcode'))
  1711. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1712. lambda: self.restore_extensions(ext_type='gerber'))
  1713. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1714. lambda: self.delete_all_extensions(ext_type='excellon'))
  1715. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1716. lambda: self.delete_all_extensions(ext_type='gcode'))
  1717. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1718. lambda: self.delete_all_extensions(ext_type='gerber'))
  1719. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1720. lambda: self.add_extension(ext_type='excellon'))
  1721. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1722. lambda: self.add_extension(ext_type='gcode'))
  1723. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1724. lambda: self.add_extension(ext_type='gerber'))
  1725. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1726. lambda: self.del_extension(ext_type='excellon'))
  1727. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1728. lambda: self.del_extension(ext_type='gcode'))
  1729. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1730. lambda: self.del_extension(ext_type='gerber'))
  1731. # connect the 'Apply' buttons from the Preferences/File Associations
  1732. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1733. lambda: self.on_register_files(obj_type='excellon'))
  1734. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1735. lambda: self.on_register_files(obj_type='gcode'))
  1736. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1737. lambda: self.on_register_files(obj_type='gerber'))
  1738. # #############################################################################
  1739. # ################################ KEYWORDS SIGNALS ###########################
  1740. # #############################################################################
  1741. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1742. lambda: self.restore_extensions(ext_type='keyword'))
  1743. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1744. lambda: self.delete_all_extensions(ext_type='keyword'))
  1745. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1746. lambda: self.add_extension(ext_type='keyword'))
  1747. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1748. lambda: self.del_extension(ext_type='keyword'))
  1749. # splash screen button signal
  1750. self.ui.general_defaults_form.general_gui_set_group.splash_cb.stateChanged.connect(self.on_splash_changed)
  1751. # connect the abort_all_tasks related slots to the related signals
  1752. self.proc_container.idle_flag.connect(self.app_is_idle)
  1753. # signal emitted when a tab is closed in the Plot Area
  1754. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  1755. # #####################################################################################
  1756. # ########### FINISHED CONNECTING SIGNALS #############################################
  1757. # #####################################################################################
  1758. self.log.debug("Finished connecting Signals.")
  1759. # #####################################################################################
  1760. # ########################## Other setups #############################################
  1761. # #####################################################################################
  1762. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  1763. # depending on from where those tools are called different actions can be done
  1764. self.call_source = 'app'
  1765. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1766. self.tool_tab_locked = False
  1767. # decide if to show or hide the Notebook side of the screen at startup
  1768. if self.defaults["global_project_at_startup"] is True:
  1769. self.ui.splitter.setSizes([1, 1])
  1770. else:
  1771. self.ui.splitter.setSizes([0, 1])
  1772. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1773. self.setup_obj_classes()
  1774. self.setup_component_editor()
  1775. # #####################################################################################
  1776. # ######################### Auto-complete KEYWORDS ####################################
  1777. # #####################################################################################
  1778. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1779. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1780. 'delete', 'drillcncjob', 'export_gcode', 'export_svg', 'ext', 'exteriors', 'follow',
  1781. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1782. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1783. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1784. 'mirror', 'ncc',
  1785. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1786. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'origin',
  1787. 'paint', 'pan', 'panel', 'panelize', 'plot_all', 'plot_objects', 'quit_flatcam',
  1788. 'save', 'save_project',
  1789. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_sys',
  1790. 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1791. 'version', 'write_gcode'
  1792. ]
  1793. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'Marius', 'My Documents', 'Paste_1',
  1794. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  1795. 'Toolchange_manual', 'Users', 'all', 'angle_x', 'angle_y', 'auto', 'axis',
  1796. 'axisoffset',
  1797. 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect', 'contour', 'default',
  1798. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dwell',
  1799. 'dwelltime', 'feedrate_z', 'grbl_11', 'grbl_laser', 'gridoffsety', 'gridx', 'gridy',
  1800. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  1801. 'milled_dias', 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order',
  1802. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  1803. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  1804. 'spacing_columns',
  1805. 'spacing_rows', 'spindlespeed', 'toolchange_xy', 'tooldia', 'use_threads', 'value',
  1806. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1807. ]
  1808. self.tcl_keywords = [
  1809. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1810. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1811. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1812. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1813. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1814. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1815. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1816. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1817. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1818. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1819. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1820. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1821. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1822. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1823. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1824. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1825. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1826. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1827. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1828. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1829. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1830. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1831. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1832. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1833. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1834. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1835. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1836. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1837. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1838. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1839. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1840. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1841. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1842. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1843. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1844. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1845. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1846. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1847. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1848. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1849. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1850. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1851. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1852. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1853. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1854. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1855. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1856. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1857. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1858. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1859. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1860. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1861. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1862. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1863. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1864. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1865. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1866. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1867. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1868. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1869. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1870. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1871. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1872. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1873. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1874. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1875. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1876. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1877. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1878. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1879. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1880. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1881. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1882. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1883. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1884. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1885. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1886. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1887. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1888. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1889. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1890. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1891. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1892. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1893. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1894. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1895. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1896. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1897. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1898. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1899. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1900. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1901. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1902. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1903. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1904. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1905. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1906. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1907. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1908. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1909. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1910. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1911. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1912. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1913. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1914. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1915. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1916. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1917. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1918. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1919. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1920. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1921. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1922. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1923. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1924. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1925. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1926. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1927. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1928. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1929. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1930. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1931. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1932. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1933. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1934. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1935. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1936. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1937. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1938. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1939. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1940. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1941. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1942. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1943. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1944. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1945. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1946. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1947. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1948. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1949. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1950. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1951. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1952. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1953. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1954. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1955. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1956. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1957. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1958. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1959. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1960. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1961. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1962. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1963. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1964. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1965. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1966. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1967. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1968. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1969. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1970. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1971. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1972. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1973. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1974. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1975. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1976. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1977. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1978. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1979. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1980. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1981. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1982. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1983. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1984. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1985. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1986. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1987. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1988. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1989. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1990. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1991. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1992. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1993. ]
  1994. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1995. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1996. # ####################################################################################
  1997. # ####################### Shell SETUP ################################################
  1998. # ####################################################################################
  1999. # this will hold the TCL instance
  2000. self.tcl = None
  2001. self.init_tcl()
  2002. self.shell = FCShell(self, version=self.version)
  2003. self.shell._edit.set_model_data(self.myKeywords)
  2004. self.shell.setWindowIcon(self.ui.app_icon)
  2005. self.shell.setWindowTitle("FlatCAM Shell")
  2006. self.shell.resize(*self.defaults["global_shell_shape"])
  2007. self.shell.append_output("FlatCAM %s - " % self.version)
  2008. self.shell.append_output(_("Type >help< to get started\n\n"))
  2009. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  2010. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  2011. self.ui.shell_dock.setWidget(self.shell)
  2012. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  2013. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  2014. QtWidgets.QDockWidget.DockWidgetFloatable |
  2015. QtWidgets.QDockWidget.DockWidgetClosable)
  2016. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  2017. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  2018. if self.defaults["global_shell_at_startup"]:
  2019. self.ui.shell_dock.show()
  2020. else:
  2021. self.ui.shell_dock.hide()
  2022. # ##################################################################################
  2023. # ###################### Tools and Plugins #########################################
  2024. # ##################################################################################
  2025. self.dblsidedtool = None
  2026. self.distance_tool = None
  2027. self.distance_min_tool = None
  2028. self.panelize_tool = None
  2029. self.film_tool = None
  2030. self.paste_tool = None
  2031. self.calculator_tool = None
  2032. self.rules_tool = None
  2033. self.sub_tool = None
  2034. self.move_tool = None
  2035. self.cutout_tool = None
  2036. self.ncclear_tool = None
  2037. self.optimal_tool = None
  2038. self.paint_tool = None
  2039. self.transform_tool = None
  2040. self.properties_tool = None
  2041. self.pdf_tool = None
  2042. self.image_tool = None
  2043. self.pcb_wizard_tool = None
  2044. self.cal_exc_tool = None
  2045. self.qrcode_tool = None
  2046. self.copper_thieving_tool = None
  2047. self.fiducial_tool = None
  2048. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  2049. self.install_tools()
  2050. # ##################################################################################
  2051. # ########################### SETUP RECENT ITEMS ###################################
  2052. # ##################################################################################
  2053. self.setup_recent_items()
  2054. # ##################################################################################
  2055. # ########################### BookMarks Manager ####################################
  2056. # ##################################################################################
  2057. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  2058. self.install_bookmarks()
  2059. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  2060. # ##################################################################################
  2061. # ############################## Tools Database ####################################
  2062. # ##################################################################################
  2063. self.tools_db_tab = None
  2064. # ### System Font Parsing ###
  2065. # self.f_parse = ParseFont(self)
  2066. # self.parse_system_fonts()
  2067. # #####################################################################################
  2068. # ######################## Check for updates ##########################################
  2069. # #####################################################################################
  2070. # Separate thread (Not worker)
  2071. # Check for updates on startup but only if the user consent and the app is not in Beta version
  2072. if (self.beta is False or self.beta is None) and \
  2073. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  2074. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  2075. self.thr2 = QtCore.QThread()
  2076. self.worker_task.emit({'fcn': self.version_check,
  2077. 'params': []})
  2078. self.thr2.start(QtCore.QThread.LowPriority)
  2079. # #####################################################################################
  2080. # ######################### Register files with FlatCAM; #############################
  2081. # ######################### It works only for Windows for now ########################
  2082. # #####################################################################################
  2083. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  2084. self.on_register_files()
  2085. # #####################################################################################
  2086. # ###################### Variables for global usage ###################################
  2087. # #####################################################################################
  2088. # hold the App units
  2089. self.units = 'IN'
  2090. # coordinates for relative position display
  2091. self.rel_point1 = (0, 0)
  2092. self.rel_point2 = (0, 0)
  2093. # variable to store coordinates
  2094. self.pos = (0, 0)
  2095. self.pos_jump = (0, 0)
  2096. # variable to store mouse coordinates
  2097. self.mouse = [0, 0]
  2098. # decide if we have a double click or single click
  2099. self.doubleclick = False
  2100. # store here the is_dragging value
  2101. self.event_is_dragging = False
  2102. # variable to store if a command is active (then the var is not None) and which one it is
  2103. self.command_active = None
  2104. # variable to store the status of moving selection action
  2105. # None value means that it's not an selection action
  2106. # True value = a selection from left to right
  2107. # False value = a selection from right to left
  2108. self.selection_type = None
  2109. # List to store the objects that are currently loaded in FlatCAM
  2110. # This list is updated on each object creation or object delete
  2111. self.all_objects_list = list()
  2112. # List to store the objects that are selected
  2113. self.sel_objects_list = list()
  2114. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  2115. self.key_modifiers = None
  2116. # Variable to hold the status of the axis
  2117. self.toggle_axis = True
  2118. # Variable to hold the status of the grid lines
  2119. self.toggle_grid_lines = True
  2120. # Variable to store the status of the fullscreen event
  2121. self.toggle_fscreen = False
  2122. # Variable to store the status of the code editor
  2123. self.toggle_codeeditor = False
  2124. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  2125. self.click_noproject = False
  2126. self.cursor = None
  2127. # Variable to store the GCODE that was edited
  2128. self.gcode_edited = ""
  2129. self.text_editor_tab = None
  2130. # reference for the self.ui.code_editor
  2131. self.reference_code_editor = None
  2132. self.script_code = ''
  2133. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  2134. self.preferences_changed_flag = False
  2135. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  2136. self.tools_db_changed_flag = False
  2137. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  2138. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  2139. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'pho',
  2140. 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top', 'tsm']
  2141. self.exc_list = ['drd', 'drl', 'exc', 'ncd', 'tap', 'txt', 'xln']
  2142. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  2143. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'plt', 'ply', 'rol',
  2144. 'sbp', 'tap', 'xpi']
  2145. self.svg_list = ['svg']
  2146. self.dxf_list = ['dxf']
  2147. self.pdf_list = ['pdf']
  2148. self.prj_list = ['flatprj']
  2149. self.conf_list = ['flatconfig']
  2150. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  2151. # flag for polygons not cleared
  2152. self.poly_not_cleared = False
  2153. # VisPy visuals
  2154. self.isHovering = False
  2155. self.notHovering = True
  2156. # Window geometry
  2157. self.x_pos = None
  2158. self.y_pos = None
  2159. self.width = None
  2160. self.height = None
  2161. # when True, the app has to return from any thread
  2162. self.abort_flag = False
  2163. # set the value used in the Windows Title
  2164. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  2165. # this holds a widget that is installed in the Plot Area when View Source option is used
  2166. self.source_editor_tab = None
  2167. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  2168. # VisPy visuals
  2169. if self.is_legacy is False:
  2170. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  2171. else:
  2172. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  2173. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  2174. # ###############################################################################
  2175. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  2176. # ############# It's done only once after install ###############
  2177. # ###############################################################################
  2178. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  2179. fac_def_from_file = factory_file.read()
  2180. factory_defaults = json.loads(fac_def_from_file)
  2181. # if the file contain an empty dictionary then save the factory defaults into the file
  2182. if not factory_defaults:
  2183. self.save_factory_defaults(silent_message=False)
  2184. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  2185. initial_lay = 'compact'
  2186. self.on_layout(lay=initial_lay)
  2187. # Set the combobox in Preferences to the current layout
  2188. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  2189. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  2190. factory_file.close()
  2191. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  2192. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  2193. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  2194. # after the first run, this object should be False
  2195. self.defaults["first_run"] = False
  2196. # ###############################################################################
  2197. # ################# ADDING FlatCAM EDITORS section ##############################
  2198. # ###############################################################################
  2199. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2200. # at the first launch of the App , the editors will not be functional.
  2201. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  2202. self.exc_editor = FlatCAMExcEditor(self)
  2203. self.grb_editor = FlatCAMGrbEditor(self)
  2204. self.log.debug("Finished adding FlatCAM Editor's.")
  2205. self.set_ui_title(name=_("New Project - Not saved"))
  2206. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2207. current_platform = platform.architecture()[0]
  2208. if current_platform != '64bit':
  2209. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2210. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2211. # ###############################################################################
  2212. # ####################### Finished the CONSTRUCTOR ##############################
  2213. # ###############################################################################
  2214. App.log.debug("END of constructor. Releasing control.")
  2215. # #####################################################################################
  2216. # ########################## SHOW GUI #################################################
  2217. # #####################################################################################
  2218. # if the app is not started as headless, show it
  2219. if self.cmd_line_headless != 1:
  2220. if show_splash:
  2221. # finish the splash
  2222. self.splash.finish(self.ui)
  2223. mgui_settings = QSettings("Open Source", "FlatCAM")
  2224. if mgui_settings.contains("maximized_gui"):
  2225. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  2226. if maximized_ui is True:
  2227. self.ui.showMaximized()
  2228. else:
  2229. self.ui.show()
  2230. else:
  2231. self.ui.show()
  2232. if self.defaults["global_systray_icon"]:
  2233. self.trayIcon.show()
  2234. else:
  2235. log.warning("******************* RUNNING HEADLESS *******************")
  2236. # #####################################################################################
  2237. # ########################## START-UP ARGUMENTS #######################################
  2238. # #####################################################################################
  2239. # test if the program was started with a script as parameter
  2240. if self.cmd_line_shellvar:
  2241. try:
  2242. cnt = 0
  2243. command_tcl = 0
  2244. for i in self.cmd_line_shellvar.split(','):
  2245. if i is not None:
  2246. # noinspection PyBroadException
  2247. try:
  2248. command_tcl = eval(i)
  2249. except Exception:
  2250. command_tcl = i
  2251. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  2252. cnt += 1
  2253. # if there are Windows paths then replace the path separator with a Unix like one
  2254. if sys.platform == 'win32':
  2255. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  2256. self.shell._sysShell.exec_command(command_tcl_formatted, no_echo=True)
  2257. except Exception as ext:
  2258. print("ERROR: ", ext)
  2259. sys.exit(2)
  2260. if self.cmd_line_shellfile:
  2261. try:
  2262. if self.ui.shell_dock.isHidden():
  2263. self.ui.shell_dock.show()
  2264. with open(self.cmd_line_shellfile, "r") as myfile:
  2265. if show_splash:
  2266. self.splash.showMessage('%s: %ssec\n%s' % (
  2267. _("Canvas initialization started.\n"
  2268. "Canvas initialization finished in"), '%.2f' % self.used_time,
  2269. _("Executing Tcl Script ...")),
  2270. alignment=Qt.AlignBottom | Qt.AlignLeft,
  2271. color=QtGui.QColor("gray"))
  2272. cmd_line_shellfile_text = myfile.read()
  2273. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  2274. except Exception as ext:
  2275. print("ERROR: ", ext)
  2276. sys.exit(2)
  2277. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2278. # the path/file_name must be enclosed in quotes if it contain spaces
  2279. if App.args:
  2280. self.args_at_startup.emit(App.args)
  2281. @staticmethod
  2282. def copy_and_overwrite(from_path, to_path):
  2283. """
  2284. From here:
  2285. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2286. :param from_path: source path
  2287. :param to_path: destination path
  2288. :return: None
  2289. """
  2290. if os.path.exists(to_path):
  2291. shutil.rmtree(to_path)
  2292. try:
  2293. shutil.copytree(from_path, to_path)
  2294. except FileNotFoundError:
  2295. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2296. shutil.copytree(from_new_path, to_path)
  2297. def on_startup_args(self, args, silent=False):
  2298. """
  2299. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2300. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  2301. :param args: a list containing the application args at startup
  2302. :return: None
  2303. """
  2304. if args is not None:
  2305. args_to_process = args
  2306. else:
  2307. args_to_process = App.args
  2308. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2309. for argument in args_to_process:
  2310. if '.FlatPrj'.lower() in argument.lower():
  2311. try:
  2312. project_name = str(argument)
  2313. if project_name == "":
  2314. if silent is False:
  2315. self.inform.emit(_("Open cancelled."))
  2316. else:
  2317. # self.open_project(project_name)
  2318. run_from_arg = True
  2319. # self.worker_task.emit({'fcn': self.open_project,
  2320. # 'params': [project_name, run_from_arg]})
  2321. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2322. except Exception as e:
  2323. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2324. elif '.FlatConfig'.lower() in argument.lower():
  2325. try:
  2326. file_name = str(argument)
  2327. if file_name == "":
  2328. if silent is False:
  2329. self.inform.emit(_("Open Config file failed."))
  2330. else:
  2331. run_from_arg = True
  2332. # self.worker_task.emit({'fcn': self.open_config_file,
  2333. # 'params': [file_name, run_from_arg]})
  2334. self.open_config_file(file_name, run_from_arg=run_from_arg)
  2335. except Exception as e:
  2336. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2337. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  2338. try:
  2339. file_name = str(argument)
  2340. if file_name == "":
  2341. if silent is False:
  2342. self.inform.emit(_("Open Script file failed."))
  2343. else:
  2344. if silent is False:
  2345. self.on_fileopenscript(name=file_name)
  2346. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  2347. self.on_filerunscript(name=file_name)
  2348. except Exception as e:
  2349. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2350. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  2351. log.debug("App.on_startup_args() --> Quit event.")
  2352. sys.exit()
  2353. elif 'save'.lower() in argument.lower():
  2354. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  2355. self.save_defaults()
  2356. else:
  2357. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2358. proc_arg = argument.lower()
  2359. for ext in exc_list:
  2360. proc_ext = ext.replace(' ', '')
  2361. proc_ext = '.%s' % proc_ext
  2362. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2363. file_name = str(argument)
  2364. if file_name == "":
  2365. if silent is False:
  2366. self.inform.emit(_("Open Excellon file failed."))
  2367. else:
  2368. self.on_fileopenexcellon(name=file_name)
  2369. return
  2370. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2371. for ext in gco_list:
  2372. proc_ext = ext.replace(' ', '')
  2373. proc_ext = '.%s' % proc_ext
  2374. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2375. file_name = str(argument)
  2376. if file_name == "":
  2377. if silent is False:
  2378. self.inform.emit(_("Open GCode file failed."))
  2379. else:
  2380. self.on_fileopengcode(name=file_name)
  2381. return
  2382. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2383. for ext in grb_list:
  2384. proc_ext = ext.replace(' ', '')
  2385. proc_ext = '.%s' % proc_ext
  2386. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2387. file_name = str(argument)
  2388. if file_name == "":
  2389. if silent is False:
  2390. self.inform.emit(_("Open Gerber file failed."))
  2391. else:
  2392. self.on_fileopengerber(name=file_name)
  2393. return
  2394. # if it reached here without already returning then the app was registered with a file that it does not
  2395. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  2396. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  2397. # for arg in args_to_process:
  2398. # if 'FlatCAM.exe' in arg:
  2399. # continue
  2400. # else:
  2401. # sys.exit(2)
  2402. def set_ui_title(self, name):
  2403. """
  2404. Sets the title of the main window.
  2405. :param name: String that store the project path and project name
  2406. :return: None
  2407. """
  2408. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  2409. (self.version,
  2410. ('BETA' if self.beta else ''),
  2411. platform.architecture()[0],
  2412. self.engine,
  2413. name)
  2414. )
  2415. def on_theme_change(self, val):
  2416. t_settings = QSettings("Open Source", "FlatCAM")
  2417. t_settings.setValue('theme', val)
  2418. # This will write the setting to the platform specific storage.
  2419. del t_settings
  2420. self.on_app_restart()
  2421. def on_app_restart(self):
  2422. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  2423. # be left in the SySTray
  2424. try:
  2425. self.trayIcon.hide()
  2426. except Exception:
  2427. pass
  2428. fcTranslate.restart_program(app=self)
  2429. def defaults_read_form(self):
  2430. """
  2431. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2432. :return: None
  2433. """
  2434. for option in self.defaults_form_fields:
  2435. try:
  2436. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2437. except Exception as e:
  2438. log.debug("App.defaults_read_form() --> %s" % str(e))
  2439. def defaults_write_form(self, factor=None, fl_units=None):
  2440. """
  2441. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2442. self.defaults dictionary.
  2443. :param factor: will apply a factor to the values that written in the GUI elements
  2444. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2445. :return: None
  2446. """
  2447. for option in self.defaults:
  2448. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2449. # try:
  2450. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2451. # except KeyError:
  2452. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2453. # # TODO: Rethink this?
  2454. # pass
  2455. def defaults_write_form_field(self, field, factor=None, units=None):
  2456. """
  2457. Basically it is the worker in the self.defaults_write_form()
  2458. :param field: the GUI element in Preferences GUI to be updated
  2459. :param factor: factor to be applied to the field parameter
  2460. :param units: current FLatCAM measuring units
  2461. :return: None, it updates GUI elements
  2462. """
  2463. try:
  2464. if factor is None:
  2465. if units is None:
  2466. self.defaults_form_fields[field].set_value(self.defaults[field])
  2467. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2468. self.defaults_form_fields[field].set_value(self.defaults[field])
  2469. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2470. self.defaults_form_fields[field].set_value(self.defaults[field])
  2471. else:
  2472. if units is None:
  2473. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2474. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2475. self.defaults_form_fields[field].set_value((self.defaults[field] * factor))
  2476. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2477. self.defaults_form_fields[field].set_value((self.defaults[field] * factor))
  2478. except KeyError:
  2479. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2480. # TODO: Rethink this?
  2481. pass
  2482. except AttributeError:
  2483. log.debug(field)
  2484. def clear_pool(self):
  2485. """
  2486. Clear the multiprocessing pool and calls garbage collector.
  2487. :return: None
  2488. """
  2489. self.pool.close()
  2490. self.pool = Pool()
  2491. self.pool_recreated.emit(self.pool)
  2492. gc.collect()
  2493. def install_tools(self):
  2494. """
  2495. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2496. Instantiation of the Tools classes.
  2497. The order that the tools are installed is important as they can depend on each other install position.
  2498. :return: None
  2499. """
  2500. self.dblsidedtool = DblSidedTool(self)
  2501. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2502. self.cal_exc_tool = ToolCalibrateExcellon(self)
  2503. self.cal_exc_tool.install(icon=QtGui.QIcon('share/drill16.png'), pos=self.ui.menutool,
  2504. before=self.dblsidedtool.menuAction,
  2505. separator=False)
  2506. self.distance_tool = Distance(self)
  2507. self.distance_tool.install(icon=QtGui.QIcon('share/distance16.png'), pos=self.ui.menuedit,
  2508. before=self.ui.menueditorigin,
  2509. separator=False)
  2510. self.distance_min_tool = DistanceMin(self)
  2511. self.distance_min_tool.install(icon=QtGui.QIcon('share/distance_min16.png'), pos=self.ui.menuedit,
  2512. before=self.ui.menueditorigin,
  2513. separator=True)
  2514. self.panelize_tool = Panelize(self)
  2515. self.panelize_tool.install(icon=QtGui.QIcon('share/panelize16.png'))
  2516. self.film_tool = Film(self)
  2517. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2518. self.paste_tool = SolderPaste(self)
  2519. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2520. self.calculator_tool = ToolCalculator(self)
  2521. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator16.png'), separator=True)
  2522. self.sub_tool = ToolSub(self)
  2523. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2524. self.rules_tool = RulesCheck(self)
  2525. self.rules_tool.install(icon=QtGui.QIcon('share/rules32.png'), pos=self.ui.menutool, separator=False)
  2526. self.optimal_tool = ToolOptimal(self)
  2527. self.optimal_tool.install(icon=QtGui.QIcon('share/open_excellon32.png'), pos=self.ui.menutool, separator=True)
  2528. self.move_tool = ToolMove(self)
  2529. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2530. before=self.ui.menueditorigin, separator=True)
  2531. self.cutout_tool = CutOut(self)
  2532. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2533. before=self.sub_tool.menuAction)
  2534. self.ncclear_tool = NonCopperClear(self)
  2535. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2536. before=self.sub_tool.menuAction, separator=True)
  2537. self.paint_tool = ToolPaint(self)
  2538. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2539. before=self.sub_tool.menuAction, separator=True)
  2540. self.copper_thieving_tool = ToolCopperThieving(self)
  2541. self.copper_thieving_tool.install(icon=QtGui.QIcon('share/copperfill32.png'), pos=self.ui.menutool)
  2542. self.fiducial_tool = ToolFiducials(self)
  2543. self.fiducial_tool.install(icon=QtGui.QIcon('share/fiducials_32.png'), pos=self.ui.menutool)
  2544. self.qrcode_tool = QRCode(self)
  2545. self.qrcode_tool.install(icon=QtGui.QIcon('share/qrcode32.png'), pos=self.ui.menutool)
  2546. self.transform_tool = ToolTransform(self)
  2547. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2548. self.properties_tool = Properties(self)
  2549. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2550. self.pdf_tool = ToolPDF(self)
  2551. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2552. separator=True)
  2553. self.image_tool = ToolImage(self)
  2554. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2555. separator=True)
  2556. self.pcb_wizard_tool = PcbWizard(self)
  2557. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2558. self.log.debug("Tools are installed.")
  2559. def remove_tools(self):
  2560. """
  2561. Will remove all the actions in the Tool menu.
  2562. :return: None
  2563. """
  2564. for act in self.ui.menutool.actions():
  2565. self.ui.menutool.removeAction(act)
  2566. def init_tools(self):
  2567. """
  2568. Initialize the Tool tab in the notebook side of the central widget.
  2569. Remove the actions in the Tools menu.
  2570. Instantiate again the FlatCAM tools (plugins).
  2571. All this is required when changing the layout: standard, compact etc.
  2572. :return: None
  2573. """
  2574. log.debug("init_tools()")
  2575. # delete the data currently in the Tools Tab and the Tab itself
  2576. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2577. if widget is not None:
  2578. widget.deleteLater()
  2579. self.ui.notebook.removeTab(2)
  2580. # rebuild the Tools Tab
  2581. self.ui.tool_tab = QtWidgets.QWidget()
  2582. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2583. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2584. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2585. self.ui.tool_scroll_area = VerticalScrollArea()
  2586. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2587. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2588. # first remove all of them
  2589. self.remove_tools()
  2590. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2591. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2592. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2593. # third install all of them
  2594. self.install_tools()
  2595. self.log.debug("Tools are initialized.")
  2596. # def parse_system_fonts(self):
  2597. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2598. # 'params': []})
  2599. def connect_toolbar_signals(self):
  2600. """
  2601. Reconnect the signals to the actions in the toolbar.
  2602. This has to be done each time after the FlatCAM tools are removed/installed.
  2603. :return: None
  2604. """
  2605. # Toolbar
  2606. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2607. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2608. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2609. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2610. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2611. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2612. self.ui.replot_btn.triggered.connect(self.plot_all)
  2613. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2614. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2615. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2616. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2617. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2618. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2619. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2620. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2621. self.ui.copy_btn.triggered.connect(self.on_copy_object)
  2622. self.ui.delete_btn.triggered.connect(self.on_delete)
  2623. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  2624. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  2625. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  2626. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  2627. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2628. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2629. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2630. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2631. # Tools Toolbar Signals
  2632. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2633. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2634. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2635. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2636. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2637. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2638. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2639. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2640. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  2641. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  2642. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2643. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2644. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  2645. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  2646. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  2647. def object2editor(self):
  2648. """
  2649. Send the current Geometry or Excellon object (if any) into the it's editor.
  2650. :return: None
  2651. """
  2652. self.report_usage("object2editor()")
  2653. # disable the objects menu as it may interfere with the Editors
  2654. self.ui.menuobjects.setDisabled(True)
  2655. edited_object = self.collection.get_active()
  2656. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2657. isinstance(edited_object, FlatCAMExcellon):
  2658. pass
  2659. else:
  2660. self.inform.emit('[WARNING_NOTCL] %s' %
  2661. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2662. return
  2663. if isinstance(edited_object, FlatCAMGeometry):
  2664. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2665. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2666. # we set the notebook to hidden
  2667. self.ui.splitter.setSizes([0, 1])
  2668. if edited_object.multigeo is True:
  2669. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  2670. if len(sel_rows) > 1:
  2671. self.inform.emit('[WARNING_NOTCL] %s' %
  2672. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  2673. "is not possible.\n"
  2674. "Edit only one geometry at a time."))
  2675. # determine the tool dia of the selected tool
  2676. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  2677. # now find the key in the edited_object.tools that has this tooldia
  2678. multi_tool = 1
  2679. for tool in edited_object.tools:
  2680. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2681. multi_tool = tool
  2682. break
  2683. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2684. else:
  2685. self.geo_editor.edit_fcgeometry(edited_object)
  2686. # set call source to the Editor we go into
  2687. self.call_source = 'geo_editor'
  2688. elif isinstance(edited_object, FlatCAMExcellon):
  2689. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2690. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2691. if self.ui.splitter.sizes()[0] == 0:
  2692. self.ui.splitter.setSizes([1, 1])
  2693. self.exc_editor.edit_fcexcellon(edited_object)
  2694. # set call source to the Editor we go into
  2695. self.call_source = 'exc_editor'
  2696. elif isinstance(edited_object, FlatCAMGerber):
  2697. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2698. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2699. if self.ui.splitter.sizes()[0] == 0:
  2700. self.ui.splitter.setSizes([1, 1])
  2701. self.grb_editor.edit_fcgerber(edited_object)
  2702. # set call source to the Editor we go into
  2703. self.call_source = 'grb_editor'
  2704. # make sure that we can't select another object while in Editor Mode:
  2705. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2706. self.ui.project_frame.setDisabled(True)
  2707. # delete any selection shape that might be active as they are not relevant in Editor
  2708. self.delete_selection_shape()
  2709. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2710. self.ui.plot_tab_area.protectTab(0)
  2711. self.inform.emit('[WARNING_NOTCL] %s' %
  2712. _("Editor is activated ..."))
  2713. self.should_we_save = True
  2714. def editor2object(self, cleanup=None):
  2715. """
  2716. Transfers the Geometry or Excellon from it's editor to the current object.
  2717. :return: None
  2718. """
  2719. self.report_usage("editor2object()")
  2720. # re-enable the objects menu that was disabled on entry in Editor mode
  2721. self.ui.menuobjects.setDisabled(False)
  2722. # do not update a geometry or excellon object unless it comes out of an editor
  2723. if self.call_source != 'app':
  2724. edited_obj = self.collection.get_active()
  2725. if cleanup is None:
  2726. msgbox = QtWidgets.QMessageBox()
  2727. msgbox.setText(_("Do you want to save the edited object?"))
  2728. msgbox.setWindowTitle(_("Close Editor"))
  2729. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2730. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2731. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2732. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2733. msgbox.setDefaultButton(bt_yes)
  2734. msgbox.exec_()
  2735. response = msgbox.clickedButton()
  2736. if response == bt_yes:
  2737. # clean the Tools Tab
  2738. self.ui.tool_scroll_area.takeWidget()
  2739. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2740. self.ui.notebook.setTabText(2, "Tool")
  2741. if isinstance(edited_obj, FlatCAMGeometry):
  2742. obj_type = "Geometry"
  2743. if cleanup is None:
  2744. self.geo_editor.update_fcgeometry(edited_obj)
  2745. self.geo_editor.update_options(edited_obj)
  2746. self.geo_editor.deactivate()
  2747. # update the geo object options so it is including the bounding box values
  2748. try:
  2749. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2750. edited_obj.options['xmin'] = xmin
  2751. edited_obj.options['ymin'] = ymin
  2752. edited_obj.options['xmax'] = xmax
  2753. edited_obj.options['ymax'] = ymax
  2754. except AttributeError as e:
  2755. self.inform.emit('[WARNING] %s' %
  2756. _("Object empty after edit."))
  2757. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2758. elif isinstance(edited_obj, FlatCAMGerber):
  2759. obj_type = "Gerber"
  2760. if cleanup is None:
  2761. self.grb_editor.update_fcgerber()
  2762. self.grb_editor.update_options(edited_obj)
  2763. self.grb_editor.deactivate_grb_editor()
  2764. # delete the old object (the source object) if it was an empty one
  2765. try:
  2766. if len(edited_obj.solid_geometry) == 0:
  2767. old_name = edited_obj.options['name']
  2768. self.collection.set_active(old_name)
  2769. self.collection.delete_active()
  2770. except TypeError:
  2771. # if the solid_geometry is a single Polygon the len() will not work
  2772. # in any case, falling here means that we have something in the solid_geometry, even if only
  2773. # a single Polygon, therefore we pass this
  2774. pass
  2775. # restore GUI to the Selected TAB
  2776. # Remove anything else in the GUI
  2777. self.ui.selected_scroll_area.takeWidget()
  2778. # Switch notebook to Selected page
  2779. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2780. elif isinstance(edited_obj, FlatCAMExcellon):
  2781. obj_type = "Excellon"
  2782. if cleanup is None:
  2783. self.exc_editor.update_fcexcellon(edited_obj)
  2784. self.exc_editor.update_options(edited_obj)
  2785. self.exc_editor.deactivate()
  2786. # delete the old object (the source object) if it was an empty one
  2787. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  2788. old_name = edited_obj.options['name']
  2789. self.collection.set_active(old_name)
  2790. self.collection.delete_active()
  2791. # restore GUI to the Selected TAB
  2792. # Remove anything else in the GUI
  2793. self.ui.tool_scroll_area.takeWidget()
  2794. # Switch notebook to Selected page
  2795. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2796. else:
  2797. self.inform.emit('[WARNING_NOTCL] %s' %
  2798. _("Select a Gerber, Geometry or Excellon Object to update."))
  2799. return
  2800. self.inform.emit('[selected] %s %s' %
  2801. (obj_type, _("is updated, returning to App...")))
  2802. elif response == bt_no:
  2803. # clean the Tools Tab
  2804. self.ui.tool_scroll_area.takeWidget()
  2805. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2806. self.ui.notebook.setTabText(2, "Tool")
  2807. if isinstance(edited_obj, FlatCAMGeometry):
  2808. self.geo_editor.deactivate()
  2809. elif isinstance(edited_obj, FlatCAMGerber):
  2810. self.grb_editor.deactivate_grb_editor()
  2811. elif isinstance(edited_obj, FlatCAMExcellon):
  2812. self.exc_editor.deactivate()
  2813. # set focus on the project tab
  2814. else:
  2815. self.inform.emit('[WARNING_NOTCL] %s' %
  2816. _("Select a Gerber, Geometry or Excellon Object to update."))
  2817. return
  2818. edited_obj.set_ui(edited_obj.ui_type())
  2819. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2820. elif response == bt_cancel:
  2821. return
  2822. else:
  2823. if isinstance(edited_obj, FlatCAMGeometry):
  2824. self.geo_editor.deactivate()
  2825. elif isinstance(edited_obj, FlatCAMGerber):
  2826. self.grb_editor.deactivate_grb_editor()
  2827. elif isinstance(edited_obj, FlatCAMExcellon):
  2828. self.exc_editor.deactivate()
  2829. else:
  2830. self.inform.emit('[WARNING_NOTCL] %s' %
  2831. _("Select a Gerber, Geometry or Excellon Object to update."))
  2832. return
  2833. # if notebook is hidden we show it
  2834. if self.ui.splitter.sizes()[0] == 0:
  2835. self.ui.splitter.setSizes([1, 1])
  2836. # restore the call_source to app
  2837. self.call_source = 'app'
  2838. edited_obj.plot()
  2839. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2840. self.ui.plot_tab_area.protectTab(0)
  2841. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2842. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2843. self.ui.project_frame.setDisabled(False)
  2844. def get_last_folder(self):
  2845. """
  2846. Get the folder path from where the last file was opened.
  2847. :return: String, last opened folder path
  2848. """
  2849. return self.defaults["global_last_folder"]
  2850. def get_last_save_folder(self):
  2851. """
  2852. Get the folder path from where the last file was saved.
  2853. :return: String, last saved folder path
  2854. """
  2855. loc = self.defaults["global_last_save_folder"]
  2856. if loc is None:
  2857. loc = self.defaults["global_last_folder"]
  2858. if loc is None:
  2859. loc = os.path.dirname(__file__)
  2860. return loc
  2861. def report_usage(self, resource):
  2862. """
  2863. Increments usage counter for the given resource
  2864. in self.defaults['global_stats'].
  2865. :param resource: Name of the resource.
  2866. :return: None
  2867. """
  2868. if resource in self.defaults['global_stats']:
  2869. self.defaults['global_stats'][resource] += 1
  2870. else:
  2871. self.defaults['global_stats'][resource] = 1
  2872. def init_tcl(self):
  2873. """
  2874. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2875. :return: None
  2876. """
  2877. if hasattr(self, 'tcl') and self.tcl is not None:
  2878. # self.tcl = None
  2879. # TODO we need to clean non default variables and procedures here
  2880. # new object cannot be used here as it will not remember values created for next passes,
  2881. # because tcl was execudted in old instance of TCL
  2882. pass
  2883. else:
  2884. self.tcl = tk.Tcl()
  2885. self.setup_shell()
  2886. self.log.debug("TCL Shell has been initialized.")
  2887. # TODO: This shouldn't be here.
  2888. class TclErrorException(Exception):
  2889. """
  2890. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2891. """
  2892. pass
  2893. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2894. """
  2895. Shows a message on the FlatCAM Shell
  2896. :param msg: Message to display.
  2897. :param show: Opens the shell.
  2898. :param error: Shows the message as an error.
  2899. :param warning: Shows the message as an warning.
  2900. :param success: Shows the message as an success.
  2901. :param selected: Indicate that something was selected on canvas
  2902. :return: None
  2903. """
  2904. if show:
  2905. self.ui.shell_dock.show()
  2906. try:
  2907. if error:
  2908. self.shell.append_error(msg + "\n")
  2909. elif warning:
  2910. self.shell.append_warning(msg + "\n")
  2911. elif success:
  2912. self.shell.append_success(msg + "\n")
  2913. elif selected:
  2914. self.shell.append_selected(msg + "\n")
  2915. else:
  2916. self.shell.append_output(msg + "\n")
  2917. except AttributeError:
  2918. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2919. def raise_tcl_unknown_error(self, unknownException):
  2920. """
  2921. Raise exception if is different type than TclErrorException
  2922. this is here mainly to show unknown errors inside TCL shell console.
  2923. :param unknownException:
  2924. :return:
  2925. """
  2926. if not isinstance(unknownException, self.TclErrorException):
  2927. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2928. else:
  2929. raise unknownException
  2930. def display_tcl_error(self, error, error_info=None):
  2931. """
  2932. Escape bracket [ with '\' otherwise there is error
  2933. "ERROR: missing close-bracket" instead of real error
  2934. :param error: it may be text or exception
  2935. :param error_info: Some informations about the error
  2936. :return: None
  2937. """
  2938. if isinstance(error, Exception):
  2939. exc_type, exc_value, exc_traceback = error_info
  2940. if not isinstance(error, self.TclErrorException):
  2941. show_trace = 1
  2942. else:
  2943. show_trace = int(self.defaults['global_verbose_error_level'])
  2944. if show_trace > 0:
  2945. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2946. trc_formated = []
  2947. for a in reversed(trc):
  2948. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2949. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2950. else:
  2951. text = "%s" % error
  2952. else:
  2953. text = error
  2954. text = text.replace('[', '\\[').replace('"', '\\"')
  2955. self.tcl.eval('return -code error "%s"' % text)
  2956. def raise_tcl_error(self, text):
  2957. """
  2958. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2959. :param text: text of error
  2960. :return: raise exception
  2961. """
  2962. self.display_tcl_error(text)
  2963. raise self.TclErrorException(text)
  2964. def exec_command(self, text, no_echo=False):
  2965. """
  2966. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2967. Also handles execution in separated threads
  2968. :param text: FlatCAM TclCommand with parameters
  2969. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2970. will create crashes of the _Expandable_Edit widget
  2971. :return: output if there was any
  2972. """
  2973. self.report_usage('exec_command')
  2974. result = self.exec_command_test(text, False, no_echo=no_echo)
  2975. # MS: added this method call so the geometry is updated once the TCL command is executed
  2976. # if no_plot is None:
  2977. # self.plot_all()
  2978. return result
  2979. def exec_command_test(self, text, reraise=True, no_echo=False):
  2980. """
  2981. Same as exec_command(...) with additional control over exceptions.
  2982. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2983. :param text: Input command
  2984. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2985. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2986. will create crashes of the _Expandable_Edit widget
  2987. :return: Output from the command
  2988. """
  2989. tcl_command_string = str(text)
  2990. try:
  2991. if no_echo is False:
  2992. self.shell.open_proccessing() # Disables input box.
  2993. result = self.tcl.eval(str(tcl_command_string))
  2994. if result != 'None' and no_echo is False:
  2995. self.shell.append_output(result + '\n')
  2996. except tk.TclError as e:
  2997. # This will display more precise answer if something in TCL shell fails
  2998. result = self.tcl.eval("set errorInfo")
  2999. self.log.error("Exec command Exception: %s" % (result + '\n'))
  3000. if no_echo is False:
  3001. self.shell.append_error('ERROR: ' + result + '\n')
  3002. # Show error in console and just return or in test raise exception
  3003. if reraise:
  3004. raise e
  3005. finally:
  3006. if no_echo is False:
  3007. self.shell.close_proccessing()
  3008. pass
  3009. return result
  3010. # """
  3011. # Code below is unsused. Saved for later.
  3012. # """
  3013. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  3014. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  3015. # self.log.debug(parts)
  3016. # try:
  3017. # if parts[0] not in commands:
  3018. # self.shell.append_error("Unknown command\n")
  3019. # return
  3020. #
  3021. # #import inspect
  3022. # #inspect.getargspec(someMethod)
  3023. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  3024. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  3025. # self.shell.append_error(
  3026. # "Command %s takes %d arguments. %d given.\n" %
  3027. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  3028. # )
  3029. # return
  3030. #
  3031. # cmdfcn = commands[parts[0]]["fcn"]
  3032. # cmdconv = commands[parts[0]]["converters"]
  3033. # if len(parts) - 1 > 0:
  3034. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  3035. # else:
  3036. # retval = cmdfcn()
  3037. # retfcn = commands[parts[0]]["retfcn"]
  3038. # if retval and retfcn(retval):
  3039. # self.shell.append_output(retfcn(retval) + "\n")
  3040. #
  3041. # except Exception as e:
  3042. # #self.shell.append_error(''.join(traceback.format_exc()))
  3043. # #self.shell.append_error("?\n")
  3044. # self.shell.append_error(str(e) + "\n")
  3045. def info(self, msg):
  3046. """
  3047. Informs the user. Normally on the status bar, optionally
  3048. also on the shell.
  3049. :param msg: Text to write.
  3050. :return: None
  3051. """
  3052. # Type of message in brackets at the beginning of the message.
  3053. match = re.search("\[([^\]]+)\](.*)", msg)
  3054. if match:
  3055. level = match.group(1)
  3056. msg_ = match.group(2)
  3057. self.ui.fcinfo.set_status(str(msg_), level=level)
  3058. if level.lower() == "error":
  3059. self.shell_message(msg, error=True, show=True)
  3060. elif level.lower() == "warning":
  3061. self.shell_message(msg, warning=True, show=True)
  3062. elif level.lower() == "error_notcl":
  3063. self.shell_message(msg, error=True, show=False)
  3064. elif level.lower() == "warning_notcl":
  3065. self.shell_message(msg, warning=True, show=False)
  3066. elif level.lower() == "success":
  3067. self.shell_message(msg, success=True, show=False)
  3068. elif level.lower() == "selected":
  3069. self.shell_message(msg, selected=True, show=False)
  3070. else:
  3071. self.shell_message(msg, show=False)
  3072. else:
  3073. self.ui.fcinfo.set_status(str(msg), level="info")
  3074. # make sure that if the message is to clear the infobar with a space
  3075. # is not printed over and over on the shell
  3076. if msg != '':
  3077. self.shell_message(msg)
  3078. def restore_toolbar_view(self):
  3079. """
  3080. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  3081. was saved in the defaults dictionary.
  3082. :return: None
  3083. """
  3084. tb = self.defaults["global_toolbar_view"]
  3085. if tb & 1:
  3086. self.ui.toolbarfile.setVisible(True)
  3087. else:
  3088. self.ui.toolbarfile.setVisible(False)
  3089. if tb & 2:
  3090. self.ui.toolbargeo.setVisible(True)
  3091. else:
  3092. self.ui.toolbargeo.setVisible(False)
  3093. if tb & 4:
  3094. self.ui.toolbarview.setVisible(True)
  3095. else:
  3096. self.ui.toolbarview.setVisible(False)
  3097. if tb & 8:
  3098. self.ui.toolbartools.setVisible(True)
  3099. else:
  3100. self.ui.toolbartools.setVisible(False)
  3101. if tb & 16:
  3102. self.ui.exc_edit_toolbar.setVisible(True)
  3103. else:
  3104. self.ui.exc_edit_toolbar.setVisible(False)
  3105. if tb & 32:
  3106. self.ui.geo_edit_toolbar.setVisible(True)
  3107. else:
  3108. self.ui.geo_edit_toolbar.setVisible(False)
  3109. if tb & 64:
  3110. self.ui.grb_edit_toolbar.setVisible(True)
  3111. else:
  3112. self.ui.grb_edit_toolbar.setVisible(False)
  3113. if tb & 128:
  3114. self.ui.snap_toolbar.setVisible(True)
  3115. else:
  3116. self.ui.snap_toolbar.setVisible(False)
  3117. if tb & 256:
  3118. self.ui.toolbarshell.setVisible(True)
  3119. else:
  3120. self.ui.toolbarshell.setVisible(False)
  3121. def load_defaults(self, filename):
  3122. """
  3123. Loads the aplication's default settings from current_defaults.FlatConfig into
  3124. ``self.defaults``.
  3125. :return: None
  3126. """
  3127. try:
  3128. f = open(self.data_path + "/" + filename + ".FlatConfig")
  3129. options = f.read()
  3130. f.close()
  3131. except IOError:
  3132. self.log.error("Could not load defaults file.")
  3133. self.inform.emit('[ERROR] %s' %
  3134. _("Could not load defaults file."))
  3135. # in case the defaults file can't be loaded, show all toolbars
  3136. self.defaults["global_toolbar_view"] = 511
  3137. return
  3138. try:
  3139. defaults = json.loads(options)
  3140. except Exception:
  3141. # in case the defaults file can't be loaded, show all toolbars
  3142. self.defaults["global_toolbar_view"] = 511
  3143. e = sys.exc_info()[0]
  3144. App.log.error(str(e))
  3145. self.inform.emit('[ERROR] %s' % _("Failed to parse defaults file."))
  3146. return
  3147. self.defaults.update(defaults)
  3148. log.debug("FlatCAM defaults loaded from: %s" % filename)
  3149. def on_import_preferences(self):
  3150. """
  3151. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  3152. ``self.defaults``.
  3153. :return: None
  3154. """
  3155. self.report_usage("on_import_preferences")
  3156. App.log.debug("on_import_preferences()")
  3157. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  3158. try:
  3159. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3160. directory=self.data_path,
  3161. filter=filter_)
  3162. except TypeError:
  3163. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3164. filter=filter_)
  3165. filename = str(filename)
  3166. if filename == "":
  3167. self.inform.emit('[WARNING_NOTCL] %s' %
  3168. _("FlatCAM preferences import cancelled."))
  3169. else:
  3170. try:
  3171. f = open(filename)
  3172. options = f.read()
  3173. f.close()
  3174. except IOError:
  3175. self.log.error("Could not load defaults file.")
  3176. self.inform.emit('[ERROR_NOTCL] %s' %
  3177. _("Could not load defaults file."))
  3178. return
  3179. try:
  3180. defaults_from_file = json.loads(options)
  3181. except Exception:
  3182. e = sys.exc_info()[0]
  3183. App.log.error(str(e))
  3184. self.inform.emit('[ERROR_NOTCL] %s' %
  3185. _("Failed to parse defaults file."))
  3186. return
  3187. self.defaults.update(defaults_from_file)
  3188. self.on_preferences_edited()
  3189. self.inform.emit('[success] %s: %s' %
  3190. (_("Imported Defaults from"), filename))
  3191. def on_export_preferences(self):
  3192. """
  3193. Save the defaults dictionary to a file.
  3194. :return: None
  3195. """
  3196. self.report_usage("on_export_preferences")
  3197. App.log.debug("on_export_preferences()")
  3198. defaults_file_content = None
  3199. self.date = str(datetime.today()).rpartition('.')[0]
  3200. self.date = ''.join(c for c in self.date if c not in ':-')
  3201. self.date = self.date.replace(' ', '_')
  3202. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  3203. try:
  3204. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  3205. caption=_("Export FlatCAM Preferences"),
  3206. directory=self.data_path + '/preferences_' + self.date,
  3207. filter=filter__
  3208. )
  3209. except TypeError:
  3210. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  3211. filter=filter__)
  3212. filename = str(filename)
  3213. defaults_from_file = {}
  3214. if filename == "":
  3215. self.inform.emit('[WARNING_NOTCL] %s' %
  3216. _("FlatCAM preferences export cancelled."))
  3217. return
  3218. else:
  3219. try:
  3220. f = open(filename, 'w')
  3221. defaults_file_content = f.read()
  3222. f.close()
  3223. except PermissionError:
  3224. self.inform.emit('[WARNING] %s' %
  3225. _("Permission denied, saving not possible.\n"
  3226. "Most likely another app is holding the file open and not accessible."))
  3227. return
  3228. except IOError:
  3229. App.log.debug('Creating a new preferences file ...')
  3230. f = open(filename, 'w')
  3231. json.dump({}, f)
  3232. f.close()
  3233. except Exception:
  3234. e = sys.exc_info()[0]
  3235. App.log.error("Could not load defaults file.")
  3236. App.log.error(str(e))
  3237. self.inform.emit('[ERROR_NOTCL] %s' %
  3238. _("Could not load preferences file."))
  3239. return
  3240. try:
  3241. defaults_from_file = json.loads(defaults_file_content)
  3242. except Exception:
  3243. App.log.warning("Trying to read an empty Preferences file. Continue.")
  3244. # Update options
  3245. self.defaults_read_form()
  3246. defaults_from_file.update(self.defaults)
  3247. self.propagate_defaults(silent=True)
  3248. # Save update options
  3249. try:
  3250. f = open(filename, "w")
  3251. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  3252. f.close()
  3253. except Exception:
  3254. self.inform.emit('[ERROR_NOTCL] %s' %
  3255. _("Failed to write defaults to file."))
  3256. return
  3257. if self.defaults["global_open_style"] is False:
  3258. self.file_opened.emit("preferences", filename)
  3259. self.file_saved.emit("preferences", filename)
  3260. self.inform.emit('[success] %s: %s' %
  3261. (_("Exported preferences to"), filename))
  3262. def on_preferences_open_folder(self):
  3263. """
  3264. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  3265. :return: None
  3266. """
  3267. self.report_usage("on_preferences_open_folder()")
  3268. if sys.platform == 'win32':
  3269. subprocess.Popen('explorer %s' % self.data_path)
  3270. elif sys.platform == 'darwin':
  3271. os.system('open "%s"' % self.data_path)
  3272. else:
  3273. subprocess.Popen(['xdg-open', self.data_path])
  3274. self.inform.emit('[success] %s' %
  3275. _("FlatCAM Preferences Folder opened."))
  3276. def save_geometry(self, x, y, width, height, notebook_width):
  3277. """
  3278. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  3279. launch of the application.
  3280. :param x: X position of the main window
  3281. :param y: Y position of the main window
  3282. :param width: width of the main window
  3283. :param height: height of the main window
  3284. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  3285. :return: None
  3286. """
  3287. self.defaults["global_def_win_x"] = x
  3288. self.defaults["global_def_win_y"] = y
  3289. self.defaults["global_def_win_w"] = width
  3290. self.defaults["global_def_win_h"] = height
  3291. self.defaults["global_def_notebook_width"] = notebook_width
  3292. self.save_defaults()
  3293. def restore_main_win_geom(self):
  3294. try:
  3295. self.ui.setGeometry(self.defaults["global_def_win_x"],
  3296. self.defaults["global_def_win_y"],
  3297. self.defaults["global_def_win_w"],
  3298. self.defaults["global_def_win_h"])
  3299. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  3300. except KeyError as e:
  3301. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  3302. def message_dialog(self, title, message, kind="info"):
  3303. """
  3304. Builds and show a custom QMessageBox to be used in FlatCAM.
  3305. :param title: title of the QMessageBox
  3306. :param message: message to be displayed
  3307. :param kind: type of QMessageBox; will display a specific icon.
  3308. :return:
  3309. """
  3310. icon = {"info": QtWidgets.QMessageBox.Information,
  3311. "warning": QtWidgets.QMessageBox.Warning,
  3312. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3313. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  3314. dlg.setText(message)
  3315. dlg.exec_()
  3316. def register_recent(self, kind, filename):
  3317. """
  3318. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  3319. dictionary.
  3320. :param kind: type of file that was opened
  3321. :param filename: the path and file name for the file that was opened
  3322. :return:
  3323. """
  3324. self.log.debug("register_recent()")
  3325. self.log.debug(" %s" % kind)
  3326. self.log.debug(" %s" % filename)
  3327. record = {'kind': str(kind), 'filename': str(filename)}
  3328. if record in self.recent:
  3329. return
  3330. if record in self.recent_projects:
  3331. return
  3332. if record['kind'] == 'project':
  3333. self.recent_projects.insert(0, record)
  3334. else:
  3335. self.recent.insert(0, record)
  3336. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3337. self.recent.pop()
  3338. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3339. self.recent_projects.pop()
  3340. try:
  3341. f = open(self.data_path + '/recent.json', 'w')
  3342. except IOError:
  3343. App.log.error("Failed to open recent items file for writing.")
  3344. self.inform.emit('[ERROR_NOTCL] %s' %
  3345. _('Failed to open recent files file for writing.'))
  3346. return
  3347. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3348. f.close()
  3349. try:
  3350. fp = open(self.data_path + '/recent_projects.json', 'w')
  3351. except IOError:
  3352. App.log.error("Failed to open recent items file for writing.")
  3353. self.inform.emit('[ERROR_NOTCL] %s' %
  3354. _('Failed to open recent projects file for writing.'))
  3355. return
  3356. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3357. fp.close()
  3358. # Re-build the recent items menu
  3359. self.setup_recent_items()
  3360. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3361. """
  3362. Creates a new specialized FlatCAMObj and attaches it to the application,
  3363. this is, updates the GUI accordingly, any other records and plots it.
  3364. This method is thread-safe.
  3365. Notes:
  3366. * If the name is in use, the self.collection will modify it
  3367. when appending it to the collection. There is no need to handle
  3368. name conflicts here.
  3369. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3370. :type kind: str
  3371. :param name: Name for the object.
  3372. :type name: str
  3373. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3374. The function is called with 2 parameters: the new object and the App instance.
  3375. :type initialize: function
  3376. :param active:
  3377. :param fit:
  3378. :param plot: If to plot the resulting object
  3379. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3380. self.colleaction
  3381. :return: None
  3382. :rtype: None
  3383. """
  3384. App.log.debug("new_object()")
  3385. obj_plot = plot
  3386. obj_autoselected = autoselected
  3387. t0 = time.time() # Debug
  3388. # ## Create object
  3389. classdict = {
  3390. "gerber": FlatCAMGerber,
  3391. "excellon": FlatCAMExcellon,
  3392. "cncjob": FlatCAMCNCjob,
  3393. "geometry": FlatCAMGeometry,
  3394. "script": FlatCAMScript,
  3395. "document": FlatCAMDocument
  3396. }
  3397. App.log.debug("Calling object constructor...")
  3398. # Object creation/instantiation
  3399. obj = classdict[kind](name)
  3400. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3401. # IMPORTANT
  3402. # The key names in defaults and options dictionary's are not random:
  3403. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3404. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  3405. # copied to self.options. After that, below, depending on the type of
  3406. # object that is created, it will strip the name of the object and the underline (if the original key was
  3407. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3408. # "toolchange"
  3409. for option in self.options:
  3410. if option.find(kind + "_") == 0:
  3411. oname = option[len(kind) + 1:]
  3412. obj.options[oname] = self.options[option]
  3413. obj.isHovering = False
  3414. obj.notHovering = True
  3415. # Initialize as per user request
  3416. # User must take care to implement initialize
  3417. # in a thread-safe way as is is likely that we
  3418. # have been invoked in a separate thread.
  3419. t1 = time.time()
  3420. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3421. try:
  3422. return_value = initialize(obj, self)
  3423. except Exception as e:
  3424. msg = '[ERROR_NOTCL] %s' % \
  3425. _("An internal error has ocurred. See shell.\n")
  3426. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3427. msg += traceback.format_exc()
  3428. self.inform.emit(msg)
  3429. # if str(e) == "Empty Geometry":
  3430. # self.inform.emit("[ERROR_NOTCL] )
  3431. # else:
  3432. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  3433. return "fail"
  3434. t2 = time.time()
  3435. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3436. if return_value == 'fail':
  3437. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3438. return "fail"
  3439. # Check units and convert if necessary
  3440. # This condition CAN be true because initialize() can change obj.units
  3441. if self.options["units"].upper() != obj.units.upper():
  3442. self.inform.emit('%s: %s' %
  3443. (_("Converting units to "), self.options["units"]))
  3444. obj.convert_units(self.options["units"])
  3445. t3 = time.time()
  3446. self.log.debug("%f seconds converting units." % (t3 - t2))
  3447. # Create the bounding box for the object and then add the results to the obj.options
  3448. # But not for Scripts or for Documents
  3449. if kind != 'document' and kind != 'script':
  3450. try:
  3451. xmin, ymin, xmax, ymax = obj.bounds()
  3452. obj.options['xmin'] = xmin
  3453. obj.options['ymin'] = ymin
  3454. obj.options['xmax'] = xmax
  3455. obj.options['ymax'] = ymax
  3456. except Exception as e:
  3457. log.warning("The object has no bounds properties. %s" % str(e))
  3458. return "fail"
  3459. # update the KeyWords list with the name of the file
  3460. self.myKeywords.append(obj.options['name'])
  3461. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3462. # Move the object to the main thread and let the app know that it is available.
  3463. obj.moveToThread(self.main_thread)
  3464. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3465. return obj
  3466. def new_excellon_object(self):
  3467. """
  3468. Creates a new, blank Excellon object.
  3469. :return: None
  3470. """
  3471. self.report_usage("new_excellon_object()")
  3472. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3473. def new_geometry_object(self):
  3474. """
  3475. Creates a new, blank and single-tool Geometry object.
  3476. :return: None
  3477. """
  3478. self.report_usage("new_geometry_object()")
  3479. def initialize(obj, app):
  3480. obj.multitool = False
  3481. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3482. def new_gerber_object(self):
  3483. """
  3484. Creates a new, blank Gerber object.
  3485. :return: None
  3486. """
  3487. self.report_usage("new_gerber_object()")
  3488. def initialize(grb_obj, app):
  3489. grb_obj.multitool = False
  3490. grb_obj.source_file = []
  3491. grb_obj.multigeo = False
  3492. grb_obj.follow = False
  3493. grb_obj.apertures = {}
  3494. grb_obj.solid_geometry = []
  3495. try:
  3496. grb_obj.options['xmin'] = 0
  3497. grb_obj.options['ymin'] = 0
  3498. grb_obj.options['xmax'] = 0
  3499. grb_obj.options['ymax'] = 0
  3500. except KeyError:
  3501. pass
  3502. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3503. def new_script_object(self, name=None, text=None):
  3504. """
  3505. Creates a new, blank TCL Script object.
  3506. :param name: a name for the new object
  3507. :param text: pass a source file to the newly created script to be loaded in it
  3508. :return: None
  3509. """
  3510. self.report_usage("new_script_object()")
  3511. if text is not None:
  3512. new_source_file = text
  3513. else:
  3514. commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  3515. "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n"\
  3516. "# Cncjob, Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, " \
  3517. "Follow, GeoCutout, GeoUnion, GetNames,\n"\
  3518. "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  3519. "ListSys, MillDrills,\n"\
  3520. "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  3521. "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"\
  3522. "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  3523. "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  3524. "# SubtractRectangle, Version, WriteGCode\n"
  3525. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  3526. '# %s:\n' % _('TCL Tutorial is here') + \
  3527. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  3528. '# %s:\n' % _("FlatCAM commands list")
  3529. new_source_file += commands_list + '\n'
  3530. def initialize(obj, app):
  3531. obj.source_file = deepcopy(new_source_file)
  3532. if name is None:
  3533. outname = 'new_script'
  3534. else:
  3535. outname = name
  3536. self.new_object('script', outname, initialize, plot=False)
  3537. def new_document_object(self):
  3538. """
  3539. Creates a new, blank Document object.
  3540. :return: None
  3541. """
  3542. self.report_usage("new_document_object()")
  3543. def initialize(obj, app):
  3544. obj.source_file = ""
  3545. self.new_object('document', 'new_document', initialize, plot=False)
  3546. def on_object_created(self, obj, plot, auto_select):
  3547. """
  3548. Event callback for object creation.
  3549. It will add the new object to the collection. After that it will plot the object in a threaded way
  3550. :param obj: The newly created FlatCAM object.
  3551. :param plot: if the newly create object t obe plotted
  3552. :param auto_select: if the newly created object to be autoselected after creation
  3553. :return: None
  3554. """
  3555. t0 = time.time() # DEBUG
  3556. self.log.debug("on_object_created()")
  3557. # The Collection might change the name if there is a collision
  3558. self.collection.append(obj)
  3559. # after adding the object to the collection always update the list of objects that are in the collection
  3560. self.all_objects_list = self.collection.get_list()
  3561. # self.inform.emit('[selected] %s created & selected: %s' %
  3562. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3563. if obj.kind == 'gerber':
  3564. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3565. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3566. elif obj.kind == 'excellon':
  3567. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3568. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3569. elif obj.kind == 'cncjob':
  3570. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3571. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3572. elif obj.kind == 'geometry':
  3573. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3574. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3575. elif obj.kind == 'script':
  3576. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3577. kind=obj.kind.capitalize(), color='orange', name=str(obj.options['name'])))
  3578. elif obj.kind == 'document':
  3579. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3580. kind=obj.kind.capitalize(), color='darkCyan', name=str(obj.options['name'])))
  3581. # update the SHELL auto-completer model with the name of the new object
  3582. self.shell._edit.set_model_data(self.myKeywords)
  3583. if auto_select:
  3584. # select the just opened object but deselect the previous ones
  3585. self.collection.set_all_inactive()
  3586. self.collection.set_active(obj.options["name"])
  3587. else:
  3588. self.collection.set_all_inactive()
  3589. # here it is done the object plotting
  3590. def worker_task(t_obj):
  3591. with self.proc_container.new(_("Plotting")):
  3592. if isinstance(t_obj, FlatCAMCNCjob):
  3593. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3594. else:
  3595. t_obj.plot()
  3596. t1 = time.time() # DEBUG
  3597. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3598. self.object_plotted.emit(t_obj)
  3599. # Send to worker
  3600. # self.worker.add_task(worker_task, [self])
  3601. if plot is True:
  3602. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3603. def on_object_changed(self, obj):
  3604. """
  3605. Called whenever the geometry of the object was changed in some way.
  3606. This require the update of it's bounding values so it can be the selected on canvas.
  3607. Update the bounding box data from obj.options
  3608. :param obj: the object that was changed
  3609. :return: None
  3610. """
  3611. xmin, ymin, xmax, ymax = obj.bounds()
  3612. obj.options['xmin'] = xmin
  3613. obj.options['ymin'] = ymin
  3614. obj.options['xmax'] = xmax
  3615. obj.options['ymax'] = ymax
  3616. log.debug("Object changed, updating the bounding box data on self.options")
  3617. # delete the old selection shape
  3618. self.delete_selection_shape()
  3619. self.should_we_save = True
  3620. def on_object_plotted(self):
  3621. """
  3622. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3623. :return: None
  3624. """
  3625. self.on_zoom_fit(None)
  3626. def on_about(self):
  3627. """
  3628. Displays the "about" dialog found in the Menu --> Help.
  3629. :return: None
  3630. """
  3631. self.report_usage("on_about")
  3632. version = self.version
  3633. version_date = self.version_date
  3634. beta = self.beta
  3635. class AboutDialog(QtWidgets.QDialog):
  3636. def __init__(self, parent=None):
  3637. QtWidgets.QDialog.__init__(self, parent)
  3638. # Icon and title
  3639. self.setWindowIcon(parent.app_icon)
  3640. self.setWindowTitle(_("About FlatCAM"))
  3641. self.resize(600, 200)
  3642. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3643. # self.setStyleSheet(
  3644. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3645. # "background-attachment: fixed"
  3646. # )
  3647. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3648. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3649. # palette = QtGui.QPalette()
  3650. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3651. # self.setPalette(palette)
  3652. logo = QtWidgets.QLabel()
  3653. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3654. title = QtWidgets.QLabel(
  3655. "<font size=8><B>FlatCAM</B></font><BR>"
  3656. "{title}<BR>"
  3657. "<BR>"
  3658. "<BR>"
  3659. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3660. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3661. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3662. "<B>{issue}</B></a><BR>".format(
  3663. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3664. devel=_("Development"),
  3665. down=_("DOWNLOAD"),
  3666. issue=_("Issue tracker"))
  3667. )
  3668. title.setOpenExternalLinks(True)
  3669. closebtn = QtWidgets.QPushButton(_("Close"))
  3670. tab_widget = QtWidgets.QTabWidget()
  3671. description_label = QtWidgets.QLabel(
  3672. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3673. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3674. version=version,
  3675. beta=('BETA' if beta else ''),
  3676. date=version_date,
  3677. arch=platform.architecture()[0])
  3678. )
  3679. description_label.setOpenExternalLinks(True)
  3680. lic_lbl_header = QtWidgets.QLabel(
  3681. '%s:<br>%s<br>' % (
  3682. _('Licensed under the MIT license'),
  3683. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  3684. "http://www.opensource.org/licenses/mit-license.php</a>"
  3685. )
  3686. )
  3687. lic_lbl_header.setOpenExternalLinks(True)
  3688. lic_lbl_body = QtWidgets.QLabel(
  3689. _(
  3690. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3691. 'of this software and associated documentation files (the "Software"), to deal\n'
  3692. 'in the Software without restriction, including without limitation the rights\n'
  3693. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3694. 'copies of the Software, and to permit persons to whom the Software is\n'
  3695. 'furnished to do so, subject to the following conditions:\n\n'
  3696. 'The above copyright notice and this permission notice shall be included in\n'
  3697. 'all copies or substantial portions of the Software.\n\n'
  3698. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3699. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3700. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3701. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3702. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3703. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3704. 'THE SOFTWARE.'
  3705. )
  3706. )
  3707. attributions_label = QtWidgets.QLabel(
  3708. _(
  3709. 'Some of the icons used are from the following sources:<br>'
  3710. '<div>Icons made by <a href="https://www.flaticon.com/authors/freepik" '
  3711. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  3712. 'title="Flaticon">www.flaticon.com</a></div>'
  3713. 'Icons by <a target="_blank" href="https://icons8.com">Icons8</a>'
  3714. )
  3715. )
  3716. # layouts
  3717. layout1 = QtWidgets.QVBoxLayout()
  3718. layout1_1 = QtWidgets.QHBoxLayout()
  3719. layout1_2 = QtWidgets.QHBoxLayout()
  3720. layout2 = QtWidgets.QHBoxLayout()
  3721. layout3 = QtWidgets.QHBoxLayout()
  3722. self.setLayout(layout1)
  3723. layout1.addLayout(layout1_1)
  3724. layout1.addLayout(layout1_2)
  3725. layout1.addLayout(layout2)
  3726. layout1.addLayout(layout3)
  3727. layout1_1.addStretch()
  3728. layout1_1.addWidget(description_label)
  3729. layout1_2.addWidget(tab_widget)
  3730. self.splash_tab = QtWidgets.QWidget()
  3731. self.splash_tab.setObjectName("splash_about")
  3732. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3733. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3734. tab_widget.addTab(self.splash_tab, _("Splash"))
  3735. self.programmmers_tab = QtWidgets.QWidget()
  3736. self.programmmers_tab.setObjectName("programmers_about")
  3737. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3738. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3739. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3740. self.translators_tab = QtWidgets.QWidget()
  3741. self.translators_tab.setObjectName("translators_about")
  3742. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3743. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3744. tab_widget.addTab(self.translators_tab, _("Translators"))
  3745. self.license_tab = QtWidgets.QWidget()
  3746. self.license_tab.setObjectName("license_about")
  3747. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3748. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3749. tab_widget.addTab(self.license_tab, _("License"))
  3750. self.attributions_tab = QtWidgets.QWidget()
  3751. self.attributions_tab.setObjectName("attributions_about")
  3752. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  3753. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  3754. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  3755. self.splash_tab_layout.addWidget(logo, stretch=0)
  3756. self.splash_tab_layout.addWidget(title, stretch=1)
  3757. pal = QtGui.QPalette()
  3758. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3759. self.prog_grid_lay = QtWidgets.QGridLayout()
  3760. self.prog_grid_lay.setHorizontalSpacing(20)
  3761. self.prog_grid_lay.setColumnStretch(0, 0)
  3762. self.prog_grid_lay.setColumnStretch(2, 1)
  3763. prog_widget = QtWidgets.QWidget()
  3764. prog_widget.setLayout(self.prog_grid_lay)
  3765. prog_scroll = QtWidgets.QScrollArea()
  3766. prog_scroll.setWidget(prog_widget)
  3767. prog_scroll.setWidgetResizable(True)
  3768. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3769. prog_scroll.setPalette(pal)
  3770. self.programmmers_tab_layout.addWidget(prog_scroll)
  3771. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  3772. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  3773. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3774. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  3775. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Program Author"), 1, 1)
  3776. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  3777. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  3778. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  3779. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  3780. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  3781. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  3782. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  3783. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 6, 0)
  3784. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  3785. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  3786. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  3787. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  3788. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 11, 0)
  3789. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  3790. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  3791. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 14, 0)
  3792. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 12, 0)
  3793. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 15, 0)
  3794. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 16, 0)
  3795. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 17, 0)
  3796. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 18, 0)
  3797. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 19, 0)
  3798. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 20, 0)
  3799. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 21, 0)
  3800. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 22, 0)
  3801. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 23, 0)
  3802. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 24, 0)
  3803. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 25, 0)
  3804. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 26, 0)
  3805. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 27, 0)
  3806. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 28, 0)
  3807. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 29, 0)
  3808. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 30, 0)
  3809. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 31, 0)
  3810. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 32, 0)
  3811. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 33, 0)
  3812. self.translator_grid_lay = QtWidgets.QGridLayout()
  3813. self.translator_grid_lay.setColumnStretch(0, 0)
  3814. self.translator_grid_lay.setColumnStretch(1, 0)
  3815. self.translator_grid_lay.setColumnStretch(2, 1)
  3816. self.translator_grid_lay.setColumnStretch(3, 0)
  3817. # trans_widget = QtWidgets.QWidget()
  3818. # trans_widget.setLayout(self.translator_grid_lay)
  3819. # self.translators_tab_layout.addWidget(trans_widget)
  3820. # self.translators_tab_layout.addStretch()
  3821. trans_widget = QtWidgets.QWidget()
  3822. trans_widget.setLayout(self.translator_grid_lay)
  3823. trans_scroll = QtWidgets.QScrollArea()
  3824. trans_scroll.setWidget(trans_widget)
  3825. trans_scroll.setWidgetResizable(True)
  3826. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3827. trans_scroll.setPalette(pal)
  3828. self.translators_tab_layout.addWidget(trans_scroll)
  3829. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  3830. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  3831. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  3832. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  3833. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  3834. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  3835. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  3836. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  3837. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 2, 1)
  3838. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "(Google-Translation)"), 2, 2)
  3839. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  3840. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  3841. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 3, 1)
  3842. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt"), 3, 2)
  3843. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  3844. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  3845. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  3846. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 3)
  3847. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  3848. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  3849. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 3)
  3850. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  3851. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  3852. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "(Google-Translation)"), 6, 2)
  3853. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 3)
  3854. self.translator_grid_lay.setColumnStretch(0, 0)
  3855. self.translators_tab_layout.addStretch()
  3856. self.license_tab_layout.addWidget(lic_lbl_header)
  3857. self.license_tab_layout.addWidget(lic_lbl_body)
  3858. self.license_tab_layout.addStretch()
  3859. self.attributions_tab_layout.addWidget(attributions_label)
  3860. self.attributions_tab_layout.addStretch()
  3861. layout3.addStretch()
  3862. layout3.addWidget(closebtn)
  3863. closebtn.clicked.connect(self.accept)
  3864. AboutDialog(self.ui).exec_()
  3865. def install_bookmarks(self, book_dict=None):
  3866. """
  3867. Install the bookmarks actions in the Help menu -> Bookmarks
  3868. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  3869. :return: None
  3870. """
  3871. if book_dict is None:
  3872. self.defaults["global_bookmarks"].update(
  3873. {
  3874. '1': ['FlatCAM', "http://flatcam.org"],
  3875. '2': ['Backup Site', ""]
  3876. }
  3877. )
  3878. else:
  3879. self.defaults["global_bookmarks"].clear()
  3880. self.defaults["global_bookmarks"].update(book_dict)
  3881. # first try to disconnect if somehow they get connected from elsewhere
  3882. for act in self.ui.menuhelp_bookmarks.actions():
  3883. try:
  3884. act.triggered.disconnect()
  3885. except TypeError:
  3886. pass
  3887. # clear all actions except the last one who is the Bookmark manager
  3888. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  3889. pass
  3890. else:
  3891. self.ui.menuhelp_bookmarks.removeAction(act)
  3892. bm_limit = int(self.defaults["global_bookmarks_limit"])
  3893. if self.defaults["global_bookmarks"]:
  3894. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  3895. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  3896. # the JSON is first making the keys as strings (therefore I have to use strings too
  3897. # or do the conversion :(
  3898. # )
  3899. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  3900. # the '10' entry jsut after '1' therefore ordering as strings
  3901. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  3902. key=lambda x: int(x[0]))
  3903. for entry, bookmark in sorted_bookmarks:
  3904. title = bookmark[0]
  3905. weblink = bookmark[1]
  3906. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  3907. act.setText(title)
  3908. act.setIcon(QtGui.QIcon('share/link16.png'))
  3909. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  3910. if title == 'Backup Site' and weblink == "":
  3911. act.triggered.connect(self.on_backup_site)
  3912. else:
  3913. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  3914. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  3915. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  3916. def on_bookmarks_manager(self):
  3917. """
  3918. Adds the bookmark manager in a Tab in Plot Area
  3919. :return:
  3920. """
  3921. for idx in range(self.ui.plot_tab_area.count()):
  3922. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  3923. # there can be only one instance of Bookmark Manager at one time
  3924. return
  3925. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  3926. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  3927. # add the tab if it was closed
  3928. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  3929. # delete the absolute and relative position and messages in the infobar
  3930. self.ui.position_label.setText("")
  3931. self.ui.rel_position_label.setText("")
  3932. # Switch plot_area to preferences page
  3933. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  3934. @staticmethod
  3935. def on_backup_site():
  3936. msgbox = QtWidgets.QMessageBox()
  3937. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  3938. "1. FlatCAM.org website is down\n"
  3939. "2. Someone forked FlatCAM project and wants to point\n"
  3940. "to his own website\n\n"
  3941. "If you can't get any informations about FlatCAM beta\n"
  3942. "use the YouTube channel link from the Help menu."))
  3943. msgbox.setWindowTitle(_("Alternative website"))
  3944. msgbox.setWindowIcon(QtGui.QIcon('share/globe16.png'))
  3945. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  3946. msgbox.setDefaultButton(bt_yes)
  3947. msgbox.exec_()
  3948. # response = msgbox.clickedButton()
  3949. def on_file_savedefaults(self):
  3950. """
  3951. Callback for menu item File->Save Defaults. Saves application default options
  3952. ``self.defaults`` to current_defaults.FlatConfig.
  3953. :return: None
  3954. """
  3955. self.save_defaults()
  3956. # def on_app_exit(self):
  3957. # self.report_usage("on_app_exit()")
  3958. #
  3959. # if self.collection.get_list():
  3960. # msgbox = QtWidgets.QMessageBox()
  3961. # # msgbox.setText("<B>Save changes ...</B>")
  3962. # msgbox.setText("There are files/objects opened in FlatCAM. "
  3963. # "\n"
  3964. # "Do you want to Save the project?")
  3965. # msgbox.setWindowTitle("Save changes")
  3966. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3967. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  3968. # QtWidgets.QMessageBox.Cancel)
  3969. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  3970. #
  3971. # response = msgbox.exec_()
  3972. #
  3973. # if response == QtWidgets.QMessageBox.Yes:
  3974. # self.on_file_saveprojectas(thread=False)
  3975. # elif response == QtWidgets.QMessageBox.Cancel:
  3976. # return
  3977. # self.save_defaults()
  3978. # else:
  3979. # self.save_defaults()
  3980. # log.debug("Application defaults saved ... Exit event.")
  3981. # QtWidgets.qApp.quit()
  3982. def save_defaults(self, silent=False, data_path=None, first_time=False):
  3983. """
  3984. Saves application default options
  3985. ``self.defaults`` to current_defaults.FlatConfig file.
  3986. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  3987. used at the next launch of the application.
  3988. :param silent: whether to display a message in status bar or not; boolean
  3989. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  3990. When the application is portable it should be a mobile location.
  3991. :return: None
  3992. """
  3993. self.report_usage("save_defaults")
  3994. if data_path is None:
  3995. data_path = self.data_path
  3996. # Read options from file
  3997. try:
  3998. f = open(data_path + "/current_defaults.FlatConfig")
  3999. defaults_file_content = f.read()
  4000. f.close()
  4001. except Exception:
  4002. e = sys.exc_info()[0]
  4003. App.log.error("Could not load defaults file.")
  4004. App.log.error(str(e))
  4005. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load defaults file."))
  4006. return
  4007. try:
  4008. defaults = json.loads(defaults_file_content)
  4009. except Exception:
  4010. e = sys.exc_info()[0]
  4011. App.log.error("Failed to parse defaults file.")
  4012. App.log.error(str(e))
  4013. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse defaults file."))
  4014. return
  4015. # Update options
  4016. self.defaults_read_form()
  4017. defaults.update(self.defaults)
  4018. self.propagate_defaults(silent=True)
  4019. # Save the toolbar view
  4020. tb_status = 0
  4021. if self.ui.toolbarfile.isVisible():
  4022. tb_status += 1
  4023. if self.ui.toolbargeo.isVisible():
  4024. tb_status += 2
  4025. if self.ui.toolbarview.isVisible():
  4026. tb_status += 4
  4027. if self.ui.toolbartools.isVisible():
  4028. tb_status += 8
  4029. if self.ui.exc_edit_toolbar.isVisible():
  4030. tb_status += 16
  4031. if self.ui.geo_edit_toolbar.isVisible():
  4032. tb_status += 32
  4033. if self.ui.grb_edit_toolbar.isVisible():
  4034. tb_status += 64
  4035. if self.ui.snap_toolbar.isVisible():
  4036. tb_status += 128
  4037. if self.ui.toolbarshell.isVisible():
  4038. tb_status += 256
  4039. if first_time is False:
  4040. self.defaults["global_toolbar_view"] = tb_status
  4041. # Save update options
  4042. try:
  4043. f = open(data_path + "/current_defaults.FlatConfig", "w")
  4044. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  4045. f.close()
  4046. except Exception as e:
  4047. log.debug("App.save_defaults() --> %s" % str(e))
  4048. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to write defaults to file."))
  4049. return
  4050. if not silent:
  4051. self.inform.emit('[success] %s' % _("Preferences saved."))
  4052. def save_factory_defaults(self, silent_message=False, data_path=None):
  4053. """
  4054. Saves application factory default options
  4055. ``self.defaults`` to factory_defaults.FlatConfig.
  4056. It's a one time job done just after the first install.
  4057. :param silent_message: whether to display a message in status bar or not; boolean
  4058. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  4059. When the application is portable it should be a mobile location.
  4060. :return: None
  4061. """
  4062. self.report_usage("save_factory_defaults")
  4063. if data_path is None:
  4064. data_path = self.data_path
  4065. # Read options from file
  4066. try:
  4067. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  4068. factory_defaults_file_content = f_f_def.read()
  4069. f_f_def.close()
  4070. except Exception:
  4071. e = sys.exc_info()[0]
  4072. App.log.error("Could not load factory defaults file.")
  4073. App.log.error(str(e))
  4074. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load factory defaults file."))
  4075. return
  4076. try:
  4077. factory_defaults = json.loads(factory_defaults_file_content)
  4078. except Exception:
  4079. e = sys.exc_info()[0]
  4080. App.log.error("Failed to parse factory defaults file.")
  4081. App.log.error(str(e))
  4082. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse factory defaults file."))
  4083. return
  4084. # Update options
  4085. self.defaults_read_form()
  4086. factory_defaults.update(self.defaults)
  4087. self.propagate_defaults(silent=True)
  4088. # Save update options
  4089. try:
  4090. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  4091. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  4092. f_f_def_s.close()
  4093. except Exception as e:
  4094. log.debug("App.save_factory_default() save update --> %s" % str(e))
  4095. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to write factory defaults to file."))
  4096. return
  4097. if silent_message is False:
  4098. self.inform.emit(_("Factory defaults saved."))
  4099. def final_save(self):
  4100. """
  4101. Callback for doing a preferences save to file whenever the application is about to quit.
  4102. If the project has changes, it will ask the user to save the project.
  4103. :return: None
  4104. """
  4105. if self.save_in_progress:
  4106. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  4107. return
  4108. if self.should_we_save and self.collection.get_list():
  4109. msgbox = QtWidgets.QMessageBox()
  4110. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  4111. "\n"
  4112. "Do you want to Save the project?"))
  4113. msgbox.setWindowTitle(_("Save changes"))
  4114. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4115. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4116. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4117. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4118. msgbox.setDefaultButton(bt_yes)
  4119. msgbox.exec_()
  4120. response = msgbox.clickedButton()
  4121. if response == bt_yes:
  4122. try:
  4123. self.trayIcon.hide()
  4124. except Exception:
  4125. pass
  4126. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  4127. elif response == bt_no:
  4128. try:
  4129. self.trayIcon.hide()
  4130. except Exception:
  4131. pass
  4132. self.quit_application()
  4133. elif response == bt_cancel:
  4134. return
  4135. else:
  4136. try:
  4137. self.trayIcon.hide()
  4138. except Exception:
  4139. pass
  4140. self.quit_application()
  4141. def quit_application(self):
  4142. """
  4143. Called (as a pyslot or not) when the application is quit.
  4144. :return: None
  4145. """
  4146. self.save_defaults()
  4147. log.debug("App.final_save() --> App Defaults saved.")
  4148. if self.cmd_line_headless != 1:
  4149. # save app state to file
  4150. stgs = QSettings("Open Source", "FlatCAM")
  4151. stgs.setValue('saved_gui_state', self.ui.saveState())
  4152. stgs.setValue('maximized_gui', self.ui.isMaximized())
  4153. stgs.setValue(
  4154. 'language',
  4155. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  4156. )
  4157. stgs.setValue(
  4158. 'notebook_font_size',
  4159. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  4160. )
  4161. stgs.setValue(
  4162. 'axis_font_size',
  4163. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  4164. )
  4165. stgs.setValue(
  4166. 'textbox_font_size',
  4167. self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  4168. )
  4169. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  4170. stgs.setValue(
  4171. 'machinist',
  4172. 1 if self.ui.general_defaults_form.general_app_group.machinist_cb.get_value() else 0
  4173. )
  4174. # This will write the setting to the platform specific storage.
  4175. del stgs
  4176. log.debug("App.final_save() --> App UI state saved.")
  4177. QtWidgets.qApp.quit()
  4178. def on_portable_checked(self, state):
  4179. """
  4180. Callback called when the checkbox in Preferences GUI is checked.
  4181. It will set the application as portable by creating the preferences and recent files in the
  4182. 'config' folder found in the FlatCAM installation folder.
  4183. :param state: boolean, the state of the checkbox when clicked/checked
  4184. :return:
  4185. """
  4186. line_no = 0
  4187. data = None
  4188. if sys.platform != 'win32':
  4189. # this won't work in Linux or MacOS
  4190. return
  4191. # test if the app was frozen and choose the path for the configuration file
  4192. if getattr(sys, "frozen", False) is True:
  4193. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  4194. else:
  4195. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  4196. config_file = current_data_path + '\\configuration.txt'
  4197. try:
  4198. with open(config_file, 'r') as f:
  4199. try:
  4200. data = f.readlines()
  4201. except Exception as e:
  4202. log.debug('App.__init__() -->%s' % str(e))
  4203. return
  4204. except FileNotFoundError:
  4205. pass
  4206. for line in data:
  4207. line = line.strip('\n')
  4208. param = str(line).rpartition('=')
  4209. if param[0] == 'portable':
  4210. break
  4211. line_no += 1
  4212. if state:
  4213. data[line_no] = 'portable=True\n'
  4214. # create the new defauults files
  4215. # create current_defaults.FlatConfig file if there is none
  4216. try:
  4217. f = open(current_data_path + '/current_defaults.FlatConfig')
  4218. f.close()
  4219. except IOError:
  4220. App.log.debug('Creating empty current_defaults.FlatConfig')
  4221. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  4222. json.dump({}, f)
  4223. f.close()
  4224. # create factory_defaults.FlatConfig file if there is none
  4225. try:
  4226. f = open(current_data_path + '/factory_defaults.FlatConfig')
  4227. f.close()
  4228. except IOError:
  4229. App.log.debug('Creating empty factory_defaults.FlatConfig')
  4230. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  4231. json.dump({}, f)
  4232. f.close()
  4233. try:
  4234. f = open(current_data_path + '/recent.json')
  4235. f.close()
  4236. except IOError:
  4237. App.log.debug('Creating empty recent.json')
  4238. f = open(current_data_path + '/recent.json', 'w')
  4239. json.dump([], f)
  4240. f.close()
  4241. try:
  4242. fp = open(current_data_path + '/recent_projects.json')
  4243. fp.close()
  4244. except IOError:
  4245. App.log.debug('Creating empty recent_projects.json')
  4246. fp = open(current_data_path + '/recent_projects.json', 'w')
  4247. json.dump([], fp)
  4248. fp.close()
  4249. # save the current defaults to the new defaults file
  4250. self.save_defaults(silent=True, data_path=current_data_path)
  4251. self.save_factory_defaults(silent_message=True, data_path=current_data_path)
  4252. else:
  4253. data[line_no] = 'portable=False\n'
  4254. with open(config_file, 'w') as f:
  4255. f.writelines(data)
  4256. def on_toggle_shell(self):
  4257. """
  4258. Toggle shell: if is visible close it, if it is closed then open it
  4259. :return: None
  4260. """
  4261. self.report_usage("on_toggle_shell()")
  4262. if self.ui.shell_dock.isVisible():
  4263. self.ui.shell_dock.hide()
  4264. else:
  4265. self.ui.shell_dock.show()
  4266. def on_register_files(self, obj_type=None):
  4267. """
  4268. Called whenever there is a need to register file extensions with FlatCAM.
  4269. Works only in Windows and should be called only when FlatCAM is run in Windows.
  4270. :param obj_type: the type of object to be register for.
  4271. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  4272. :return: None
  4273. """
  4274. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  4275. new_reg_path = 'Software\\Classes\\'
  4276. # find if the current user is admin
  4277. try:
  4278. is_admin = os.getuid() == 0
  4279. except AttributeError:
  4280. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  4281. if is_admin is True:
  4282. root_path = winreg.HKEY_LOCAL_MACHINE
  4283. else:
  4284. root_path = winreg.HKEY_CURRENT_USER
  4285. # create the keys
  4286. def set_reg(name, root_path, new_reg_path, value):
  4287. try:
  4288. winreg.CreateKey(root_path, new_reg_path)
  4289. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  4290. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  4291. return True
  4292. except WindowsError:
  4293. return False
  4294. # delete key in registry
  4295. def delete_reg(root_path, reg_path, key_to_del):
  4296. key_to_del_path = reg_path + key_to_del
  4297. try:
  4298. winreg.DeleteKey(root_path, key_to_del_path)
  4299. return True
  4300. except WindowsError:
  4301. return False
  4302. if obj_type is None or obj_type == 'excellon':
  4303. exc_list = \
  4304. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4305. exc_list = [x for x in exc_list if x != '']
  4306. # register all keys in the Preferences window
  4307. for ext in exc_list:
  4308. new_k = new_reg_path + '.%s' % ext
  4309. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4310. # and unregister those that are no longer in the Preferences windows but are in the file
  4311. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  4312. if ext not in exc_list:
  4313. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4314. # now write the updated extensions to the self.defaults
  4315. # new_ext = ''
  4316. # for ext in exc_list:
  4317. # new_ext = new_ext + ext + ', '
  4318. # self.defaults["fa_excellon"] = new_ext
  4319. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  4320. if obj_type is None or obj_type == 'gcode':
  4321. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4322. gco_list = [x for x in gco_list if x != '']
  4323. # register all keys in the Preferences window
  4324. for ext in gco_list:
  4325. new_k = new_reg_path + '.%s' % ext
  4326. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4327. # and unregister those that are no longer in the Preferences windows but are in the file
  4328. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  4329. if ext not in gco_list:
  4330. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4331. # now write the updated extensions to the self.defaults
  4332. # new_ext = ''
  4333. # for ext in gco_list:
  4334. # new_ext = new_ext + ext + ', '
  4335. # self.defaults["fa_gcode"] = new_ext
  4336. self.inform.emit('[success] %s' %
  4337. _("Selected GCode file extensions registered with FlatCAM."))
  4338. if obj_type is None or obj_type == 'gerber':
  4339. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4340. grb_list = [x for x in grb_list if x != '']
  4341. # register all keys in the Preferences window
  4342. for ext in grb_list:
  4343. new_k = new_reg_path + '.%s' % ext
  4344. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4345. # and unregister those that are no longer in the Preferences windows but are in the file
  4346. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  4347. if ext not in grb_list:
  4348. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4349. # now write the updated extensions to the self.defaults
  4350. # new_ext = ''
  4351. # for ext in grb_list:
  4352. # new_ext = new_ext + ext + ', '
  4353. # self.defaults["fa_gerber"] = new_ext
  4354. self.inform.emit('[success] %s' %
  4355. _("Selected Gerber file extensions registered with FlatCAM."))
  4356. def add_extension(self, ext_type):
  4357. """
  4358. Add a file extension to the list for a specific object
  4359. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4360. :return:
  4361. """
  4362. if ext_type == 'excellon':
  4363. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4364. if new_ext == '':
  4365. return
  4366. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4367. if new_ext in old_val:
  4368. return
  4369. old_val.append(new_ext)
  4370. old_val.sort()
  4371. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4372. if ext_type == 'gcode':
  4373. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4374. if new_ext == '':
  4375. return
  4376. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4377. if new_ext in old_val:
  4378. return
  4379. old_val.append(new_ext)
  4380. old_val.sort()
  4381. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4382. if ext_type == 'gerber':
  4383. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4384. if new_ext == '':
  4385. return
  4386. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4387. if new_ext in old_val:
  4388. return
  4389. old_val.append(new_ext)
  4390. old_val.sort()
  4391. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4392. if ext_type == 'keyword':
  4393. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4394. if new_kw == '':
  4395. return
  4396. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4397. if new_kw in old_val:
  4398. return
  4399. old_val.append(new_kw)
  4400. old_val.sort()
  4401. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4402. # update the self.myKeywords so the model is updated
  4403. self.autocomplete_kw_list = \
  4404. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4405. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4406. self.shell._edit.set_model_data(self.myKeywords)
  4407. def del_extension(self, ext_type):
  4408. """
  4409. Remove a file extension from the list for a specific object
  4410. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4411. :return:
  4412. """
  4413. if ext_type == 'excellon':
  4414. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4415. if new_ext == '':
  4416. return
  4417. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4418. if new_ext not in old_val:
  4419. return
  4420. old_val.remove(new_ext)
  4421. old_val.sort()
  4422. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4423. if ext_type == 'gcode':
  4424. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4425. if new_ext == '':
  4426. return
  4427. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4428. if new_ext not in old_val:
  4429. return
  4430. old_val.remove(new_ext)
  4431. old_val.sort()
  4432. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4433. if ext_type == 'gerber':
  4434. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4435. if new_ext == '':
  4436. return
  4437. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4438. if new_ext not in old_val:
  4439. return
  4440. old_val.remove(new_ext)
  4441. old_val.sort()
  4442. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4443. if ext_type == 'keyword':
  4444. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4445. if new_kw == '':
  4446. return
  4447. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4448. if new_kw not in old_val:
  4449. return
  4450. old_val.remove(new_kw)
  4451. old_val.sort()
  4452. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4453. # update the self.myKeywords so the model is updated
  4454. self.autocomplete_kw_list = \
  4455. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4456. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4457. self.shell._edit.set_model_data(self.myKeywords)
  4458. def restore_extensions(self, ext_type):
  4459. """
  4460. Restore all file extensions associations with FlatCAM, for a specific object
  4461. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4462. :return:
  4463. """
  4464. if ext_type == 'excellon':
  4465. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  4466. # for the ability to open Excellon files with .txt extension
  4467. new_exc_list = deepcopy(self.exc_list)
  4468. try:
  4469. new_exc_list.remove('txt')
  4470. except ValueError:
  4471. pass
  4472. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  4473. if ext_type == 'gcode':
  4474. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  4475. if ext_type == 'gerber':
  4476. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  4477. if ext_type == 'keyword':
  4478. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  4479. # update the self.myKeywords so the model is updated
  4480. self.autocomplete_kw_list = self.default_keywords
  4481. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4482. self.shell._edit.set_model_data(self.myKeywords)
  4483. def delete_all_extensions(self, ext_type):
  4484. """
  4485. Delete all file extensions associations with FlatCAM, for a specific object
  4486. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4487. :return:
  4488. """
  4489. if ext_type == 'excellon':
  4490. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4491. if ext_type == 'gcode':
  4492. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4493. if ext_type == 'gerber':
  4494. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4495. if ext_type == 'keyword':
  4496. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4497. # update the self.myKeywords so the model is updated
  4498. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4499. self.shell._edit.set_model_data(self.myKeywords)
  4500. def on_edit_join(self, name=None):
  4501. """
  4502. Callback for Edit->Join. Joins the selected geometry objects into
  4503. a new one.
  4504. :return: None
  4505. """
  4506. self.report_usage("on_edit_join()")
  4507. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4508. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4509. geo_type_set = set()
  4510. objs = self.collection.get_selected()
  4511. if len(objs) < 2:
  4512. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4513. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4514. return 'fail'
  4515. for obj in objs:
  4516. geo_type_set.add(obj.multigeo)
  4517. # if len(geo_type_list) == 1 means that all list elements are the same
  4518. if len(geo_type_set) != 1:
  4519. self.inform.emit('[ERROR] %s' %
  4520. _("Failed join. The Geometry objects are of different types.\n"
  4521. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4522. "convert from one to another and retry joining \n"
  4523. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4524. "the result may not be what was expected. \n"
  4525. "Check the generated GCODE."))
  4526. return
  4527. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4528. if True in geo_type_set:
  4529. def initialize(geo_obj, app):
  4530. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=True)
  4531. app.inform.emit('[success] %s.' % _("Multigeo. Geometry merging finished"))
  4532. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4533. for v in obj.tools.values():
  4534. v['data']['name'] = obj_name_multi
  4535. self.new_object("geometry", obj_name_multi, initialize)
  4536. else:
  4537. def initialize(geo_obj, app):
  4538. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=False)
  4539. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  4540. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4541. for v in obj.tools.values():
  4542. v['data']['name'] = obj_name_single
  4543. self.new_object("geometry", obj_name_single, initialize)
  4544. self.should_we_save = True
  4545. def on_edit_join_exc(self):
  4546. """
  4547. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4548. a new Excellon.
  4549. :return: None
  4550. """
  4551. self.report_usage("on_edit_join_exc()")
  4552. objs = self.collection.get_selected()
  4553. for obj in objs:
  4554. if not isinstance(obj, FlatCAMExcellon):
  4555. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  4556. return
  4557. if len(objs) < 2:
  4558. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4559. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4560. return 'fail'
  4561. def initialize(exc_obj, app):
  4562. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=exc_obj)
  4563. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  4564. self.new_object("excellon", 'Combo_Excellon', initialize)
  4565. self.should_we_save = True
  4566. def on_edit_join_grb(self):
  4567. """
  4568. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4569. a new Gerber object.
  4570. :return: None
  4571. """
  4572. self.report_usage("on_edit_join_grb()")
  4573. objs = self.collection.get_selected()
  4574. for obj in objs:
  4575. if not isinstance(obj, FlatCAMGerber):
  4576. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  4577. return
  4578. if len(objs) < 2:
  4579. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4580. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4581. return 'fail'
  4582. def initialize(grb_obj, app):
  4583. FlatCAMGerber.merge(self, grb_list=objs, grb_final=grb_obj)
  4584. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  4585. self.new_object("gerber", 'Combo_Gerber', initialize)
  4586. self.should_we_save = True
  4587. def on_convert_singlegeo_to_multigeo(self):
  4588. """
  4589. Called for converting a Geometry object from single-geo to multi-geo.
  4590. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4591. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4592. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4593. the solid-geometry of that tool.
  4594. :return: None
  4595. """
  4596. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4597. obj = self.collection.get_active()
  4598. if obj is None:
  4599. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  4600. return
  4601. if not isinstance(obj, FlatCAMGeometry):
  4602. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4603. return
  4604. obj.multigeo = True
  4605. for tooluid, dict_value in obj.tools.items():
  4606. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4607. if not isinstance(obj.solid_geometry, list):
  4608. obj.solid_geometry = [obj.solid_geometry]
  4609. obj.solid_geometry[:] = []
  4610. obj.plot()
  4611. self.should_we_save = True
  4612. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  4613. def on_convert_multigeo_to_singlegeo(self):
  4614. """
  4615. Called for converting a Geometry object from multi-geo to single-geo.
  4616. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4617. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4618. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4619. the solid-geometry of that tool.
  4620. :return: None
  4621. """
  4622. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4623. obj = self.collection.get_active()
  4624. if obj is None:
  4625. self.inform.emit('[ERROR_NOTCL] %s' %
  4626. _("Failed. Select a Geometry Object and try again."))
  4627. return
  4628. if not isinstance(obj, FlatCAMGeometry):
  4629. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4630. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4631. return
  4632. obj.multigeo = False
  4633. total_solid_geometry = []
  4634. for tooluid, dict_value in obj.tools.items():
  4635. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4636. # clear the original geometry
  4637. dict_value['solid_geometry'][:] = []
  4638. obj.solid_geometry = deepcopy(total_solid_geometry)
  4639. obj.plot()
  4640. self.should_we_save = True
  4641. self.inform.emit('[success] %s' %
  4642. _("A Geometry object was converted to SingleGeo type."))
  4643. def on_defaults_dict_change(self, field):
  4644. """
  4645. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4646. Edit -> Preferences tab window.
  4647. :param field: the key of the self.defaults dictionary that was changed.
  4648. :return: None
  4649. """
  4650. self.defaults_write_form_field(field)
  4651. if field == "units":
  4652. self.set_screen_units(self.defaults['units'])
  4653. def set_screen_units(self, units):
  4654. """
  4655. Set the FlatCAM units on the status bar.
  4656. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4657. :return: None
  4658. """
  4659. self.ui.units_label.setText("[" + units.lower() + "]")
  4660. def on_toggle_units(self, no_pref=False):
  4661. """
  4662. Callback for the Units radio-button change in the Preferences tab.
  4663. Changes the application's default units adn for the project too.
  4664. If changing the project's units, the change propagates to all of
  4665. the objects in the project.
  4666. :return: None
  4667. """
  4668. self.report_usage("on_toggle_units")
  4669. if self.toggle_units_ignore:
  4670. return
  4671. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4672. # If option is the same, then ignore
  4673. if new_units == self.defaults["units"].upper():
  4674. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4675. return
  4676. # Options to scale
  4677. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin', "gerber_isooverlap",
  4678. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  4679. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  4680. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4681. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  4682. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  4683. "excellon_editor_slot_lin_pitch",
  4684. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4685. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4686. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  4687. "geometry_feedrate_probe", "geometry_startz",
  4688. 'cncjob_tooldia',
  4689. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4690. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  4691. "tools_nccnewdia",
  4692. "tools_2sided_drilldia", "tools_film_boundary",
  4693. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4694. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4695. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4696. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4697. "tools_transform_offset_y",
  4698. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4699. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4700. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4701. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4702. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  4703. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  4704. "tools_cr_h2h_val", "tools_cr_dh_val", "tools_fiducials_dia", "tools_fiducials_margin",
  4705. "tools_fiducials_mode", "tools_fiducials_second_pos", "tools_fiducials_type",
  4706. "tools_fiducials_line_thickness",
  4707. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  4708. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  4709. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  4710. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  4711. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  4712. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance"]
  4713. def scale_defaults(sfactor):
  4714. for dim in dimensions:
  4715. if dim == 'excellon_toolchangexy':
  4716. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4717. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4718. coords_xy[0] *= sfactor
  4719. coords_xy[1] *= sfactor
  4720. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4721. elif dim == 'geometry_toolchangexy':
  4722. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4723. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4724. coords_xy[0] *= sfactor
  4725. coords_xy[1] *= sfactor
  4726. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4727. elif dim == 'geometry_cnctooldia':
  4728. tools_diameters = []
  4729. try:
  4730. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4731. tools_diameters = [eval(a) for a in tools_string if a != '']
  4732. except Exception as e:
  4733. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4734. self.defaults['geometry_cnctooldia'] = ''
  4735. for t in range(len(tools_diameters)):
  4736. tools_diameters[t] *= sfactor
  4737. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  4738. elif dim == 'tools_ncctools':
  4739. ncctools = []
  4740. try:
  4741. tools_string = self.defaults["tools_ncctools"].split(",")
  4742. ncctools = [eval(a) for a in tools_string if a != '']
  4743. except Exception as e:
  4744. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4745. self.defaults['tools_ncctools'] = ''
  4746. for t in range(len(ncctools)):
  4747. ncctools[t] *= sfactor
  4748. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  4749. elif dim == 'tools_solderpaste_tools':
  4750. sptools = []
  4751. try:
  4752. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4753. sptools = [eval(a) for a in tools_string if a != '']
  4754. except Exception as e:
  4755. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4756. self.defaults['tools_solderpaste_tools'] = ""
  4757. for t in range(len(sptools)):
  4758. sptools[t] *= sfactor
  4759. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  4760. elif dim == 'tools_solderpaste_xy_toolchange':
  4761. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4762. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4763. sp_coords[0] *= sfactor
  4764. sp_coords[1] *= sfactor
  4765. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  4766. elif dim == 'global_gridx' or dim == 'global_gridy':
  4767. if new_units == 'IN':
  4768. val = 0.1
  4769. try:
  4770. val = float(self.defaults[dim]) * sfactor
  4771. except Exception as e:
  4772. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4773. self.defaults[dim] = float('%.6f' % val)
  4774. else:
  4775. val = 0.1
  4776. try:
  4777. val = float(self.defaults[dim]) * sfactor
  4778. except Exception as e:
  4779. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4780. self.defaults[dim] = float('%.4f' % val)
  4781. else:
  4782. val = 0.1
  4783. if self.defaults[dim]:
  4784. try:
  4785. val = float(self.defaults[dim]) * sfactor
  4786. except Exception as e:
  4787. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4788. self.defaults[dim] = val
  4789. # The scaling factor depending on choice of units.
  4790. factor = 1/25.4
  4791. if new_units == 'MM':
  4792. factor = 25.4
  4793. # Changing project units. Warn user.
  4794. msgbox = QtWidgets.QMessageBox()
  4795. msgbox.setWindowTitle(_("Toggle Units"))
  4796. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  4797. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4798. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  4799. "properties of all objects to be scaled accordingly.\nContinue?"))
  4800. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4801. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4802. msgbox.setDefaultButton(bt_ok)
  4803. msgbox.exec_()
  4804. response = msgbox.clickedButton()
  4805. if response == bt_ok:
  4806. if no_pref is False:
  4807. self.defaults_read_form()
  4808. scale_defaults(factor)
  4809. self.defaults_write_form(fl_units=new_units)
  4810. self.defaults["units"] = new_units
  4811. # save the defaults to file, some may assume that the conversion is enough and it's not
  4812. self.on_save_button()
  4813. self.should_we_save = True
  4814. # change this only if the workspace is active
  4815. if self.defaults['global_workspace'] is True:
  4816. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  4817. # adjust the grid values on the main toolbar
  4818. dec = 6 if new_units == 'IN'else 4
  4819. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  4820. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  4821. if not self.ui.grid_gap_link_cb.isChecked():
  4822. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  4823. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  4824. for obj in self.collection.get_list():
  4825. obj.convert_units(new_units)
  4826. # make that the properties stored in the object are also updated
  4827. self.object_changed.emit(obj)
  4828. obj.build_ui()
  4829. current = self.collection.get_active()
  4830. if current is not None:
  4831. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4832. if not isinstance(current, FlatCAMGeometry):
  4833. current.to_form()
  4834. self.plot_all()
  4835. self.inform.emit('[success] %s: %s' %
  4836. (_("Converted units to"), new_units))
  4837. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4838. self.set_screen_units(new_units)
  4839. else:
  4840. # Undo toggling
  4841. self.toggle_units_ignore = True
  4842. if self.defaults['units'].upper() == 'MM':
  4843. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4844. else:
  4845. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4846. self.toggle_units_ignore = False
  4847. self.inform.emit('[WARNING_NOTCL]%s' %
  4848. _(" Units conversion cancelled."))
  4849. self.defaults_read_form()
  4850. def on_toggle_units_click(self):
  4851. try:
  4852. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4853. except (TypeError, AttributeError):
  4854. pass
  4855. if self.defaults["units"] == 'MM':
  4856. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4857. else:
  4858. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4859. self.on_toggle_units(no_pref=True)
  4860. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4861. lambda: self.on_toggle_units(no_pref=False))
  4862. def on_fullscreen(self, disable=False):
  4863. self.report_usage("on_fullscreen()")
  4864. if self.toggle_fscreen is False and disable is False:
  4865. # self.ui.showFullScreen()
  4866. self.ui.setWindowFlags(self.ui.windowFlags() | Qt.FramelessWindowHint)
  4867. a = self.ui.geometry()
  4868. self.x_pos = a.x()
  4869. self.y_pos = a.y()
  4870. self.width = a.width()
  4871. self.height = a.height()
  4872. # set new geometry to full desktop rect
  4873. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  4874. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  4875. # everything else will not work without this hack. This happen in Windows.
  4876. # https://bugreports.qt.io/browse/QTBUG-41309
  4877. desktop = QtWidgets.QApplication.desktop()
  4878. screen = desktop.screenNumber(QtGui.QCursor.pos())
  4879. rec = desktop.screenGeometry(screen)
  4880. x = rec.x() - 1
  4881. y = rec.y() - 1
  4882. h = rec.height() + 2
  4883. w = rec.width() + 2
  4884. self.ui.setGeometry(x, y, w, h)
  4885. self.ui.show()
  4886. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4887. tb.setVisible(False)
  4888. self.ui.splitter_left.setVisible(False)
  4889. self.toggle_fscreen = True
  4890. elif self.toggle_fscreen is True or disable is True:
  4891. self.ui.setWindowFlags(self.ui.windowFlags() & ~Qt.FramelessWindowHint)
  4892. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  4893. self.ui.showNormal()
  4894. self.restore_toolbar_view()
  4895. self.ui.splitter_left.setVisible(True)
  4896. self.toggle_fscreen = False
  4897. def on_toggle_plotarea(self):
  4898. self.report_usage("on_toggle_plotarea()")
  4899. try:
  4900. name = self.ui.plot_tab_area.widget(0).objectName()
  4901. except AttributeError:
  4902. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4903. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4904. self.ui.plot_tab_area.protectTab(0)
  4905. return
  4906. if name != 'plotarea':
  4907. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4908. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4909. self.ui.plot_tab_area.protectTab(0)
  4910. else:
  4911. self.ui.plot_tab_area.closeTab(0)
  4912. def on_toggle_notebook(self):
  4913. if self.ui.splitter.sizes()[0] == 0:
  4914. self.ui.splitter.setSizes([1, 1])
  4915. self.ui.menu_toggle_nb.setChecked(True)
  4916. else:
  4917. self.ui.splitter.setSizes([0, 1])
  4918. self.ui.menu_toggle_nb.setChecked(False)
  4919. def on_toggle_axis(self):
  4920. self.report_usage("on_toggle_axis()")
  4921. if self.toggle_axis is False:
  4922. if self.is_legacy is False:
  4923. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  4924. parent=self.plotcanvas.view.scene)
  4925. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  4926. parent=self.plotcanvas.view.scene)
  4927. else:
  4928. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  4929. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  4930. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  4931. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  4932. self.plotcanvas.canvas.draw()
  4933. self.toggle_axis = True
  4934. else:
  4935. if self.is_legacy is False:
  4936. self.plotcanvas.v_line.parent = None
  4937. self.plotcanvas.h_line.parent = None
  4938. else:
  4939. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  4940. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  4941. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  4942. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  4943. self.plotcanvas.canvas.draw()
  4944. self.toggle_axis = False
  4945. def on_toggle_grid(self):
  4946. self.report_usage("on_toggle_grid()")
  4947. self.ui.grid_snap_btn.trigger()
  4948. def on_toggle_grid_lines(self):
  4949. self.report_usage("on_toggle_grd_lines()")
  4950. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  4951. if tt_settings.contains("theme"):
  4952. theme = tt_settings.value('theme', type=str)
  4953. else:
  4954. theme = 'white'
  4955. if self.toggle_grid_lines is False:
  4956. if self.is_legacy is False:
  4957. if theme == 'white':
  4958. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  4959. else:
  4960. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  4961. else:
  4962. self.plotcanvas.axes.grid(True)
  4963. try:
  4964. self.plotcanvas.canvas.draw()
  4965. except IndexError:
  4966. pass
  4967. pass
  4968. self.toggle_grid_lines = True
  4969. else:
  4970. if self.is_legacy is False:
  4971. if theme == 'white':
  4972. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  4973. else:
  4974. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  4975. else:
  4976. self.plotcanvas.axes.grid(False)
  4977. try:
  4978. self.plotcanvas.canvas.draw()
  4979. except IndexError:
  4980. pass
  4981. self.toggle_grid_lines = False
  4982. def show_preferences_gui(self):
  4983. """
  4984. Called to initialize and show the Preferences GUI
  4985. :return: None
  4986. """
  4987. self.gen_form = self.ui.general_defaults_form
  4988. self.ger_form = self.ui.gerber_defaults_form
  4989. self.exc_form = self.ui.excellon_defaults_form
  4990. self.geo_form = self.ui.geometry_defaults_form
  4991. self.cnc_form = self.ui.cncjob_defaults_form
  4992. self.tools_form = self.ui.tools_defaults_form
  4993. self.tools2_form = self.ui.tools2_defaults_form
  4994. self.fa_form = self.ui.util_defaults_form
  4995. try:
  4996. self.ui.general_scroll_area.takeWidget()
  4997. except Exception:
  4998. self.log.debug("Nothing to remove")
  4999. self.ui.general_scroll_area.setWidget(self.gen_form)
  5000. self.gen_form.show()
  5001. try:
  5002. self.ui.gerber_scroll_area.takeWidget()
  5003. except Exception:
  5004. self.log.debug("Nothing to remove")
  5005. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  5006. self.ger_form.show()
  5007. try:
  5008. self.ui.excellon_scroll_area.takeWidget()
  5009. except Exception:
  5010. self.log.debug("Nothing to remove")
  5011. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  5012. self.exc_form.show()
  5013. try:
  5014. self.ui.geometry_scroll_area.takeWidget()
  5015. except Exception:
  5016. self.log.debug("Nothing to remove")
  5017. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  5018. self.geo_form.show()
  5019. try:
  5020. self.ui.cncjob_scroll_area.takeWidget()
  5021. except Exception:
  5022. self.log.debug("Nothing to remove")
  5023. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  5024. self.cnc_form.show()
  5025. try:
  5026. self.ui.tools_scroll_area.takeWidget()
  5027. except Exception:
  5028. self.log.debug("Nothing to remove")
  5029. self.ui.tools_scroll_area.setWidget(self.tools_form)
  5030. self.tools_form.show()
  5031. try:
  5032. self.ui.tools2_scroll_area.takeWidget()
  5033. except Exception:
  5034. self.log.debug("Nothing to remove")
  5035. self.ui.tools2_scroll_area.setWidget(self.tools2_form)
  5036. self.tools2_form.show()
  5037. try:
  5038. self.ui.fa_scroll_area.takeWidget()
  5039. except Exception:
  5040. self.log.debug("Nothing to remove")
  5041. self.ui.fa_scroll_area.setWidget(self.fa_form)
  5042. self.fa_form.show()
  5043. self.log.debug("Finished Preferences GUI form initialization.")
  5044. # self.options2form()
  5045. def init_color_pickers_in_preferences_gui(self):
  5046. # Init Plot Colors
  5047. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  5048. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5049. "background-color:%s;"
  5050. "border-color: dimgray" % str(self.defaults['global_plot_fill'])[:7])
  5051. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  5052. int(self.defaults['global_plot_fill'][7:9], 16))
  5053. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  5054. int(self.defaults['global_plot_fill'][7:9], 16))
  5055. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  5056. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5057. "background-color:%s;"
  5058. "border-color: dimgray" % str(self.defaults['global_plot_line'])[:7])
  5059. # Init Left-Right Selection colors
  5060. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  5061. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5062. "background-color:%s;"
  5063. "border-color: dimgray" % str(self.defaults['global_sel_fill'])[:7])
  5064. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  5065. int(self.defaults['global_sel_fill'][7:9], 16))
  5066. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  5067. int(self.defaults['global_sel_fill'][7:9], 16))
  5068. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  5069. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5070. "background-color:%s;"
  5071. "border-color: dimgray" % str(self.defaults['global_sel_line'])[:7])
  5072. # Init Right-Left Selection colors
  5073. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  5074. self.defaults['global_alt_sel_fill'])
  5075. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5076. "background-color:%s;"
  5077. "border-color: dimgray" % str(self.defaults['global_alt_sel_fill'])[:7])
  5078. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  5079. int(self.defaults['global_sel_fill'][7:9], 16))
  5080. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  5081. int(self.defaults['global_sel_fill'][7:9], 16))
  5082. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  5083. self.defaults['global_alt_sel_line'])
  5084. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5085. "background-color:%s;"
  5086. "border-color: dimgray" % str(self.defaults['global_alt_sel_line'])[:7])
  5087. # Init Draw color and Selection Draw Color
  5088. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  5089. self.defaults['global_draw_color'])
  5090. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5091. "background-color:%s;"
  5092. "border-color: dimgray" % str(self.defaults['global_draw_color'])[:7])
  5093. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  5094. self.defaults['global_sel_draw_color'])
  5095. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5096. "background-color:%s;"
  5097. "border-color: dimgray" % str(self.defaults['global_sel_draw_color'])[:7])
  5098. # Init Project Items color
  5099. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  5100. self.defaults['global_proj_item_color'])
  5101. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5102. "background-color:%s;"
  5103. "border-color: dimgray" % str(self.defaults['global_proj_item_color'])[:7])
  5104. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  5105. self.defaults['global_proj_item_dis_color'])
  5106. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5107. "background-color:%s;"
  5108. "border-color: dimgray" % str(self.defaults['global_proj_item_dis_color'])[:7])
  5109. # Init the Annotation CNC Job color
  5110. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  5111. self.defaults['cncjob_annotation_fontcolor'])
  5112. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5113. "background-color:%s;"
  5114. "border-color: dimgray" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  5115. # Init the Tool Film color
  5116. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  5117. self.defaults['tools_film_color'])
  5118. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5119. "background-color:%s;"
  5120. "border-color: dimgray" % str(self.defaults['tools_film_color'])[:7]
  5121. )
  5122. # Init the Tool QRCode colors
  5123. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(
  5124. self.defaults['tools_qrcode_fill_color'])
  5125. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5126. "background-color:%s;"
  5127. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])[:7])
  5128. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(
  5129. self.defaults['tools_qrcode_back_color'])
  5130. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5131. "background-color:%s;"
  5132. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])[:7])
  5133. def on_excellon_defaults_button(self):
  5134. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  5135. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  5136. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  5137. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  5138. self.defaults_form_fields["excellon_zeros"].set_value('L')
  5139. self.defaults_form_fields["excellon_units"].set_value('INCH')
  5140. log.debug("Excellon app defaults loaded ...")
  5141. def on_update_exc_export(self, state):
  5142. """
  5143. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  5144. if the update_excellon_cb checkbox is checked
  5145. :param state: state of the checkbox whose signals is tied to his slot
  5146. :return:
  5147. """
  5148. if state:
  5149. # first try to disconnect
  5150. try:
  5151. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.\
  5152. disconnect(self.on_excellon_format_changed)
  5153. except TypeError:
  5154. pass
  5155. try:
  5156. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.\
  5157. disconnect(self.on_excellon_format_changed)
  5158. except TypeError:
  5159. pass
  5160. try:
  5161. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.\
  5162. disconnect(self.on_excellon_format_changed)
  5163. except TypeError:
  5164. pass
  5165. try:
  5166. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.\
  5167. disconnect(self.on_excellon_format_changed)
  5168. except TypeError:
  5169. pass
  5170. try:
  5171. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  5172. disconnect(self.on_excellon_zeros_changed)
  5173. except TypeError:
  5174. pass
  5175. try:
  5176. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  5177. disconnect(self.on_excellon_zeros_changed)
  5178. except TypeError:
  5179. pass
  5180. # the connect them
  5181. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  5182. self.on_excellon_format_changed)
  5183. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  5184. self.on_excellon_format_changed)
  5185. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  5186. self.on_excellon_format_changed)
  5187. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  5188. self.on_excellon_format_changed)
  5189. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  5190. self.on_excellon_zeros_changed)
  5191. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  5192. self.on_excellon_units_changed)
  5193. else:
  5194. # disconnect the signals
  5195. try:
  5196. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  5197. disconnect(self.on_excellon_format_changed)
  5198. except TypeError:
  5199. pass
  5200. try:
  5201. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  5202. disconnect(self.on_excellon_format_changed)
  5203. except TypeError:
  5204. pass
  5205. try:
  5206. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  5207. disconnect(self.on_excellon_format_changed)
  5208. except TypeError:
  5209. pass
  5210. try:
  5211. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  5212. disconnect(self.on_excellon_format_changed)
  5213. except TypeError:
  5214. pass
  5215. try:
  5216. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  5217. disconnect(self.on_excellon_zeros_changed)
  5218. except TypeError:
  5219. pass
  5220. try:
  5221. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  5222. disconnect(self.on_excellon_zeros_changed)
  5223. except TypeError:
  5224. pass
  5225. def on_excellon_format_changed(self):
  5226. """
  5227. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  5228. :return: None
  5229. """
  5230. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  5231. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5232. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  5233. )
  5234. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5235. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  5236. )
  5237. else:
  5238. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5239. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  5240. )
  5241. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5242. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  5243. )
  5244. def on_excellon_zeros_changed(self):
  5245. """
  5246. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  5247. :return: None
  5248. """
  5249. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  5250. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  5251. )
  5252. def on_excellon_units_changed(self):
  5253. """
  5254. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  5255. :return: None
  5256. """
  5257. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  5258. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  5259. )
  5260. self.on_excellon_format_changed()
  5261. # Setting plot colors handlers
  5262. def on_pf_color_entry(self):
  5263. self.defaults['global_plot_fill'] = \
  5264. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  5265. self.defaults['global_plot_fill'][7:9]
  5266. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5267. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  5268. def on_pf_color_button(self):
  5269. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  5270. c_dialog = QtWidgets.QColorDialog()
  5271. plot_fill_color = c_dialog.getColor(initial=current_color)
  5272. if plot_fill_color.isValid() is False:
  5273. return
  5274. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5275. "background-color:%s" % str(plot_fill_color.name()))
  5276. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  5277. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  5278. self.defaults['global_plot_fill'] = new_val
  5279. def on_pf_color_spinner(self):
  5280. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  5281. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  5282. self.defaults['global_plot_fill'] = \
  5283. self.defaults['global_plot_fill'][:7] + \
  5284. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5285. self.defaults['global_plot_line'] = \
  5286. self.defaults['global_plot_line'][:7] + \
  5287. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5288. def on_pf_color_slider(self):
  5289. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  5290. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  5291. def on_pl_color_entry(self):
  5292. self.defaults['global_plot_line'] = \
  5293. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  5294. self.defaults['global_plot_line'][7:9]
  5295. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5296. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  5297. def on_pl_color_button(self):
  5298. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  5299. # print(current_color)
  5300. c_dialog = QtWidgets.QColorDialog()
  5301. plot_line_color = c_dialog.getColor(initial=current_color)
  5302. if plot_line_color.isValid() is False:
  5303. return
  5304. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5305. "background-color:%s" % str(plot_line_color.name()))
  5306. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  5307. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  5308. self.defaults['global_plot_line'] = new_val_line
  5309. # Setting selection colors (left - right) handlers
  5310. def on_sf_color_entry(self):
  5311. self.defaults['global_sel_fill'] = \
  5312. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  5313. self.defaults['global_sel_fill'][7:9]
  5314. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5315. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  5316. def on_sf_color_button(self):
  5317. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  5318. c_dialog = QtWidgets.QColorDialog()
  5319. plot_fill_color = c_dialog.getColor(initial=current_color)
  5320. if plot_fill_color.isValid() is False:
  5321. return
  5322. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5323. "background-color:%s" % str(plot_fill_color.name()))
  5324. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  5325. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  5326. self.defaults['global_sel_fill'] = new_val
  5327. def on_sf_color_spinner(self):
  5328. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  5329. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  5330. self.defaults['global_sel_fill'] = \
  5331. self.defaults['global_sel_fill'][:7] + \
  5332. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5333. self.defaults['global_sel_line'] = \
  5334. self.defaults['global_sel_line'][:7] + \
  5335. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5336. def on_sf_color_slider(self):
  5337. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  5338. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  5339. def on_sl_color_entry(self):
  5340. self.defaults['global_sel_line'] = \
  5341. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  5342. self.defaults['global_sel_line'][7:9]
  5343. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5344. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  5345. def on_sl_color_button(self):
  5346. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  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.sl_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_sel_line'][7:9])
  5354. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  5355. self.defaults['global_sel_line'] = new_val_line
  5356. # Setting selection colors (right - left) handlers
  5357. def on_alt_sf_color_entry(self):
  5358. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  5359. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  5360. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5361. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  5362. def on_alt_sf_color_button(self):
  5363. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  5364. c_dialog = QtWidgets.QColorDialog()
  5365. plot_fill_color = c_dialog.getColor(initial=current_color)
  5366. if plot_fill_color.isValid() is False:
  5367. return
  5368. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5369. "background-color:%s" % str(plot_fill_color.name()))
  5370. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  5371. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  5372. self.defaults['global_alt_sel_fill'] = new_val
  5373. def on_alt_sf_color_spinner(self):
  5374. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  5375. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  5376. self.defaults['global_alt_sel_fill'] = \
  5377. self.defaults['global_alt_sel_fill'][:7] + \
  5378. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5379. self.defaults['global_alt_sel_line'] = \
  5380. self.defaults['global_alt_sel_line'][:7] + \
  5381. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5382. def on_alt_sf_color_slider(self):
  5383. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  5384. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  5385. def on_alt_sl_color_entry(self):
  5386. self.defaults['global_alt_sel_line'] = \
  5387. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  5388. self.defaults['global_alt_sel_line'][7:9]
  5389. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5390. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  5391. def on_alt_sl_color_button(self):
  5392. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  5393. c_dialog = QtWidgets.QColorDialog()
  5394. plot_line_color = c_dialog.getColor(initial=current_color)
  5395. if plot_line_color.isValid() is False:
  5396. return
  5397. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5398. "background-color:%s" % str(plot_line_color.name()))
  5399. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  5400. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  5401. self.defaults['global_alt_sel_line'] = new_val_line
  5402. # Setting Editor colors
  5403. def on_draw_color_entry(self):
  5404. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5405. .draw_color_entry.get_value()
  5406. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5407. "background-color:%s" % str(self.defaults['global_draw_color']))
  5408. def on_draw_color_button(self):
  5409. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  5410. c_dialog = QtWidgets.QColorDialog()
  5411. draw_color = c_dialog.getColor(initial=current_color)
  5412. if draw_color.isValid() is False:
  5413. return
  5414. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5415. "background-color:%s" % str(draw_color.name()))
  5416. new_val = str(draw_color.name())
  5417. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  5418. self.defaults['global_draw_color'] = new_val
  5419. def on_sel_draw_color_entry(self):
  5420. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5421. .sel_draw_color_entry.get_value()
  5422. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5423. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  5424. def on_sel_draw_color_button(self):
  5425. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  5426. c_dialog = QtWidgets.QColorDialog()
  5427. sel_draw_color = c_dialog.getColor(initial=current_color)
  5428. if sel_draw_color.isValid() is False:
  5429. return
  5430. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5431. "background-color:%s" % str(sel_draw_color.name()))
  5432. new_val_sel = str(sel_draw_color.name())
  5433. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  5434. self.defaults['global_sel_draw_color'] = new_val_sel
  5435. def on_proj_color_entry(self):
  5436. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  5437. .proj_color_entry.get_value()
  5438. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5439. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  5440. def on_proj_color_button(self):
  5441. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  5442. c_dialog = QtWidgets.QColorDialog()
  5443. proj_color = c_dialog.getColor(initial=current_color)
  5444. if proj_color.isValid() is False:
  5445. return
  5446. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5447. "background-color:%s" % str(proj_color.name()))
  5448. new_val_sel = str(proj_color.name())
  5449. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  5450. self.defaults['global_proj_item_color'] = new_val_sel
  5451. def on_proj_color_dis_entry(self):
  5452. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  5453. .proj_color_dis_entry.get_value()
  5454. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5455. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  5456. def on_proj_color_dis_button(self):
  5457. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  5458. c_dialog = QtWidgets.QColorDialog()
  5459. proj_color = c_dialog.getColor(initial=current_color)
  5460. if proj_color.isValid() is False:
  5461. return
  5462. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5463. "background-color:%s" % str(proj_color.name()))
  5464. new_val_sel = str(proj_color.name())
  5465. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  5466. self.defaults['global_proj_item_dis_color'] = new_val_sel
  5467. def on_annotation_fontcolor_entry(self):
  5468. self.defaults['cncjob_annotation_fontcolor'] = \
  5469. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.get_value()
  5470. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5471. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  5472. def on_annotation_fontcolor_button(self):
  5473. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  5474. c_dialog = QtWidgets.QColorDialog()
  5475. annotation_color = c_dialog.getColor(initial=current_color)
  5476. if annotation_color.isValid() is False:
  5477. return
  5478. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5479. "background-color:%s" % str(annotation_color.name()))
  5480. new_val_sel = str(annotation_color.name())
  5481. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(new_val_sel)
  5482. self.defaults['cncjob_annotation_fontcolor'] = new_val_sel
  5483. def on_film_color_entry(self):
  5484. self.defaults['tools_film_color'] = \
  5485. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  5486. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5487. "background-color:%s;"
  5488. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  5489. )
  5490. def on_film_color_button(self):
  5491. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  5492. c_dialog = QtWidgets.QColorDialog()
  5493. film_color = c_dialog.getColor(initial=current_color)
  5494. if film_color.isValid() is False:
  5495. return
  5496. # if new color is different then mark that the Preferences are changed
  5497. if film_color != current_color:
  5498. self.on_preferences_edited()
  5499. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5500. "background-color:%s;"
  5501. "border-color: dimgray" % str(film_color.name())
  5502. )
  5503. new_val_sel = str(film_color.name())
  5504. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  5505. self.defaults['tools_film_color'] = new_val_sel
  5506. def on_qrcode_fill_color_entry(self):
  5507. self.defaults['tools_qrcode_fill_color'] = \
  5508. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  5509. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5510. "background-color:%s;"
  5511. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  5512. )
  5513. def on_qrcode_fill_color_button(self):
  5514. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  5515. c_dialog = QtWidgets.QColorDialog()
  5516. fill_color = c_dialog.getColor(initial=current_color)
  5517. if fill_color.isValid() is False:
  5518. return
  5519. # if new color is different then mark that the Preferences are changed
  5520. if fill_color != current_color:
  5521. self.on_preferences_edited()
  5522. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5523. "background-color:%s;"
  5524. "border-color: dimgray" % str(fill_color.name())
  5525. )
  5526. new_val_sel = str(fill_color.name())
  5527. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  5528. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  5529. def on_qrcode_back_color_entry(self):
  5530. self.defaults['tools_qrcode_back_color'] = \
  5531. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  5532. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5533. "background-color:%s;"
  5534. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  5535. )
  5536. def on_qrcode_back_color_button(self):
  5537. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  5538. c_dialog = QtWidgets.QColorDialog()
  5539. back_color = c_dialog.getColor(initial=current_color)
  5540. if back_color.isValid() is False:
  5541. return
  5542. # if new color is different then mark that the Preferences are changed
  5543. if back_color != current_color:
  5544. self.on_preferences_edited()
  5545. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5546. "background-color:%s;"
  5547. "border-color: dimgray" % str(back_color.name())
  5548. )
  5549. new_val_sel = str(back_color.name())
  5550. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  5551. self.defaults['tools_qrcode_back_color'] = new_val_sel
  5552. def on_splash_changed(self, state):
  5553. settings = QSettings("Open Source", "FlatCAM")
  5554. settings.setValue('splash_screen', 1) if state else settings.setValue('splash_screen', 0)
  5555. # This will write the setting to the platform specific storage.
  5556. del settings
  5557. def on_tab_rmb_click(self, checked):
  5558. self.ui.notebook.set_detachable(val=checked)
  5559. self.defaults["global_tabs_detachable"] = checked
  5560. self.ui.plot_tab_area.set_detachable(val=checked)
  5561. self.defaults["global_tabs_detachable"] = checked
  5562. def on_tab_setup_context_menu(self):
  5563. initial_checked = self.defaults["global_tabs_detachable"]
  5564. action_name = str(_("Detachable Tabs"))
  5565. action = QtWidgets.QAction(self)
  5566. action.setCheckable(True)
  5567. action.setText(action_name)
  5568. action.setChecked(initial_checked)
  5569. self.ui.notebook.tabBar.addAction(action)
  5570. self.ui.plot_tab_area.tabBar.addAction(action)
  5571. try:
  5572. action.triggered.disconnect()
  5573. except TypeError:
  5574. pass
  5575. action.triggered.connect(self.on_tab_rmb_click)
  5576. def on_deselect_all(self):
  5577. self.collection.set_all_inactive()
  5578. self.delete_selection_shape()
  5579. def on_workspace_modified(self):
  5580. # self.save_defaults(silent=True)
  5581. if self.is_legacy is True:
  5582. self.plotcanvas.delete_workspace()
  5583. self.defaults_read_form()
  5584. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  5585. def on_workspace(self):
  5586. if self.ui.general_defaults_form.general_gui_group.workspace_cb.get_value():
  5587. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  5588. else:
  5589. self.plotcanvas.delete_workspace()
  5590. self.defaults_read_form()
  5591. # self.save_defaults(silent=True)
  5592. def on_workspace_toggle(self):
  5593. state = False if self.ui.general_defaults_form.general_gui_group.workspace_cb.get_value() else True
  5594. try:
  5595. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  5596. except TypeError:
  5597. pass
  5598. self.ui.general_defaults_form.general_gui_group.workspace_cb.set_value(state)
  5599. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  5600. self.on_workspace()
  5601. def on_layout(self, index=None, lay=None):
  5602. """
  5603. Set the toolbars layout (location)
  5604. :param index:
  5605. :param lay: type of layout to be set on the toolbard
  5606. :return: None
  5607. """
  5608. self.report_usage("on_layout()")
  5609. if lay:
  5610. current_layout = lay
  5611. else:
  5612. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  5613. lay_settings = QSettings("Open Source", "FlatCAM")
  5614. lay_settings.setValue('layout', current_layout)
  5615. # This will write the setting to the platform specific storage.
  5616. del lay_settings
  5617. # first remove the toolbars:
  5618. try:
  5619. self.ui.removeToolBar(self.ui.toolbarfile)
  5620. self.ui.removeToolBar(self.ui.toolbargeo)
  5621. self.ui.removeToolBar(self.ui.toolbarview)
  5622. self.ui.removeToolBar(self.ui.toolbarshell)
  5623. self.ui.removeToolBar(self.ui.toolbartools)
  5624. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  5625. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  5626. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  5627. self.ui.removeToolBar(self.ui.snap_toolbar)
  5628. self.ui.removeToolBar(self.ui.toolbarshell)
  5629. except Exception:
  5630. pass
  5631. if current_layout == 'standard':
  5632. # ## TOOLBAR INSTALLATION # ##
  5633. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5634. self.ui.toolbarfile.setObjectName('File_TB')
  5635. self.ui.addToolBar(self.ui.toolbarfile)
  5636. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5637. self.ui.toolbargeo.setObjectName('Edit_TB')
  5638. self.ui.addToolBar(self.ui.toolbargeo)
  5639. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5640. self.ui.toolbarview.setObjectName('View_TB')
  5641. self.ui.addToolBar(self.ui.toolbarview)
  5642. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5643. self.ui.toolbarshell.setObjectName('Shell_TB')
  5644. self.ui.addToolBar(self.ui.toolbarshell)
  5645. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5646. self.ui.toolbartools.setObjectName('Tools_TB')
  5647. self.ui.addToolBar(self.ui.toolbartools)
  5648. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5649. # self.ui.exc_edit_toolbar.setVisible(False)
  5650. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5651. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  5652. self.ui.addToolBarBreak()
  5653. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5654. # self.ui.geo_edit_toolbar.setVisible(False)
  5655. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5656. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  5657. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5658. # self.ui.grb_edit_toolbar.setVisible(False)
  5659. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5660. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  5661. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5662. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5663. # self.ui.snap_toolbar.setMaximumHeight(30)
  5664. self.ui.addToolBar(self.ui.snap_toolbar)
  5665. self.ui.corner_snap_btn.setVisible(False)
  5666. self.ui.snap_magnet.setVisible(False)
  5667. elif current_layout == 'compact':
  5668. # ## TOOLBAR INSTALLATION # ##
  5669. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5670. self.ui.toolbarfile.setObjectName('File_TB')
  5671. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  5672. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5673. self.ui.toolbargeo.setObjectName('Edit_TB')
  5674. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  5675. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5676. self.ui.toolbarshell.setObjectName('Shell_TB')
  5677. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  5678. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5679. self.ui.toolbartools.setObjectName('Tools_TB')
  5680. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  5681. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5682. # self.ui.geo_edit_toolbar.setVisible(False)
  5683. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5684. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  5685. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5686. self.ui.toolbarview.setObjectName('View_TB')
  5687. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  5688. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  5689. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5690. # self.ui.grb_edit_toolbar.setVisible(False)
  5691. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5692. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  5693. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5694. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5695. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  5696. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5697. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5698. self.ui.snap_toolbar.setMaximumHeight(30)
  5699. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  5700. self.ui.corner_snap_btn.setVisible(True)
  5701. self.ui.snap_magnet.setVisible(True)
  5702. # add all the actions to the toolbars
  5703. self.ui.populate_toolbars()
  5704. # reconnect all the signals to the toolbar actions
  5705. self.connect_toolbar_signals()
  5706. self.ui.grid_snap_btn.setChecked(True)
  5707. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  5708. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  5709. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  5710. self.ui.grid_gap_link_cb.setChecked(True)
  5711. def on_cursor_type(self, val):
  5712. """
  5713. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  5714. :return: None
  5715. """
  5716. self.app_cursor.enabled = False
  5717. if val == 'small':
  5718. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(False)
  5719. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(False)
  5720. self.app_cursor = self.plotcanvas.new_cursor()
  5721. else:
  5722. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(True)
  5723. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(True)
  5724. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  5725. if self.ui.grid_snap_btn.isChecked():
  5726. self.app_cursor.enabled = True
  5727. else:
  5728. self.app_cursor.enabled = False
  5729. def on_cnc_custom_parameters(self, signal_text):
  5730. if signal_text == 'Parameters':
  5731. return
  5732. else:
  5733. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  5734. def on_save_button(self):
  5735. log.debug("App.on_save_button() --> Saving preferences to file.")
  5736. # Preferences saved, update flag
  5737. self.preferences_changed_flag = False
  5738. # Preferences save, update the color of the Preferences Tab text
  5739. for idx in range(self.ui.plot_tab_area.count()):
  5740. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5741. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  5742. self.save_defaults(silent=False)
  5743. # load the defaults so they are updated into the app
  5744. self.load_defaults(filename='current_defaults')
  5745. # Re-fresh project options
  5746. self.on_options_app2project()
  5747. settgs = QSettings("Open Source", "FlatCAM")
  5748. # save the notebook font size
  5749. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  5750. settgs.setValue('notebook_font_size', fsize)
  5751. # save the axis font size
  5752. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  5753. settgs.setValue('axis_font_size', g_fsize)
  5754. # save the textbox font size
  5755. tb_fsize = self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  5756. settgs.setValue('textbox_font_size', tb_fsize)
  5757. settgs.setValue(
  5758. 'machinist',
  5759. 1 if self.ui.general_defaults_form.general_app_group.machinist_cb.get_value() else 0
  5760. )
  5761. # This will write the setting to the platform specific storage.
  5762. del settgs
  5763. def on_tool_add_keypress(self):
  5764. # ## Current application units in Upper Case
  5765. self.units = self.defaults['units'].upper()
  5766. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5767. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5768. if notebook_widget_name == 'selected_tab':
  5769. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5770. # Tool add works for Geometry only if Advanced is True in Preferences
  5771. if self.defaults["global_app_level"] == 'a':
  5772. tool_add_popup = FCInputDialog(title="New Tool ...",
  5773. text='Enter a Tool Diameter:',
  5774. min=0.0000, max=99.9999, decimals=4)
  5775. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5776. val, ok = tool_add_popup.get_value()
  5777. if ok:
  5778. if float(val) == 0:
  5779. self.inform.emit('[WARNING_NOTCL] %s' %
  5780. _("Please enter a tool diameter with non-zero value, in Float format."))
  5781. return
  5782. self.collection.get_active().on_tool_add(dia=float(val))
  5783. else:
  5784. self.inform.emit('[WARNING_NOTCL] %s...' %
  5785. _("Adding Tool cancelled"))
  5786. else:
  5787. msgbox = QtWidgets.QMessageBox()
  5788. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5789. "Go to Preferences -> General - Show Advanced Options."))
  5790. msgbox.setWindowTitle("Tool adding ...")
  5791. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  5792. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5793. msgbox.setDefaultButton(bt_ok)
  5794. msgbox.exec_()
  5795. # work only if the notebook tab on focus is the Tools_Tab
  5796. if notebook_widget_name == 'tool_tab':
  5797. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5798. # and only if the tool is NCC Tool
  5799. if tool_widget == self.ncclear_tool.toolName:
  5800. self.ncclear_tool.on_add_tool_by_key()
  5801. # and only if the tool is Paint Area Tool
  5802. elif tool_widget == self.paint_tool.toolName:
  5803. self.paint_tool.on_add_tool_by_key()
  5804. # and only if the tool is Solder Paste Dispensing Tool
  5805. elif tool_widget == self.paste_tool.toolName:
  5806. self.paste_tool.on_add_tool_by_key()
  5807. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5808. # See description bellow.
  5809. def on_delete_keypress(self):
  5810. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5811. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5812. if notebook_widget_name == 'selected_tab':
  5813. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5814. self.collection.get_active().on_tool_delete()
  5815. # work only if the notebook tab on focus is the Tools_Tab
  5816. elif notebook_widget_name == 'tool_tab':
  5817. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5818. # and only if the tool is NCC Tool
  5819. if tool_widget == self.ncclear_tool.toolName:
  5820. self.ncclear_tool.on_tool_delete()
  5821. # and only if the tool is Paint Tool
  5822. elif tool_widget == self.paint_tool.toolName:
  5823. self.paint_tool.on_tool_delete()
  5824. # and only if the tool is Solder Paste Dispensing Tool
  5825. elif tool_widget == self.paste_tool.toolName:
  5826. self.paste_tool.on_tool_delete()
  5827. else:
  5828. self.on_delete()
  5829. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5830. # some screens you have to be careful where you hover with your mouse.
  5831. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5832. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5833. # Complicated, I know :)
  5834. def on_delete(self):
  5835. """
  5836. Delete the currently selected FlatCAMObjs.
  5837. :return: None
  5838. """
  5839. self.report_usage("on_delete()")
  5840. response = None
  5841. bt_ok = None
  5842. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5843. # a geometry object before we update it.
  5844. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5845. and self.grb_editor.editor_active is False:
  5846. if self.defaults["global_delete_confirmation"] is True:
  5847. msgbox = QtWidgets.QMessageBox()
  5848. msgbox.setWindowTitle(_("Delete objects"))
  5849. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  5850. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5851. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5852. "the selected objects?"))
  5853. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5854. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5855. msgbox.setDefaultButton(bt_ok)
  5856. msgbox.exec_()
  5857. response = msgbox.clickedButton()
  5858. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  5859. if self.collection.get_active():
  5860. self.log.debug("App.on_delete()")
  5861. while self.collection.get_active():
  5862. obj_active = self.collection.get_active()
  5863. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  5864. if isinstance(obj_active, FlatCAMGerber):
  5865. for el in obj_active.mark_shapes:
  5866. obj_active.mark_shapes[el].clear(update=True)
  5867. obj_active.mark_shapes[el].enabled = False
  5868. # obj_active.mark_shapes[el] = None
  5869. del el
  5870. elif isinstance(obj_active, FlatCAMCNCjob):
  5871. try:
  5872. obj_active.annotation.clear(update=True)
  5873. obj_active.annotation.enabled = False
  5874. except AttributeError:
  5875. pass
  5876. self.delete_first_selected()
  5877. self.inform.emit('%s...' %
  5878. _("Object(s) deleted"))
  5879. # make sure that the selection shape is deleted, too
  5880. self.delete_selection_shape()
  5881. else:
  5882. self.inform.emit(_("Failed. No object(s) selected..."))
  5883. else:
  5884. self.inform.emit(_("Save the work in Editor and try again ..."))
  5885. def delete_first_selected(self):
  5886. # Keep this for later
  5887. try:
  5888. sel_obj = self.collection.get_active()
  5889. name = sel_obj.options["name"]
  5890. isPlotted = sel_obj.options["plot"]
  5891. except AttributeError:
  5892. self.log.debug("Nothing selected for deletion")
  5893. return
  5894. if self.is_legacy is True:
  5895. # Remove plot only if the object was plotted otherwise delaxes will fail
  5896. if isPlotted:
  5897. try:
  5898. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  5899. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  5900. except Exception as e:
  5901. log.debug("App.delete_first_selected() --> %s" % str(e))
  5902. self.plotcanvas.auto_adjust_axes()
  5903. # Remove from dictionary
  5904. self.collection.delete_active()
  5905. # Clear form
  5906. self.setup_component_editor()
  5907. self.inform.emit('%s: %s' %
  5908. (_("Object deleted"), name))
  5909. def on_set_origin(self):
  5910. """
  5911. Set the origin to the left mouse click position
  5912. :return: None
  5913. """
  5914. # display the message for the user
  5915. # and ask him to click on the desired position
  5916. self.report_usage("on_set_origin()")
  5917. def origin_replot():
  5918. def worker_task():
  5919. with self.proc_container.new('%s...' % _("Plotting")):
  5920. for obj in self.collection.get_list():
  5921. obj.plot()
  5922. self.plotcanvas.fit_view()
  5923. if self.is_legacy:
  5924. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  5925. else:
  5926. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  5927. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5928. self.inform.emit(_('Click to set the origin ...'))
  5929. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  5930. # first disconnect it as it may have been used by something else
  5931. try:
  5932. self.replot_signal.disconnect()
  5933. except TypeError:
  5934. pass
  5935. self.replot_signal[list].connect(origin_replot)
  5936. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  5937. """
  5938. :param event:
  5939. :param location:
  5940. :param noplot:
  5941. :param use_thread:
  5942. :return:
  5943. """
  5944. noplot_sig = noplot
  5945. def worker_task():
  5946. with self.proc_container.new(_("Setting Origin...")):
  5947. for obj in self.collection.get_list():
  5948. obj.offset((x, y))
  5949. self.object_changed.emit(obj)
  5950. # Update the object bounding box options
  5951. a, b, c, d = obj.bounds()
  5952. obj.options['xmin'] = a
  5953. obj.options['ymin'] = b
  5954. obj.options['xmax'] = c
  5955. obj.options['ymax'] = d
  5956. self.inform.emit('[success] %s...' %
  5957. _('Origin set'))
  5958. if noplot_sig is False:
  5959. self.replot_signal.emit([])
  5960. if location is not None:
  5961. if len(location) != 2:
  5962. self.inform.emit('[ERROR_NOTCL] %s...' %
  5963. _("Origin coordinates specified but incomplete."))
  5964. return 'fail'
  5965. x, y = location
  5966. if use_thread is True:
  5967. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5968. else:
  5969. worker_task()
  5970. self.should_we_save = True
  5971. return
  5972. if event.button == 1:
  5973. if self.is_legacy is False:
  5974. event_pos = event.pos
  5975. else:
  5976. event_pos = (event.xdata, event.ydata)
  5977. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5978. if self.grid_status() == True:
  5979. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5980. else:
  5981. pos = pos_canvas
  5982. x = 0 - pos[0]
  5983. y = 0 - pos[1]
  5984. if use_thread is True:
  5985. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5986. else:
  5987. worker_task()
  5988. self.should_we_save = True
  5989. def on_jump_to(self, custom_location=None, fit_center=True):
  5990. """
  5991. Jump to a location by setting the mouse cursor location
  5992. :return:
  5993. """
  5994. self.report_usage("on_jump_to()")
  5995. # if self.is_legacy is True:
  5996. # self.inform.emit(_("Not available with the current Graphic Engine Legacy(2D)."))
  5997. # return
  5998. if not custom_location:
  5999. dia_box_location = None
  6000. try:
  6001. dia_box_location = eval(self.clipboard.text())
  6002. except Exception:
  6003. pass
  6004. if type(dia_box_location) == tuple:
  6005. dia_box_location = str(dia_box_location)
  6006. else:
  6007. dia_box_location = None
  6008. dia_box = Dialog_box(title=_("Jump to ..."),
  6009. label=_("Enter the coordinates in format X,Y:"),
  6010. icon=QtGui.QIcon('share/jump_to16.png'),
  6011. initial_text=dia_box_location)
  6012. if dia_box.ok is True:
  6013. try:
  6014. location = eval(dia_box.location)
  6015. if not isinstance(location, tuple):
  6016. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  6017. return
  6018. except Exception:
  6019. return
  6020. else:
  6021. return
  6022. else:
  6023. location = custom_location
  6024. if fit_center:
  6025. self.plotcanvas.fit_center(loc=location)
  6026. cursor = QtGui.QCursor()
  6027. if self.is_legacy is False:
  6028. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6029. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  6030. j_pos = (canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  6031. cursor.setPos(j_pos[0], j_pos[1])
  6032. else:
  6033. # find the canvas origin which is in the top left corner
  6034. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6035. # determine the coordinates for the lowest left point of the canvas
  6036. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  6037. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  6038. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  6039. # canvas) and the point (width, height) is in the top-right location
  6040. loc = self.plotcanvas.axes.transData.transform_point(location)
  6041. j_pos = (x0 + loc[0], y0 - loc[1])
  6042. cursor.setPos(j_pos[0], j_pos[1])
  6043. if self.grid_status() == True:
  6044. # Update cursor
  6045. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  6046. symbol='++', edge_color=self.cursor_color_3D,
  6047. size=self.defaults["global_cursor_size"])
  6048. # Set the position label
  6049. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6050. "<b>Y</b>: %.4f" % (location[0], location[1]))
  6051. # Set the relative position label
  6052. dx = location[0] - float(self.rel_point1[0])
  6053. dy = location[1] - float(self.rel_point1[1])
  6054. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6055. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6056. self.inform.emit('[success] %s' %
  6057. _("Done."))
  6058. return location
  6059. def on_copy_object(self):
  6060. self.report_usage("on_copy_object()")
  6061. def initialize(obj_init, app):
  6062. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6063. try:
  6064. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  6065. except AttributeError:
  6066. pass
  6067. try:
  6068. obj_init.apertures = deepcopy(obj.apertures)
  6069. except AttributeError:
  6070. pass
  6071. try:
  6072. if obj.tools:
  6073. obj_init.tools = deepcopy(obj.tools)
  6074. except Exception as e:
  6075. log.debug("App.on_copy_object() --> %s" % str(e))
  6076. def initialize_excellon(obj_init, app):
  6077. obj_init.tools = deepcopy(obj.tools)
  6078. # drills are offset, so they need to be deep copied
  6079. obj_init.drills = deepcopy(obj.drills)
  6080. # slots are offset, so they need to be deep copied
  6081. obj_init.slots = deepcopy(obj.slots)
  6082. obj_init.create_geometry()
  6083. def initialize_script(obj_init, app_obj):
  6084. obj_init.source_file = deepcopy(obj.source_file)
  6085. def initialize_document(obj_init, app_obj):
  6086. obj_init.source_file = deepcopy(obj.source_file)
  6087. for obj in self.collection.get_selected():
  6088. obj_name = obj.options["name"]
  6089. try:
  6090. if isinstance(obj, FlatCAMExcellon):
  6091. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  6092. elif isinstance(obj, FlatCAMGerber):
  6093. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  6094. elif isinstance(obj, FlatCAMGeometry):
  6095. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  6096. elif isinstance(obj, FlatCAMScript):
  6097. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  6098. elif isinstance(obj, FlatCAMDocument):
  6099. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  6100. except Exception as e:
  6101. return "Operation failed: %s" % str(e)
  6102. def on_copy_object2(self, custom_name):
  6103. def initialize_geometry(obj_init, app):
  6104. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6105. try:
  6106. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  6107. except AttributeError:
  6108. pass
  6109. try:
  6110. obj_init.apertures = deepcopy(obj.apertures)
  6111. except AttributeError:
  6112. pass
  6113. try:
  6114. if obj.tools:
  6115. obj_init.tools = deepcopy(obj.tools)
  6116. except Exception as ee:
  6117. log.debug("on_copy_object2() --> %s" % str(ee))
  6118. def initialize_gerber(obj_init, app):
  6119. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6120. obj_init.apertures = deepcopy(obj.apertures)
  6121. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  6122. def initialize_excellon(obj_init, app):
  6123. obj_init.tools = deepcopy(obj.tools)
  6124. # drills are offset, so they need to be deep copied
  6125. obj_init.drills = deepcopy(obj.drills)
  6126. # slots are offset, so they need to be deep copied
  6127. obj_init.slots = deepcopy(obj.slots)
  6128. obj_init.create_geometry()
  6129. for obj in self.collection.get_selected():
  6130. obj_name = obj.options["name"]
  6131. try:
  6132. if isinstance(obj, FlatCAMExcellon):
  6133. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  6134. elif isinstance(obj, FlatCAMGerber):
  6135. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  6136. elif isinstance(obj, FlatCAMGeometry):
  6137. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  6138. except Exception as e:
  6139. return "Operation failed: %s" % str(e)
  6140. def on_rename_object(self, text):
  6141. self.report_usage("on_rename_object()")
  6142. named_obj = self.collection.get_active()
  6143. for obj in named_obj:
  6144. if obj is list:
  6145. self.on_rename_object(text)
  6146. else:
  6147. try:
  6148. obj.options['name'] = text
  6149. except Exception as e:
  6150. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  6151. def convert_any2geo(self):
  6152. self.report_usage("convert_any2geo()")
  6153. def initialize(obj_init, app):
  6154. obj_init.solid_geometry = obj.solid_geometry
  6155. try:
  6156. obj_init.follow_geometry = obj.follow_geometry
  6157. except AttributeError:
  6158. pass
  6159. try:
  6160. obj_init.apertures = obj.apertures
  6161. except AttributeError:
  6162. pass
  6163. try:
  6164. if obj.tools:
  6165. obj_init.tools = obj.tools
  6166. except AttributeError:
  6167. pass
  6168. def initialize_excellon(obj_init, app):
  6169. # objs = self.collection.get_selected()
  6170. # FlatCAMGeometry.merge(objs, obj)
  6171. solid_geo = []
  6172. for tool in obj.tools:
  6173. for geo in obj.tools[tool]['solid_geometry']:
  6174. solid_geo.append(geo)
  6175. obj_init.solid_geometry = deepcopy(solid_geo)
  6176. if not self.collection.get_selected():
  6177. log.warning("App.convert_any2geo --> No object selected")
  6178. self.inform.emit('[WARNING_NOTCL] %s' %
  6179. _("No object is selected. Select an object and try again."))
  6180. return
  6181. for obj in self.collection.get_selected():
  6182. obj_name = obj.options["name"]
  6183. try:
  6184. if isinstance(obj, FlatCAMExcellon):
  6185. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  6186. else:
  6187. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  6188. except Exception as e:
  6189. return "Operation failed: %s" % str(e)
  6190. def convert_any2gerber(self):
  6191. self.report_usage("convert_any2gerber()")
  6192. def initialize_geometry(obj_init, app):
  6193. apertures = {}
  6194. apid = 0
  6195. apertures[str(apid)] = {}
  6196. apertures[str(apid)]['geometry'] = []
  6197. for obj_orig in obj.solid_geometry:
  6198. new_elem = dict()
  6199. new_elem['solid'] = obj_orig
  6200. try:
  6201. new_elem['follow'] = obj_orig.exterior
  6202. except AttributeError:
  6203. pass
  6204. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  6205. apertures[str(apid)]['size'] = 0.0
  6206. apertures[str(apid)]['type'] = 'C'
  6207. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6208. obj_init.apertures = deepcopy(apertures)
  6209. def initialize_excellon(obj_init, app):
  6210. apertures = {}
  6211. apid = 10
  6212. for tool in obj.tools:
  6213. apertures[str(apid)] = {}
  6214. apertures[str(apid)]['geometry'] = []
  6215. for geo in obj.tools[tool]['solid_geometry']:
  6216. new_el = dict()
  6217. new_el['solid'] = geo
  6218. new_el['follow'] = geo.exterior
  6219. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  6220. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  6221. apertures[str(apid)]['type'] = 'C'
  6222. apid += 1
  6223. # create solid_geometry
  6224. solid_geometry = []
  6225. for apid in apertures:
  6226. for geo_el in apertures[apid]['geometry']:
  6227. solid_geometry.append(geo_el['solid'])
  6228. solid_geometry = MultiPolygon(solid_geometry)
  6229. solid_geometry = solid_geometry.buffer(0.0000001)
  6230. obj_init.solid_geometry = deepcopy(solid_geometry)
  6231. obj_init.apertures = deepcopy(apertures)
  6232. # clear the working objects (perhaps not necessary due of Python GC)
  6233. apertures.clear()
  6234. if not self.collection.get_selected():
  6235. log.warning("App.convert_any2gerber --> No object selected")
  6236. self.inform.emit('[WARNING_NOTCL] %s' %
  6237. _("No object is selected. Select an object and try again."))
  6238. return
  6239. for obj in self.collection.get_selected():
  6240. obj_name = obj.options["name"]
  6241. try:
  6242. if isinstance(obj, FlatCAMExcellon):
  6243. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  6244. elif isinstance(obj, FlatCAMGeometry):
  6245. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  6246. else:
  6247. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  6248. except Exception as e:
  6249. return "Operation failed: %s" % str(e)
  6250. def abort_all_tasks(self):
  6251. if self.abort_flag is False:
  6252. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  6253. self.abort_flag = True
  6254. def app_is_idle(self):
  6255. if self.abort_flag:
  6256. self.inform.emit('[WARNING_NOTCL] %s' %
  6257. _("The current task was gracefully closed on user request..."))
  6258. self.abort_flag = False
  6259. def on_selectall(self):
  6260. self.report_usage("on_selectall()")
  6261. # delete the possible selection box around a possible selected object
  6262. self.delete_selection_shape()
  6263. for name in self.collection.get_names():
  6264. self.collection.set_active(name)
  6265. curr_sel_obj = self.collection.get_by_name(name)
  6266. # create the selection box around the selected object
  6267. if self.defaults['global_selection_shape'] is True:
  6268. self.draw_selection_shape(curr_sel_obj)
  6269. def on_preferences(self):
  6270. """
  6271. Adds the Preferences in a Tab in Plot Area
  6272. :return:
  6273. """
  6274. # add the tab if it was closed
  6275. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  6276. # delete the absolute and relative position and messages in the infobar
  6277. self.ui.position_label.setText("")
  6278. self.ui.rel_position_label.setText("")
  6279. # Switch plot_area to preferences page
  6280. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  6281. # self.ui.show()
  6282. # detect changes in the preferences
  6283. for idx in range(self.ui.pref_tab_area.count()):
  6284. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6285. try:
  6286. try:
  6287. tb.textEdited.disconnect(self.on_preferences_edited)
  6288. except (TypeError, AttributeError):
  6289. pass
  6290. tb.textEdited.connect(self.on_preferences_edited)
  6291. except AttributeError:
  6292. pass
  6293. try:
  6294. try:
  6295. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6296. except (TypeError, AttributeError):
  6297. pass
  6298. tb.modificationChanged.connect(self.on_preferences_edited)
  6299. except AttributeError:
  6300. pass
  6301. try:
  6302. try:
  6303. tb.toggled.disconnect(self.on_preferences_edited)
  6304. except (TypeError, AttributeError):
  6305. pass
  6306. tb.toggled.connect(self.on_preferences_edited)
  6307. except AttributeError:
  6308. pass
  6309. try:
  6310. try:
  6311. tb.valueChanged.disconnect(self.on_preferences_edited)
  6312. except (TypeError, AttributeError):
  6313. pass
  6314. tb.valueChanged.connect(self.on_preferences_edited)
  6315. except AttributeError:
  6316. pass
  6317. try:
  6318. try:
  6319. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6320. except (TypeError, AttributeError):
  6321. pass
  6322. tb.currentIndexChanged.connect(self.on_preferences_edited)
  6323. except AttributeError:
  6324. pass
  6325. def on_preferences_edited(self):
  6326. self.inform.emit('[WARNING_NOTCL] %s' %
  6327. _("Preferences edited but not saved."))
  6328. for idx in range(self.ui.plot_tab_area.count()):
  6329. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  6330. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  6331. self.preferences_changed_flag = True
  6332. def on_tools_database(self):
  6333. """
  6334. Adds the Tools Database in a Tab in Plot Area
  6335. :return:
  6336. """
  6337. for idx in range(self.ui.plot_tab_area.count()):
  6338. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6339. # there can be only one instance of Tools Database at one time
  6340. return
  6341. self.tools_db_tab = ToolsDB(
  6342. app=self,
  6343. parent=self.ui,
  6344. callback_on_edited=self.on_tools_db_edited,
  6345. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  6346. )
  6347. # add the tab if it was closed
  6348. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  6349. self.tools_db_tab.setObjectName("database_tab")
  6350. # delete the absolute and relative position and messages in the infobar
  6351. self.ui.position_label.setText("")
  6352. self.ui.rel_position_label.setText("")
  6353. # Switch plot_area to preferences page
  6354. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  6355. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  6356. self.tools_db_tab.ui_connect()
  6357. def on_tools_db_edited(self):
  6358. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  6359. for idx in range(self.ui.plot_tab_area.count()):
  6360. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6361. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  6362. self.tools_db_changed_flag = True
  6363. def on_geometry_tool_add_from_db_executed(self, tool):
  6364. """
  6365. Here add the tool from DB in the selected geometry object
  6366. :return:
  6367. """
  6368. tool_from_db = deepcopy(tool)
  6369. obj = self.collection.get_active()
  6370. if isinstance(obj, FlatCAMGeometry):
  6371. obj.on_tool_from_db_inserted(tool=tool_from_db)
  6372. for idx in range(self.ui.plot_tab_area.count()):
  6373. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6374. wdg = self.ui.plot_tab_area.widget(idx)
  6375. wdg.deleteLater()
  6376. self.ui.plot_tab_area.removeTab(idx)
  6377. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  6378. else:
  6379. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  6380. def on_plot_area_tab_closed(self, title):
  6381. if title == _("Preferences"):
  6382. # disconnect
  6383. for idx in range(self.ui.pref_tab_area.count()):
  6384. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6385. try:
  6386. tb.textEdited.disconnect(self.on_preferences_edited)
  6387. except (TypeError, AttributeError):
  6388. pass
  6389. try:
  6390. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6391. except (TypeError, AttributeError):
  6392. pass
  6393. try:
  6394. tb.toggled.disconnect(self.on_preferences_edited)
  6395. except (TypeError, AttributeError):
  6396. pass
  6397. try:
  6398. tb.valueChanged.disconnect(self.on_preferences_edited)
  6399. except (TypeError, AttributeError):
  6400. pass
  6401. try:
  6402. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6403. except (TypeError, AttributeError):
  6404. pass
  6405. if self.preferences_changed_flag is True:
  6406. msgbox = QtWidgets.QMessageBox()
  6407. msgbox.setText(_("One or more values are changed.\n"
  6408. "Do you want to save the Preferences?"))
  6409. msgbox.setWindowTitle(_("Save Preferences"))
  6410. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6411. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6412. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6413. msgbox.setDefaultButton(bt_yes)
  6414. msgbox.exec_()
  6415. response = msgbox.clickedButton()
  6416. if response == bt_yes:
  6417. self.on_save_button()
  6418. self.inform.emit('[success] %s' % _("Preferences saved."))
  6419. else:
  6420. self.preferences_changed_flag = False
  6421. self.inform.emit('')
  6422. return
  6423. if title == _("Tools Database"):
  6424. # disconnect the signals from the table widget in tab
  6425. self.tools_db_tab.ui_disconnect()
  6426. if self.tools_db_changed_flag is True:
  6427. msgbox = QtWidgets.QMessageBox()
  6428. msgbox.setText(_("One or more Tools are edited.\n"
  6429. "Do you want to update the Tools Database?"))
  6430. msgbox.setWindowTitle(_("Save Tools Database"))
  6431. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6432. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6433. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6434. msgbox.setDefaultButton(bt_yes)
  6435. msgbox.exec_()
  6436. response = msgbox.clickedButton()
  6437. if response == bt_yes:
  6438. self.tools_db_tab.on_save_tools_db()
  6439. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  6440. else:
  6441. self.tools_db_changed_flag = False
  6442. self.inform.emit('')
  6443. return
  6444. self.tools_db_tab.deleteLater()
  6445. if title == _("Code Editor"):
  6446. self.toggle_codeeditor = False
  6447. if title == _("Bookmarks Manager"):
  6448. self.book_dialog_tab.rebuild_actions()
  6449. self.book_dialog_tab.deleteLater()
  6450. def on_flipy(self):
  6451. self.report_usage("on_flipy()")
  6452. obj_list = self.collection.get_selected()
  6453. xminlist = []
  6454. yminlist = []
  6455. xmaxlist = []
  6456. ymaxlist = []
  6457. if not obj_list:
  6458. self.inform.emit('[WARNING_NOTCL] %s' %
  6459. _("No object selected to Flip on Y axis."))
  6460. else:
  6461. try:
  6462. # first get a bounding box to fit all
  6463. for obj in obj_list:
  6464. xmin, ymin, xmax, ymax = obj.bounds()
  6465. xminlist.append(xmin)
  6466. yminlist.append(ymin)
  6467. xmaxlist.append(xmax)
  6468. ymaxlist.append(ymax)
  6469. # get the minimum x,y and maximum x,y for all objects selected
  6470. xminimal = min(xminlist)
  6471. yminimal = min(yminlist)
  6472. xmaximal = max(xmaxlist)
  6473. ymaximal = max(ymaxlist)
  6474. px = 0.5 * (xminimal + xmaximal)
  6475. py = 0.5 * (yminimal + ymaximal)
  6476. # execute mirroring
  6477. for obj in obj_list:
  6478. obj.mirror('X', [px, py])
  6479. obj.plot()
  6480. self.object_changed.emit(obj)
  6481. self.inform.emit('[success] %s' %
  6482. _("Flip on Y axis done."))
  6483. except Exception as e:
  6484. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  6485. return
  6486. def on_flipx(self):
  6487. self.report_usage("on_flipx()")
  6488. obj_list = self.collection.get_selected()
  6489. xminlist = []
  6490. yminlist = []
  6491. xmaxlist = []
  6492. ymaxlist = []
  6493. if not obj_list:
  6494. self.inform.emit('[WARNING_NOTCL] %s' %
  6495. _("No object selected to Flip on X axis."))
  6496. else:
  6497. try:
  6498. # first get a bounding box to fit all
  6499. for obj in obj_list:
  6500. xmin, ymin, xmax, ymax = obj.bounds()
  6501. xminlist.append(xmin)
  6502. yminlist.append(ymin)
  6503. xmaxlist.append(xmax)
  6504. ymaxlist.append(ymax)
  6505. # get the minimum x,y and maximum x,y for all objects selected
  6506. xminimal = min(xminlist)
  6507. yminimal = min(yminlist)
  6508. xmaximal = max(xmaxlist)
  6509. ymaximal = max(ymaxlist)
  6510. px = 0.5 * (xminimal + xmaximal)
  6511. py = 0.5 * (yminimal + ymaximal)
  6512. # execute mirroring
  6513. for obj in obj_list:
  6514. obj.mirror('Y', [px, py])
  6515. obj.plot()
  6516. self.object_changed.emit(obj)
  6517. self.inform.emit('[success] %s' %
  6518. _("Flip on X axis done."))
  6519. except Exception as e:
  6520. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  6521. return
  6522. def on_rotate(self, silent=False, preset=None):
  6523. self.report_usage("on_rotate()")
  6524. obj_list = self.collection.get_selected()
  6525. xminlist = []
  6526. yminlist = []
  6527. xmaxlist = []
  6528. ymaxlist = []
  6529. if not obj_list:
  6530. self.inform.emit('[WARNING_NOTCL] %s' %
  6531. _("No object selected to Rotate."))
  6532. else:
  6533. if silent is False:
  6534. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6535. min=-360, max=360, decimals=4,
  6536. init_val=float(self.defaults['tools_transform_rotate']))
  6537. num, ok = rotatebox.get_value()
  6538. else:
  6539. num = preset
  6540. ok = True
  6541. if ok:
  6542. try:
  6543. # first get a bounding box to fit all
  6544. for obj in obj_list:
  6545. xmin, ymin, xmax, ymax = obj.bounds()
  6546. xminlist.append(xmin)
  6547. yminlist.append(ymin)
  6548. xmaxlist.append(xmax)
  6549. ymaxlist.append(ymax)
  6550. # get the minimum x,y and maximum x,y for all objects selected
  6551. xminimal = min(xminlist)
  6552. yminimal = min(yminlist)
  6553. xmaximal = max(xmaxlist)
  6554. ymaximal = max(ymaxlist)
  6555. px = 0.5 * (xminimal + xmaximal)
  6556. py = 0.5 * (yminimal + ymaximal)
  6557. for sel_obj in obj_list:
  6558. sel_obj.rotate(-float(num), point=(px, py))
  6559. sel_obj.plot()
  6560. self.object_changed.emit(sel_obj)
  6561. self.inform.emit('[success] %s' %
  6562. _("Rotation done."))
  6563. except Exception as e:
  6564. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  6565. return
  6566. def on_skewx(self):
  6567. self.report_usage("on_skewx()")
  6568. obj_list = self.collection.get_selected()
  6569. xminlist = []
  6570. yminlist = []
  6571. if not obj_list:
  6572. self.inform.emit('[WARNING_NOTCL] %s' %
  6573. _("No object selected to Skew/Shear on X axis."))
  6574. else:
  6575. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6576. min=-360, max=360, decimals=4,
  6577. init_val=float(self.defaults['tools_transform_skew_x']))
  6578. num, ok = skewxbox.get_value()
  6579. if ok:
  6580. # first get a bounding box to fit all
  6581. for obj in obj_list:
  6582. xmin, ymin, xmax, ymax = obj.bounds()
  6583. xminlist.append(xmin)
  6584. yminlist.append(ymin)
  6585. # get the minimum x,y and maximum x,y for all objects selected
  6586. xminimal = min(xminlist)
  6587. yminimal = min(yminlist)
  6588. for obj in obj_list:
  6589. obj.skew(num, 0, point=(xminimal, yminimal))
  6590. obj.plot()
  6591. self.object_changed.emit(obj)
  6592. self.inform.emit('[success] %s' %
  6593. _("Skew on X axis done."))
  6594. def on_skewy(self):
  6595. self.report_usage("on_skewy()")
  6596. obj_list = self.collection.get_selected()
  6597. xminlist = []
  6598. yminlist = []
  6599. if not obj_list:
  6600. self.inform.emit('[WARNING_NOTCL] %s' %
  6601. _("No object selected to Skew/Shear on Y axis."))
  6602. else:
  6603. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6604. min=-360, max=360, decimals=4,
  6605. init_val=float(self.defaults['tools_transform_skew_y']))
  6606. num, ok = skewybox.get_value()
  6607. if ok:
  6608. # first get a bounding box to fit all
  6609. for obj in obj_list:
  6610. xmin, ymin, xmax, ymax = obj.bounds()
  6611. xminlist.append(xmin)
  6612. yminlist.append(ymin)
  6613. # get the minimum x,y and maximum x,y for all objects selected
  6614. xminimal = min(xminlist)
  6615. yminimal = min(yminlist)
  6616. for obj in obj_list:
  6617. obj.skew(0, num, point=(xminimal, yminimal))
  6618. obj.plot()
  6619. self.object_changed.emit(obj)
  6620. self.inform.emit('[success] %s' %
  6621. _("Skew on Y axis done."))
  6622. def on_plots_updated(self):
  6623. """
  6624. Callback used to report when the plots have changed.
  6625. Adjust axes and zooms to fit.
  6626. :return: None
  6627. """
  6628. if self.is_legacy is False:
  6629. self.plotcanvas.update() # TODO: Need update canvas?
  6630. else:
  6631. self.plotcanvas.auto_adjust_axes()
  6632. self.on_zoom_fit(None)
  6633. self.collection.update_view()
  6634. # self.inform.emit(_("Plots updated ..."))
  6635. # TODO: Rework toolbar 'clear', 'replot' functions
  6636. def on_toolbar_replot(self):
  6637. """
  6638. Callback for toolbar button. Re-plots all objects.
  6639. :return: None
  6640. """
  6641. self.report_usage("on_toolbar_replot")
  6642. self.log.debug("on_toolbar_replot()")
  6643. try:
  6644. self.collection.get_active().read_form()
  6645. except AttributeError:
  6646. self.log.debug("on_toolbar_replot(): AttributeError")
  6647. pass
  6648. self.plot_all()
  6649. def on_row_activated(self, index):
  6650. if index.isValid():
  6651. if index.internalPointer().parent_item != self.collection.root_item:
  6652. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6653. self.collection.on_item_activated(index)
  6654. def on_row_selected(self, obj_name):
  6655. # this is a special string; when received it will make all entries unchecked
  6656. # it mean we clicked outside of the items and deselected all
  6657. if obj_name == 'none':
  6658. for act in self.ui.menuobjects.actions():
  6659. act.setChecked(False)
  6660. return
  6661. # get the name of the selected objects and add them to a list
  6662. name_list = list()
  6663. for obj in self.collection.get_selected():
  6664. name_list.append(obj.options['name'])
  6665. # set all actions as unchecked but the ones selected make them checked
  6666. for act in self.ui.menuobjects.actions():
  6667. act.setChecked(False)
  6668. if act.text() in name_list:
  6669. act.setChecked(True)
  6670. def on_collection_updated(self, obj, state, old_name):
  6671. """
  6672. Create a menu from the object loaded in the collection.
  6673. TODO: should use the collection model to do this
  6674. :param obj: object that was changd (added, deleted, renamed)
  6675. :param state: what was done with the objectCand be: added, deleted, delete_all, renamed
  6676. :param old_name: the old name of the object before the action that triggered this slot happened
  6677. :return: None
  6678. """
  6679. icon_files = {
  6680. "gerber": "share/flatcam_icon16.png",
  6681. "excellon": "share/drill16.png",
  6682. "cncjob": "share/cnc16.png",
  6683. "geometry": "share/geometry16.png",
  6684. "script": "share/script_new16.png",
  6685. "document": "share/notes16_1.png"
  6686. }
  6687. if state == 'append':
  6688. for act in self.ui.menuobjects.actions():
  6689. try:
  6690. act.triggered.disconnect()
  6691. except TypeError:
  6692. pass
  6693. self.ui.menuobjects.clear()
  6694. gerber_list = list()
  6695. exc_list = list()
  6696. cncjob_list = list()
  6697. geo_list = list()
  6698. script_list = list()
  6699. doc_list = list()
  6700. for name in self.collection.get_names():
  6701. obj_named = self.collection.get_by_name(name)
  6702. if obj_named.kind == 'gerber':
  6703. gerber_list.append(name)
  6704. elif obj_named.kind == 'excellon':
  6705. exc_list.append(name)
  6706. elif obj_named.kind == 'cncjob':
  6707. cncjob_list.append(name)
  6708. elif obj_named.kind == 'geometry':
  6709. geo_list.append(name)
  6710. elif obj_named.kind == 'script':
  6711. script_list.append(name)
  6712. elif obj_named.kind == 'document':
  6713. doc_list.append(name)
  6714. def add_act(o_name):
  6715. obj_for_icon = self.collection.get_by_name(o_name)
  6716. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6717. add_action.setCheckable(True)
  6718. add_action.setText(o_name)
  6719. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  6720. add_action.triggered.connect(
  6721. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  6722. self.collection.set_inactive(o_name))
  6723. self.ui.menuobjects.addAction(add_action)
  6724. for name in gerber_list:
  6725. add_act(name)
  6726. self.ui.menuobjects.addSeparator()
  6727. for name in exc_list:
  6728. add_act(name)
  6729. self.ui.menuobjects.addSeparator()
  6730. for name in cncjob_list:
  6731. add_act(name)
  6732. self.ui.menuobjects.addSeparator()
  6733. for name in geo_list:
  6734. add_act(name)
  6735. self.ui.menuobjects.addSeparator()
  6736. for name in script_list:
  6737. add_act(name)
  6738. self.ui.menuobjects.addSeparator()
  6739. for name in doc_list:
  6740. add_act(name)
  6741. self.ui.menuobjects.addSeparator()
  6742. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  6743. QtGui.QIcon('share/select_all.png'),
  6744. _('Select All')
  6745. )
  6746. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  6747. QtGui.QIcon('share/deselect_all32.png'),
  6748. _('Deselect All')
  6749. )
  6750. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  6751. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  6752. elif state == 'delete':
  6753. for act in self.ui.menuobjects.actions():
  6754. if act.text() == obj.options['name']:
  6755. try:
  6756. act.triggered.disconnect()
  6757. except TypeError:
  6758. pass
  6759. self.ui.menuobjects.removeAction(act)
  6760. break
  6761. elif state == 'rename':
  6762. for act in self.ui.menuobjects.actions():
  6763. if act.text() == old_name:
  6764. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6765. add_action.setText(obj.options['name'])
  6766. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  6767. add_action.triggered.connect(
  6768. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  6769. self.collection.set_inactive(obj.options['name']))
  6770. self.ui.menuobjects.insertAction(act, add_action)
  6771. try:
  6772. act.triggered.disconnect()
  6773. except TypeError:
  6774. pass
  6775. self.ui.menuobjects.removeAction(act)
  6776. break
  6777. elif state == 'delete_all':
  6778. for act in self.ui.menuobjects.actions():
  6779. try:
  6780. act.triggered.disconnect()
  6781. except TypeError:
  6782. pass
  6783. self.ui.menuobjects.clear()
  6784. self.ui.menuobjects.addSeparator()
  6785. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  6786. QtGui.QIcon('share/select_all.png'),
  6787. _('Select All')
  6788. )
  6789. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  6790. QtGui.QIcon('share/deselect_all32.png'),
  6791. _('Deselect All')
  6792. )
  6793. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  6794. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  6795. def on_objects_selection(self, on_off):
  6796. obj_list = self.collection.get_names()
  6797. if on_off is True:
  6798. self.collection.set_all_active()
  6799. for act in self.ui.menuobjects.actions():
  6800. try:
  6801. act.setChecked(True)
  6802. except Exception:
  6803. pass
  6804. if obj_list:
  6805. self.inform.emit('[selected] %s' % _("All objects are selected."))
  6806. else:
  6807. self.collection.set_all_inactive()
  6808. for act in self.ui.menuobjects.actions():
  6809. try:
  6810. act.setChecked(False)
  6811. except Exception:
  6812. pass
  6813. if obj_list:
  6814. self.inform.emit('%s' % _("Objects selection is cleared."))
  6815. else:
  6816. self.inform.emit('')
  6817. def grid_status(self):
  6818. if self.ui.grid_snap_btn.isChecked():
  6819. return True
  6820. else:
  6821. return False
  6822. def populate_cmenu_grids(self):
  6823. units = self.defaults['units'].lower()
  6824. self.ui.cmenu_gridmenu.clear()
  6825. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  6826. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  6827. grid_toggle.setCheckable(True)
  6828. if self.grid_status() == True:
  6829. grid_toggle.setChecked(True)
  6830. else:
  6831. grid_toggle.setChecked(False)
  6832. self.ui.cmenu_gridmenu.addSeparator()
  6833. for grid in sorted_list:
  6834. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  6835. action.triggered.connect(self.set_grid)
  6836. self.ui.cmenu_gridmenu.addSeparator()
  6837. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  6838. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  6839. grid_add.triggered.connect(self.on_grid_add)
  6840. grid_delete.triggered.connect(self.on_grid_delete)
  6841. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  6842. def set_grid(self):
  6843. self.ui.grid_gap_x_entry.setText(self.sender().text())
  6844. self.ui.grid_gap_y_entry.setText(self.sender().text())
  6845. def on_grid_add(self):
  6846. # ## Current application units in lower Case
  6847. units = self.defaults['units'].lower()
  6848. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  6849. text=_('Enter a Grid Value:'),
  6850. min=0.0000, max=99.9999, decimals=4)
  6851. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  6852. val, ok = grid_add_popup.get_value()
  6853. if ok:
  6854. if float(val) == 0:
  6855. self.inform.emit('[WARNING_NOTCL] %s' %
  6856. _("Please enter a grid value with non-zero value, in Float format."))
  6857. return
  6858. else:
  6859. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  6860. self.defaults["global_grid_context_menu"][str(units)].append(val)
  6861. self.inform.emit('[success] %s...' %
  6862. _("New Grid added"))
  6863. else:
  6864. self.inform.emit('[WARNING_NOTCL] %s...' %
  6865. _("Grid already exists"))
  6866. else:
  6867. self.inform.emit('[WARNING_NOTCL] %s...' %
  6868. _("Adding New Grid cancelled"))
  6869. def on_grid_delete(self):
  6870. # ## Current application units in lower Case
  6871. units = self.defaults['units'].lower()
  6872. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  6873. text='Enter a Grid Value:',
  6874. min=0.0000, max=99.9999, decimals=4)
  6875. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  6876. val, ok = grid_del_popup.get_value()
  6877. if ok:
  6878. if float(val) == 0:
  6879. self.inform.emit('[WARNING_NOTCL] %s' %
  6880. _("Please enter a grid value with non-zero value, in Float format."))
  6881. return
  6882. else:
  6883. try:
  6884. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  6885. except ValueError:
  6886. self.inform.emit('[ERROR_NOTCL]%s...' %
  6887. _(" Grid Value does not exist"))
  6888. return
  6889. self.inform.emit('[success] %s...' %
  6890. _("Grid Value deleted"))
  6891. else:
  6892. self.inform.emit('[WARNING_NOTCL] %s...' %
  6893. _("Delete Grid value cancelled"))
  6894. def on_shortcut_list(self):
  6895. self.report_usage("on_shortcut_list()")
  6896. # add the tab if it was closed
  6897. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  6898. # delete the absolute and relative position and messages in the infobar
  6899. self.ui.position_label.setText("")
  6900. self.ui.rel_position_label.setText("")
  6901. # Switch plot_area to preferences page
  6902. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  6903. # self.ui.show()
  6904. def on_select_tab(self, name):
  6905. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  6906. if self.ui.splitter.sizes()[0] == 0:
  6907. self.ui.splitter.setSizes([1, 1])
  6908. else:
  6909. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  6910. self.ui.splitter.setSizes([0, 1])
  6911. if name == 'project':
  6912. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6913. elif name == 'selected':
  6914. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6915. elif name == 'tool':
  6916. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  6917. def on_copy_name(self):
  6918. self.report_usage("on_copy_name()")
  6919. obj = self.collection.get_active()
  6920. try:
  6921. name = obj.options["name"]
  6922. except AttributeError:
  6923. log.debug("on_copy_name() --> No object selected to copy it's name")
  6924. self.inform.emit('[WARNING_NOTCL]%s' %
  6925. _(" No object selected to copy it's name"))
  6926. return
  6927. self.clipboard.setText(name)
  6928. self.inform.emit(_("Name copied on clipboard ..."))
  6929. def on_mouse_click_over_plot(self, event):
  6930. """
  6931. Default actions are:
  6932. :param event: Contains information about the event, like which button
  6933. was clicked, the pixel coordinates and the axes coordinates.
  6934. :return: None
  6935. """
  6936. self.pos = []
  6937. if self.is_legacy is False:
  6938. event_pos = event.pos
  6939. if self.defaults["global_pan_button"] == '2':
  6940. pan_button = 2
  6941. else:
  6942. pan_button = 3
  6943. # Set the mouse button for panning
  6944. self.plotcanvas.view.camera.pan_button_setting = pan_button
  6945. else:
  6946. event_pos = (event.xdata, event.ydata)
  6947. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6948. if self.defaults["global_pan_button"] == '2':
  6949. pan_button = 3
  6950. else:
  6951. pan_button = 2
  6952. # So it can receive key presses
  6953. self.plotcanvas.native.setFocus()
  6954. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6955. if self.grid_status() == True:
  6956. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  6957. else:
  6958. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  6959. try:
  6960. if event.button == 1:
  6961. # Reset here the relative coordinates so there is a new reference on the click position
  6962. if self.rel_point1 is None:
  6963. self.rel_point1 = self.pos
  6964. else:
  6965. self.rel_point2 = copy(self.rel_point1)
  6966. self.rel_point1 = self.pos
  6967. self.on_mouse_move_over_plot(event, origin_click=True)
  6968. except Exception as e:
  6969. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  6970. def on_mouse_double_click_over_plot(self, event):
  6971. if event.button == 1:
  6972. self.doubleclick = True
  6973. def on_mouse_move_over_plot(self, event, origin_click=None):
  6974. """
  6975. Callback for the mouse motion event over the plot.
  6976. :param event: Contains information about the event.
  6977. :param origin_click
  6978. :return: None
  6979. """
  6980. if self.is_legacy is False:
  6981. event_pos = event.pos
  6982. if self.defaults["global_pan_button"] == '2':
  6983. pan_button = 2
  6984. else:
  6985. pan_button = 3
  6986. self.event_is_dragging = event.is_dragging
  6987. else:
  6988. event_pos = (event.xdata, event.ydata)
  6989. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6990. if self.defaults["global_pan_button"] == '2':
  6991. pan_button = 3
  6992. else:
  6993. pan_button = 2
  6994. self.event_is_dragging = self.plotcanvas.is_dragging
  6995. # So it can receive key presses
  6996. self.plotcanvas.native.setFocus()
  6997. self.pos_jump = event_pos
  6998. self.ui.popMenu.mouse_is_panning = False
  6999. if not origin_click:
  7000. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  7001. if event.button == pan_button and self.event_is_dragging == 1:
  7002. self.ui.popMenu.mouse_is_panning = True
  7003. return
  7004. if self.rel_point1 is not None:
  7005. try: # May fail in case mouse not within axes
  7006. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7007. if self.grid_status() == True:
  7008. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  7009. # Update cursor
  7010. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  7011. symbol='++', edge_color=self.cursor_color_3D,
  7012. size=self.defaults["global_cursor_size"])
  7013. else:
  7014. pos = (pos_canvas[0], pos_canvas[1])
  7015. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  7016. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  7017. dx = pos[0] - float(self.rel_point1[0])
  7018. dy = pos[1] - float(self.rel_point1[1])
  7019. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  7020. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  7021. self.mouse = [pos[0], pos[1]]
  7022. # if the mouse is moved and the LMB is clicked then the action is a selection
  7023. if self.event_is_dragging == 1 and event.button == 1:
  7024. self.delete_selection_shape()
  7025. if dx < 0:
  7026. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  7027. face_color=self.defaults['global_alt_sel_fill'])
  7028. self.selection_type = False
  7029. elif dx > 0:
  7030. self.draw_moving_selection_shape(self.pos, pos)
  7031. self.selection_type = True
  7032. else:
  7033. self.selection_type = None
  7034. # hover effect - enabled in Preferences -> General -> GUI Settings
  7035. if self.defaults['global_hover']:
  7036. for obj in self.collection.get_list():
  7037. try:
  7038. # select the object(s) only if it is enabled (plotted)
  7039. if obj.options['plot']:
  7040. if obj not in self.collection.get_selected():
  7041. poly_obj = Polygon(
  7042. [(obj.options['xmin'], obj.options['ymin']),
  7043. (obj.options['xmax'], obj.options['ymin']),
  7044. (obj.options['xmax'], obj.options['ymax']),
  7045. (obj.options['xmin'], obj.options['ymax'])]
  7046. )
  7047. if Point(pos).within(poly_obj):
  7048. if obj.isHovering is False:
  7049. obj.isHovering = True
  7050. obj.notHovering = True
  7051. # create the selection box around the selected object
  7052. self.draw_hover_shape(obj, color='#d1e0e0FF')
  7053. else:
  7054. if obj.notHovering is True:
  7055. obj.notHovering = False
  7056. obj.isHovering = False
  7057. self.delete_hover_shape()
  7058. except Exception:
  7059. # the Exception here will happen if we try to select on screen and we have an
  7060. # newly (and empty) just created Geometry or Excellon object that do not have the
  7061. # xmin, xmax, ymin, ymax options.
  7062. # In this case poly_obj creation (see above) will fail
  7063. pass
  7064. except Exception:
  7065. self.ui.position_label.setText("")
  7066. self.ui.rel_position_label.setText("")
  7067. self.mouse = None
  7068. def on_mouse_click_release_over_plot(self, event):
  7069. """
  7070. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  7071. and has been registered in ''self.__init__()''.
  7072. :param event: contains information about the event.
  7073. :return:
  7074. """
  7075. if self.is_legacy is False:
  7076. event_pos = event.pos
  7077. right_button = 2
  7078. else:
  7079. event_pos = (event.xdata, event.ydata)
  7080. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7081. right_button = 3
  7082. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7083. if self.grid_status() == True:
  7084. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  7085. else:
  7086. pos = (pos_canvas[0], pos_canvas[1])
  7087. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  7088. # canvas menu
  7089. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  7090. self.cursor = QtGui.QCursor()
  7091. self.populate_cmenu_grids()
  7092. self.ui.popMenu.popup(self.cursor.pos())
  7093. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  7094. # selection and then select a type of selection ("enclosing" or "touching")
  7095. if event.button == 1: # left click
  7096. modifiers = QtWidgets.QApplication.keyboardModifiers()
  7097. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  7098. if modifiers == QtCore.Qt.ShiftModifier:
  7099. # do not auto open the Project Tab
  7100. self.click_noproject = True
  7101. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  7102. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  7103. return
  7104. if self.doubleclick is True:
  7105. self.doubleclick = False
  7106. if self.collection.get_selected():
  7107. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  7108. if self.ui.splitter.sizes()[0] == 0:
  7109. self.ui.splitter.setSizes([1, 1])
  7110. try:
  7111. # delete the selection shape(S) as it may be in the way
  7112. self.delete_selection_shape()
  7113. self.delete_hover_shape()
  7114. except Exception as e:
  7115. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  7116. return
  7117. else:
  7118. if self.selection_type is not None:
  7119. try:
  7120. self.selection_area_handler(self.pos, pos, self.selection_type)
  7121. self.selection_type = None
  7122. except Exception as e:
  7123. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  7124. return
  7125. else:
  7126. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  7127. if key_modifier == QtCore.Qt.ShiftModifier:
  7128. mod_key = 'Shift'
  7129. elif key_modifier == QtCore.Qt.ControlModifier:
  7130. mod_key = 'Control'
  7131. else:
  7132. mod_key = None
  7133. try:
  7134. if mod_key == self.defaults["global_mselect_key"]:
  7135. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  7136. # deselect, and if it's not selected then it will be selected
  7137. # If there is no active command (self.command_active is None) then we check if we clicked
  7138. # on a object by checking the bounding limits against mouse click position
  7139. if self.command_active is None:
  7140. self.select_objects(key='CTRL')
  7141. self.delete_hover_shape()
  7142. else:
  7143. # If there is no active command (self.command_active is None) then we check if we clicked
  7144. # on a object by checking the bounding limits against mouse click position
  7145. if self.command_active is None:
  7146. self.select_objects()
  7147. self.delete_hover_shape()
  7148. except Exception as e:
  7149. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  7150. return
  7151. def selection_area_handler(self, start_pos, end_pos, sel_type):
  7152. """
  7153. :param start_pos: mouse position when the selection LMB click was done
  7154. :param end_pos: mouse position when the left mouse button is released
  7155. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  7156. :return:
  7157. """
  7158. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  7159. # delete previous selection shape
  7160. self.delete_selection_shape()
  7161. # make all objects inactive
  7162. self.collection.set_all_inactive()
  7163. for obj in self.collection.get_list():
  7164. try:
  7165. # select the object(s) only if it is enabled (plotted)
  7166. if obj.options['plot']:
  7167. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  7168. (obj.options['xmax'], obj.options['ymin']),
  7169. (obj.options['xmax'], obj.options['ymax']),
  7170. (obj.options['xmin'], obj.options['ymax'])])
  7171. if sel_type is True:
  7172. if poly_obj.within(poly_selection):
  7173. # create the selection box around the selected object
  7174. if self.defaults['global_selection_shape'] is True:
  7175. self.draw_selection_shape(obj)
  7176. self.collection.set_active(obj.options['name'])
  7177. else:
  7178. if poly_selection.intersects(poly_obj):
  7179. # create the selection box around the selected object
  7180. if self.defaults['global_selection_shape'] is True:
  7181. self.draw_selection_shape(obj)
  7182. self.collection.set_active(obj.options['name'])
  7183. except Exception as e:
  7184. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  7185. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  7186. # In this case poly_obj creation (see above) will fail
  7187. log.debug("App.selection_area_handler() --> %s" % str(e))
  7188. def select_objects(self, key=None):
  7189. """
  7190. Will select objects clicked on canvas
  7191. :param key: for future use in cumulative selection
  7192. :return:
  7193. """
  7194. # list where we store the overlapped objects under our mouse left click position
  7195. objects_under_the_click_list = []
  7196. # Populate the list with the overlapped objects on the click position
  7197. curr_x, curr_y = self.pos
  7198. for obj in self.all_objects_list:
  7199. # FlatCAMScript and FlatCAMDocument objects can't be selected
  7200. if isinstance(obj, FlatCAMScript) or isinstance(obj, FlatCAMDocument):
  7201. continue
  7202. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  7203. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  7204. if obj.options['name'] not in objects_under_the_click_list:
  7205. if obj.options['plot']:
  7206. # add objects to the objects_under_the_click list only if the object is plotted
  7207. # (active and not disabled)
  7208. objects_under_the_click_list.append(obj.options['name'])
  7209. try:
  7210. if objects_under_the_click_list:
  7211. curr_sel_obj = self.collection.get_active()
  7212. # case when there is only an object under the click and we toggle it
  7213. if len(objects_under_the_click_list) == 1:
  7214. if curr_sel_obj is None:
  7215. self.collection.set_active(objects_under_the_click_list[0])
  7216. curr_sel_obj = self.collection.get_active()
  7217. # create the selection box around the selected object
  7218. if self.defaults['global_selection_shape'] is True:
  7219. self.draw_selection_shape(curr_sel_obj)
  7220. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  7221. self.on_objects_selection(False)
  7222. self.delete_selection_shape()
  7223. self.collection.set_active(objects_under_the_click_list[0])
  7224. curr_sel_obj = self.collection.get_active()
  7225. # create the selection box around the selected object
  7226. if self.defaults['global_selection_shape'] is True:
  7227. self.draw_selection_shape(curr_sel_obj)
  7228. self.selected_message(curr_sel_obj=curr_sel_obj)
  7229. else:
  7230. self.on_objects_selection(False)
  7231. self.delete_selection_shape()
  7232. if self.call_source != 'app':
  7233. self.call_source = 'app'
  7234. self.selected_message(curr_sel_obj=curr_sel_obj)
  7235. else:
  7236. # If there is no selected object
  7237. # make active the first element of the overlapped objects list
  7238. if self.collection.get_active() is None:
  7239. self.collection.set_active(objects_under_the_click_list[0])
  7240. name_sel_obj = self.collection.get_active().options['name']
  7241. # In case that there is a selected object but it is not in the overlapped object list
  7242. # make that object inactive and activate the first element in the overlapped object list
  7243. if name_sel_obj not in objects_under_the_click_list:
  7244. self.collection.set_inactive(name_sel_obj)
  7245. name_sel_obj = objects_under_the_click_list[0]
  7246. self.collection.set_active(name_sel_obj)
  7247. else:
  7248. sel_idx = objects_under_the_click_list.index(name_sel_obj)
  7249. self.collection.set_all_inactive()
  7250. self.collection.set_active(objects_under_the_click_list[(sel_idx + 1) %
  7251. len(objects_under_the_click_list)])
  7252. curr_sel_obj = self.collection.get_active()
  7253. # delete the possible selection box around a possible selected object
  7254. self.delete_selection_shape()
  7255. # create the selection box around the selected object
  7256. if self.defaults['global_selection_shape'] is True:
  7257. self.draw_selection_shape(curr_sel_obj)
  7258. self.selected_message(curr_sel_obj=curr_sel_obj)
  7259. else:
  7260. # deselect everything
  7261. self.on_objects_selection(False)
  7262. # delete the possible selection box around a possible selected object
  7263. self.delete_selection_shape()
  7264. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  7265. # only when working on App
  7266. if self.call_source == 'app':
  7267. if self.click_noproject is False:
  7268. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7269. else:
  7270. # restore auto open the Project Tab
  7271. self.click_noproject = False
  7272. # delete any text in the status bar, implicitly the last object name that was selected
  7273. # self.inform.emit("")
  7274. else:
  7275. self.call_source = 'app'
  7276. except Exception as e:
  7277. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  7278. def selected_message(self, curr_sel_obj):
  7279. if curr_sel_obj:
  7280. if curr_sel_obj.kind == 'gerber':
  7281. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7282. color='green', name=str(curr_sel_obj.options['name'])))
  7283. elif curr_sel_obj.kind == 'excellon':
  7284. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7285. color='brown', name=str(curr_sel_obj.options['name'])))
  7286. elif curr_sel_obj.kind == 'cncjob':
  7287. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7288. color='blue', name=str(curr_sel_obj.options['name'])))
  7289. elif curr_sel_obj.kind == 'geometry':
  7290. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  7291. color='red', name=str(curr_sel_obj.options['name'])))
  7292. def delete_hover_shape(self):
  7293. self.hover_shapes.clear()
  7294. self.hover_shapes.redraw()
  7295. def draw_hover_shape(self, sel_obj, color=None):
  7296. """
  7297. :param sel_obj: the object for which the hover shape must be drawn
  7298. :return:
  7299. """
  7300. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7301. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7302. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7303. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7304. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  7305. if self.defaults['units'].upper() == 'MM':
  7306. hover_rect = hover_rect.buffer(-0.1)
  7307. hover_rect = hover_rect.buffer(0.2)
  7308. else:
  7309. hover_rect = hover_rect.buffer(-0.00393)
  7310. hover_rect = hover_rect.buffer(0.00787)
  7311. # if color:
  7312. # face = Color(color)
  7313. # face.alpha = 0.2
  7314. # outline = Color(color, alpha=0.8)
  7315. # else:
  7316. # face = Color(self.defaults['global_sel_fill'])
  7317. # face.alpha = 0.2
  7318. # outline = self.defaults['global_sel_line']
  7319. if color:
  7320. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7321. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7322. else:
  7323. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7324. outline = self.defaults['global_sel_line']
  7325. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  7326. if self.is_legacy is True:
  7327. self.hover_shapes.redraw()
  7328. def delete_selection_shape(self):
  7329. self.move_tool.sel_shapes.clear()
  7330. self.move_tool.sel_shapes.redraw()
  7331. def draw_selection_shape(self, sel_obj, color=None):
  7332. """
  7333. :param sel_obj: the object for which the selection shape must be drawn
  7334. :return:
  7335. """
  7336. if sel_obj is None:
  7337. return
  7338. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7339. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7340. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7341. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7342. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7343. if self.defaults['units'].upper() == 'MM':
  7344. sel_rect = sel_rect.buffer(-0.1)
  7345. sel_rect = sel_rect.buffer(0.2)
  7346. else:
  7347. sel_rect = sel_rect.buffer(-0.00393)
  7348. sel_rect = sel_rect.buffer(0.00787)
  7349. if color:
  7350. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7351. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7352. else:
  7353. if self.is_legacy is False:
  7354. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7355. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  7356. else:
  7357. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  7358. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  7359. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  7360. color=outline,
  7361. face_color=face,
  7362. update=True,
  7363. layer=0,
  7364. tolerance=None))
  7365. if self.is_legacy is True:
  7366. self.move_tool.sel_shapes.redraw()
  7367. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  7368. """
  7369. :param old_coords: old coordinates
  7370. :param coords: new coordinates
  7371. :return:
  7372. """
  7373. if 'color' in kwargs:
  7374. color = kwargs['color']
  7375. else:
  7376. color = self.defaults['global_sel_line']
  7377. if 'face_color' in kwargs:
  7378. face_color = kwargs['face_color']
  7379. else:
  7380. face_color = self.defaults['global_sel_fill']
  7381. if 'face_alpha' in kwargs:
  7382. face_alpha = kwargs['face_alpha']
  7383. else:
  7384. face_alpha = 0.3
  7385. x0, y0 = old_coords
  7386. x1, y1 = coords
  7387. pt1 = (x0, y0)
  7388. pt2 = (x1, y0)
  7389. pt3 = (x1, y1)
  7390. pt4 = (x0, y1)
  7391. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7392. # color_t = Color(face_color)
  7393. # color_t.alpha = face_alpha
  7394. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  7395. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  7396. layer=0, tolerance=None)
  7397. if self.is_legacy is True:
  7398. self.move_tool.sel_shapes.redraw()
  7399. def on_file_new_click(self):
  7400. if self.collection.get_list() and self.should_we_save:
  7401. msgbox = QtWidgets.QMessageBox()
  7402. # msgbox.setText("<B>Save changes ...</B>")
  7403. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7404. "Creating a New project will delete them.\n"
  7405. "Do you want to Save the project?"))
  7406. msgbox.setWindowTitle(_("Save changes"))
  7407. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  7408. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7409. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7410. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7411. msgbox.setDefaultButton(bt_yes)
  7412. msgbox.exec_()
  7413. response = msgbox.clickedButton()
  7414. if response == bt_yes:
  7415. self.on_file_saveprojectas()
  7416. elif response == bt_cancel:
  7417. return
  7418. elif response == bt_no:
  7419. self.on_file_new()
  7420. else:
  7421. self.on_file_new()
  7422. self.inform.emit('[success] %s...' %
  7423. _("New Project created"))
  7424. def on_file_new(self, cli=None):
  7425. """
  7426. Callback for menu item File -> New. Returns the application to its
  7427. startup state. This method is thread-safe.
  7428. :return: None
  7429. """
  7430. self.report_usage("on_file_new")
  7431. # Remove everything from memory
  7432. App.log.debug("on_file_new()")
  7433. if self.call_source != 'app':
  7434. self.editor2object(cleanup=True)
  7435. # ## EDITOR section
  7436. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  7437. self.exc_editor = FlatCAMExcEditor(self)
  7438. self.grb_editor = FlatCAMGrbEditor(self)
  7439. # Clear pool
  7440. self.clear_pool()
  7441. for obj in self.collection.get_list():
  7442. # delete shapes left drawn from mark shape_collections, if any
  7443. if isinstance(obj, FlatCAMGerber):
  7444. try:
  7445. obj.mark_shapes.enabled = False
  7446. obj.mark_shapes.clear(update=True)
  7447. except AttributeError:
  7448. pass
  7449. # also delete annotation shapes, if any
  7450. elif isinstance(obj, FlatCAMCNCjob):
  7451. try:
  7452. obj.annotation.enabled = False
  7453. obj.annotation.clear(update=True)
  7454. except AttributeError:
  7455. pass
  7456. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7457. self.init_tcl()
  7458. self.delete_selection_shape()
  7459. self.collection.delete_all()
  7460. self.setup_component_editor()
  7461. # Clear project filename
  7462. self.project_filename = None
  7463. # Load the application defaults
  7464. self.load_defaults(filename='current_defaults')
  7465. # Re-fresh project options
  7466. self.on_options_app2project()
  7467. # Init Tools
  7468. self.init_tools()
  7469. if cli is None:
  7470. # Close any Tabs opened in the Plot Tab Area section
  7471. for index in range(self.ui.plot_tab_area.count()):
  7472. self.ui.plot_tab_area.closeTab(index)
  7473. # for whatever reason previous command does not close the last tab so I do it manually
  7474. self.ui.plot_tab_area.closeTab(0)
  7475. # # And then add again the Plot Area
  7476. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  7477. self.ui.plot_tab_area.protectTab(0)
  7478. # take the focus of the Notebook on Project Tab.
  7479. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7480. self.set_ui_title(name=_("New Project - Not saved"))
  7481. def obj_properties(self):
  7482. """
  7483. Will launch the object Properties Tool
  7484. :return:
  7485. """
  7486. self.report_usage("obj_properties()")
  7487. self.properties_tool.run(toggle=False)
  7488. def on_project_context_save(self):
  7489. """
  7490. Wrapper, will save the object function of it's type
  7491. :return:
  7492. """
  7493. obj = self.collection.get_active()
  7494. if type(obj) == FlatCAMGeometry:
  7495. self.on_file_exportdxf()
  7496. elif type(obj) == FlatCAMExcellon:
  7497. self.on_file_saveexcellon()
  7498. elif type(obj) == FlatCAMCNCjob:
  7499. obj.on_exportgcode_button_click()
  7500. elif type(obj) == FlatCAMGerber:
  7501. self.on_file_savegerber()
  7502. elif type(obj) == FlatCAMScript:
  7503. self.on_file_savescript()
  7504. elif type(obj) == FlatCAMDocument:
  7505. self.on_file_savedocument()
  7506. def obj_move(self):
  7507. self.report_usage("obj_move()")
  7508. self.move_tool.run(toggle=False)
  7509. def on_fileopengerber(self, signal: bool = None, name=None):
  7510. """
  7511. File menu callback for opening a Gerber.
  7512. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7513. :return: None
  7514. """
  7515. self.report_usage("on_fileopengerber")
  7516. App.log.debug("on_fileopengerber()")
  7517. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  7518. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  7519. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  7520. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  7521. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  7522. "*.mil);;" \
  7523. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  7524. "Allegro Files (*.art);;" \
  7525. "Mentor Files (*.pho *.gdo);;" \
  7526. "All Files (*.*)"
  7527. if name is None:
  7528. try:
  7529. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  7530. directory=self.get_last_folder(),
  7531. filter=_filter_)
  7532. except TypeError:
  7533. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  7534. filenames = [str(filename) for filename in filenames]
  7535. else:
  7536. filenames = [name]
  7537. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7538. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7539. _("Opening Gerber file.")),
  7540. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7541. color=QtGui.QColor("gray"))
  7542. if len(filenames) == 0:
  7543. self.inform.emit('[WARNING_NOTCL] %s' %
  7544. _("Open Gerber cancelled."))
  7545. else:
  7546. for filename in filenames:
  7547. if filename != '':
  7548. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  7549. def on_fileopenexcellon(self, signal: bool = None, name=None):
  7550. """
  7551. File menu callback for opening an Excellon file.
  7552. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7553. :return: None
  7554. """
  7555. self.report_usage("on_fileopenexcellon")
  7556. App.log.debug("on_fileopenexcellon()")
  7557. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  7558. "All Files (*.*)"
  7559. if name is None:
  7560. try:
  7561. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  7562. directory=self.get_last_folder(),
  7563. filter=_filter_)
  7564. except TypeError:
  7565. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  7566. filenames = [str(filename) for filename in filenames]
  7567. else:
  7568. filenames = [str(name)]
  7569. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7570. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7571. _("Opening Excellon file.")),
  7572. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7573. color=QtGui.QColor("gray"))
  7574. if len(filenames) == 0:
  7575. self.inform.emit('[WARNING_NOTCL]%s' %
  7576. _(" Open Excellon cancelled."))
  7577. else:
  7578. for filename in filenames:
  7579. if filename != '':
  7580. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  7581. def on_fileopengcode(self, signal: bool = None, name=None):
  7582. """
  7583. File menu call back for opening gcode.
  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_fileopengcode")
  7588. App.log.debug("on_fileopengcode()")
  7589. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  7590. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  7591. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  7592. "All Files (*.*)"
  7593. if name is None:
  7594. try:
  7595. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  7596. directory=self.get_last_folder(),
  7597. filter=_filter_)
  7598. except TypeError:
  7599. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  7600. filenames = [str(filename) for filename in filenames]
  7601. else:
  7602. filenames = [name]
  7603. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7604. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7605. _("Opening G-Code file.")),
  7606. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7607. color=QtGui.QColor("gray"))
  7608. if len(filenames) == 0:
  7609. self.inform.emit('[WARNING_NOTCL] %s' %
  7610. _("Open G-Code cancelled."))
  7611. else:
  7612. for filename in filenames:
  7613. if filename != '':
  7614. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  7615. def on_file_openproject(self, signal: bool = None):
  7616. """
  7617. File menu callback for opening a project.
  7618. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7619. :return: None
  7620. """
  7621. self.report_usage("on_file_openproject")
  7622. App.log.debug("on_file_openproject()")
  7623. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  7624. try:
  7625. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  7626. directory=self.get_last_folder(), filter=_filter_)
  7627. except TypeError:
  7628. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  7629. # The Qt methods above will return a QString which can cause problems later.
  7630. # So far json.dump() will fail to serialize it.
  7631. # TODO: Improve the serialization methods and remove this fix.
  7632. filename = str(filename)
  7633. if filename == "":
  7634. self.inform.emit('[WARNING_NOTCL] %s' %
  7635. _("Open Project cancelled."))
  7636. else:
  7637. # self.worker_task.emit({'fcn': self.open_project,
  7638. # 'params': [filename]})
  7639. # The above was failing because open_project() is not
  7640. # thread safe. The new_project()
  7641. self.open_project(filename)
  7642. def on_file_openconfig(self, signal: bool = None):
  7643. """
  7644. File menu callback for opening a config file.
  7645. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7646. :return: None
  7647. """
  7648. self.report_usage("on_file_openconfig")
  7649. App.log.debug("on_file_openconfig()")
  7650. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  7651. try:
  7652. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7653. directory=self.data_path, filter=_filter_)
  7654. except TypeError:
  7655. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7656. filter=_filter_)
  7657. if filename == "":
  7658. self.inform.emit('[WARNING_NOTCL] %s' %
  7659. _("Open Config cancelled."))
  7660. else:
  7661. self.open_config_file(filename)
  7662. def on_file_exportsvg(self):
  7663. """
  7664. Callback for menu item File->Export SVG.
  7665. :return: None
  7666. """
  7667. self.report_usage("on_file_exportsvg")
  7668. App.log.debug("on_file_exportsvg()")
  7669. obj = self.collection.get_active()
  7670. if obj is None:
  7671. self.inform.emit('[WARNING_NOTCL] %s' %
  7672. _("No object selected."))
  7673. msg = _("Please Select a Geometry object to export")
  7674. msgbox = QtWidgets.QMessageBox()
  7675. msgbox.setInformativeText(msg)
  7676. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7677. msgbox.setDefaultButton(bt_ok)
  7678. msgbox.exec_()
  7679. return
  7680. # Check for more compatible types and add as required
  7681. if (not isinstance(obj, FlatCAMGeometry)
  7682. and not isinstance(obj, FlatCAMGerber)
  7683. and not isinstance(obj, FlatCAMCNCjob)
  7684. and not isinstance(obj, FlatCAMExcellon)):
  7685. msg = '[ERROR_NOTCL] %s' % \
  7686. _("Only Geometry, Gerber and CNCJob objects can be used.")
  7687. msgbox = QtWidgets.QMessageBox()
  7688. msgbox.setInformativeText(msg)
  7689. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7690. msgbox.setDefaultButton(bt_ok)
  7691. msgbox.exec_()
  7692. return
  7693. name = obj.options["name"]
  7694. _filter = "SVG File (*.svg);;All Files (*.*)"
  7695. try:
  7696. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7697. caption=_("Export SVG"),
  7698. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  7699. filter=_filter)
  7700. except TypeError:
  7701. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  7702. filename = str(filename)
  7703. if filename == "":
  7704. self.inform.emit('[WARNING_NOTCL]%s' %
  7705. _(" Export SVG cancelled."))
  7706. return
  7707. else:
  7708. self.export_svg(name, filename)
  7709. if self.defaults["global_open_style"] is False:
  7710. self.file_opened.emit("SVG", filename)
  7711. self.file_saved.emit("SVG", filename)
  7712. def on_file_exportpng(self):
  7713. self.report_usage("on_file_exportpng")
  7714. App.log.debug("on_file_exportpng()")
  7715. self.date = str(datetime.today()).rpartition('.')[0]
  7716. self.date = ''.join(c for c in self.date if c not in ':-')
  7717. self.date = self.date.replace(' ', '_')
  7718. if self.is_legacy is False:
  7719. image = _screenshot()
  7720. data = np.asarray(image)
  7721. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  7722. self.inform.emit('[[WARNING_NOTCL]] %s' %
  7723. _('Data must be a 3D array with last dimension 3 or 4'))
  7724. return
  7725. filter_ = "PNG File (*.png);;All Files (*.*)"
  7726. try:
  7727. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7728. caption=_("Export PNG Image"),
  7729. directory=self.get_last_save_folder() + '/png_' + self.date,
  7730. filter=filter_)
  7731. except TypeError:
  7732. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  7733. filename = str(filename)
  7734. if filename == "":
  7735. self.inform.emit(_("Export PNG cancelled."))
  7736. return
  7737. else:
  7738. if self.is_legacy is False:
  7739. write_png(filename, data)
  7740. else:
  7741. self.plotcanvas.figure.savefig(filename)
  7742. if self.defaults["global_open_style"] is False:
  7743. self.file_opened.emit("png", filename)
  7744. self.file_saved.emit("png", filename)
  7745. def on_file_savegerber(self):
  7746. """
  7747. Callback for menu item in Project context menu.
  7748. :return: None
  7749. """
  7750. self.report_usage("on_file_savegerber")
  7751. App.log.debug("on_file_savegerber()")
  7752. obj = self.collection.get_active()
  7753. if obj is None:
  7754. self.inform.emit('[WARNING_NOTCL] %s' %
  7755. _("No object selected. Please select an Gerber object to export."))
  7756. return
  7757. # Check for more compatible types and add as required
  7758. if not isinstance(obj, FlatCAMGerber):
  7759. self.inform.emit('[ERROR_NOTCL] %s' %
  7760. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7761. return
  7762. name = self.collection.get_active().options["name"]
  7763. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  7764. try:
  7765. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7766. caption="Save Gerber source file",
  7767. directory=self.get_last_save_folder() + '/' + name,
  7768. filter=_filter)
  7769. except TypeError:
  7770. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  7771. filename = str(filename)
  7772. if filename == "":
  7773. self.inform.emit('[WARNING_NOTCL] %s' %
  7774. _("Save Gerber source file cancelled."))
  7775. return
  7776. else:
  7777. self.save_source_file(name, filename)
  7778. if self.defaults["global_open_style"] is False:
  7779. self.file_opened.emit("Gerber", filename)
  7780. self.file_saved.emit("Gerber", filename)
  7781. def on_file_savescript(self):
  7782. """
  7783. Callback for menu item in Project context menu.
  7784. :return: None
  7785. """
  7786. self.report_usage("on_file_savescript")
  7787. App.log.debug("on_file_savescript()")
  7788. obj = self.collection.get_active()
  7789. if obj is None:
  7790. self.inform.emit('[WARNING_NOTCL] %s' %
  7791. _("No object selected. Please select an Script object to export."))
  7792. return
  7793. # Check for more compatible types and add as required
  7794. if not isinstance(obj, FlatCAMScript):
  7795. self.inform.emit('[ERROR_NOTCL] %s' %
  7796. _("Failed. Only Script objects can be saved as TCL Script files..."))
  7797. return
  7798. name = self.collection.get_active().options["name"]
  7799. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  7800. try:
  7801. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7802. caption="Save Script source file",
  7803. directory=self.get_last_save_folder() + '/' + name,
  7804. filter=_filter)
  7805. except TypeError:
  7806. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Script source file"), filter=_filter)
  7807. filename = str(filename)
  7808. if filename == "":
  7809. self.inform.emit('[WARNING_NOTCL] %s' %
  7810. _("Save Script source file cancelled."))
  7811. return
  7812. else:
  7813. self.save_source_file(name, filename)
  7814. if self.defaults["global_open_style"] is False:
  7815. self.file_opened.emit("Script", filename)
  7816. self.file_saved.emit("Script", filename)
  7817. def on_file_savedocument(self):
  7818. """
  7819. Callback for menu item in Project context menu.
  7820. :return: None
  7821. """
  7822. self.report_usage("on_file_savedocument")
  7823. App.log.debug("on_file_savedocument()")
  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 Document object to export."))
  7828. return
  7829. # Check for more compatible types and add as required
  7830. if not isinstance(obj, FlatCAMScript):
  7831. self.inform.emit('[ERROR_NOTCL] %s' %
  7832. _("Failed. Only Document objects can be saved as Document files..."))
  7833. return
  7834. name = self.collection.get_active().options["name"]
  7835. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  7836. try:
  7837. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7838. caption="Save Document source file",
  7839. directory=self.get_last_save_folder() + '/' + name,
  7840. filter=_filter)
  7841. except TypeError:
  7842. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Document source file"), filter=_filter)
  7843. filename = str(filename)
  7844. if filename == "":
  7845. self.inform.emit('[WARNING_NOTCL] %s' %
  7846. _("Save Document 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("Document", filename)
  7852. self.file_saved.emit("Document", filename)
  7853. def on_file_saveexcellon(self):
  7854. """
  7855. Callback for menu item in project context menu.
  7856. :return: None
  7857. """
  7858. self.report_usage("on_file_saveexcellon")
  7859. App.log.debug("on_file_saveexcellon()")
  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 Excellon object to export."))
  7864. return
  7865. # Check for more compatible types and add as required
  7866. if not isinstance(obj, FlatCAMExcellon):
  7867. self.inform.emit('[ERROR_NOTCL] %s' %
  7868. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7869. return
  7870. name = self.collection.get_active().options["name"]
  7871. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7872. try:
  7873. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7874. caption=_("Save Excellon source file"),
  7875. directory=self.get_last_save_folder() + '/' + name,
  7876. filter=_filter)
  7877. except TypeError:
  7878. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  7879. filename = str(filename)
  7880. if filename == "":
  7881. self.inform.emit('[WARNING_NOTCL] %s' %
  7882. _("Saving Excellon 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("Excellon", filename)
  7888. self.file_saved.emit("Excellon", filename)
  7889. def on_file_exportexcellon(self):
  7890. """
  7891. Callback for menu item File->Export->Excellon.
  7892. :return: None
  7893. """
  7894. self.report_usage("on_file_exportexcellon")
  7895. App.log.debug("on_file_exportexcellon()")
  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 Excellon object to export."))
  7900. return
  7901. # Check for more compatible types and add as required
  7902. if not isinstance(obj, FlatCAMExcellon):
  7903. self.inform.emit('[ERROR_NOTCL] %s' %
  7904. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7905. return
  7906. name = self.collection.get_active().options["name"]
  7907. _filter = self.defaults["excellon_save_filters"]
  7908. try:
  7909. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7910. caption=_("Export Excellon"),
  7911. directory=self.get_last_save_folder() + '/' + name,
  7912. filter=_filter)
  7913. except TypeError:
  7914. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  7915. filename = str(filename)
  7916. if filename == "":
  7917. self.inform.emit('[WARNING_NOTCL] %s' %
  7918. _("Export Excellon cancelled."))
  7919. return
  7920. else:
  7921. used_extension = filename.rpartition('.')[2]
  7922. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  7923. self.export_excellon(name, filename)
  7924. if self.defaults["global_open_style"] is False:
  7925. self.file_opened.emit("Excellon", filename)
  7926. self.file_saved.emit("Excellon", filename)
  7927. def on_file_exportgerber(self):
  7928. """
  7929. Callback for menu item File->Export->Gerber.
  7930. :return: None
  7931. """
  7932. self.report_usage("on_file_exportgerber")
  7933. App.log.debug("on_file_exportgerber()")
  7934. obj = self.collection.get_active()
  7935. if obj is None:
  7936. self.inform.emit('[WARNING_NOTCL] %s' %
  7937. _("No object selected. Please Select an Gerber object to export."))
  7938. return
  7939. # Check for more compatible types and add as required
  7940. if not isinstance(obj, FlatCAMGerber):
  7941. self.inform.emit('[ERROR_NOTCL] %s' %
  7942. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7943. return
  7944. name = self.collection.get_active().options["name"]
  7945. _filter_ = self.defaults['gerber_save_filters']
  7946. try:
  7947. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7948. caption=_("Export Gerber"),
  7949. directory=self.get_last_save_folder() + '/' + name,
  7950. filter=_filter_)
  7951. except TypeError:
  7952. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  7953. filename = str(filename)
  7954. if filename == "":
  7955. self.inform.emit('[WARNING_NOTCL] %s' %
  7956. _("Export Gerber cancelled."))
  7957. return
  7958. else:
  7959. used_extension = filename.rpartition('.')[2]
  7960. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  7961. self.export_gerber(name, filename)
  7962. if self.defaults["global_open_style"] is False:
  7963. self.file_opened.emit("Gerber", filename)
  7964. self.file_saved.emit("Gerber", filename)
  7965. def on_file_exportdxf(self):
  7966. """
  7967. Callback for menu item File->Export DXF.
  7968. :return: None
  7969. """
  7970. self.report_usage("on_file_exportdxf")
  7971. App.log.debug("on_file_exportdxf()")
  7972. obj = self.collection.get_active()
  7973. if obj is None:
  7974. self.inform.emit('[WARNING_NOTCL] %s' %
  7975. _("No object selected."))
  7976. msg = _("Please Select a Geometry object to export")
  7977. msgbox = QtWidgets.QMessageBox()
  7978. msgbox.setInformativeText(msg)
  7979. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7980. msgbox.setDefaultButton(bt_ok)
  7981. msgbox.exec_()
  7982. return
  7983. # Check for more compatible types and add as required
  7984. if not isinstance(obj, FlatCAMGeometry):
  7985. msg = '[ERROR_NOTCL] %s' % \
  7986. _("Only Geometry objects can be used.")
  7987. msgbox = QtWidgets.QMessageBox()
  7988. msgbox.setInformativeText(msg)
  7989. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7990. msgbox.setDefaultButton(bt_ok)
  7991. msgbox.exec_()
  7992. return
  7993. name = self.collection.get_active().options["name"]
  7994. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7995. try:
  7996. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7997. caption=_("Export DXF"),
  7998. directory=self.get_last_save_folder() + '/' + name,
  7999. filter=_filter_)
  8000. except TypeError:
  8001. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  8002. filter=_filter_)
  8003. filename = str(filename)
  8004. if filename == "":
  8005. self.inform.emit('[WARNING_NOTCL] %s' %
  8006. _("Export DXF cancelled."))
  8007. return
  8008. else:
  8009. self.export_dxf(name, filename)
  8010. if self.defaults["global_open_style"] is False:
  8011. self.file_opened.emit("DXF", filename)
  8012. self.file_saved.emit("DXF", filename)
  8013. def on_file_importsvg(self, type_of_obj):
  8014. """
  8015. Callback for menu item File->Import SVG.
  8016. :param type_of_obj: to import the SVG as Geometry or as Gerber
  8017. :type type_of_obj: str
  8018. :return: None
  8019. """
  8020. self.report_usage("on_file_importsvg")
  8021. App.log.debug("on_file_importsvg()")
  8022. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  8023. try:
  8024. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  8025. directory=self.get_last_folder(), filter=_filter_)
  8026. except TypeError:
  8027. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  8028. filter=_filter_)
  8029. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  8030. type_of_obj = "geometry"
  8031. filenames = [str(filename) for filename in filenames]
  8032. if len(filenames) == 0:
  8033. self.inform.emit('[WARNING_NOTCL] %s' %
  8034. _("Open SVG cancelled."))
  8035. else:
  8036. for filename in filenames:
  8037. if filename != '':
  8038. self.worker_task.emit({'fcn': self.import_svg,
  8039. 'params': [filename, type_of_obj]})
  8040. def on_file_importdxf(self, type_of_obj):
  8041. """
  8042. Callback for menu item File->Import DXF.
  8043. :param type_of_obj: to import the DXF as Geometry or as Gerber
  8044. :type type_of_obj: str
  8045. :return: None
  8046. """
  8047. self.report_usage("on_file_importdxf")
  8048. App.log.debug("on_file_importdxf()")
  8049. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  8050. try:
  8051. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  8052. directory=self.get_last_folder(),
  8053. filter=_filter_)
  8054. except TypeError:
  8055. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  8056. filter=_filter_)
  8057. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  8058. type_of_obj = "geometry"
  8059. filenames = [str(filename) for filename in filenames]
  8060. if len(filenames) == 0:
  8061. self.inform.emit('[WARNING_NOTCL] %s' %
  8062. _("Open DXF cancelled."))
  8063. else:
  8064. for filename in filenames:
  8065. if filename != '':
  8066. self.worker_task.emit({'fcn': self.import_dxf,
  8067. 'params': [filename, type_of_obj]})
  8068. # ###############################################################################################################
  8069. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  8070. # ###############################################################################################################
  8071. def init_code_editor(self, name):
  8072. self.text_editor_tab = TextEditor(app=self)
  8073. # add the tab if it was closed
  8074. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  8075. self.text_editor_tab.setObjectName('text_editor_tab')
  8076. # delete the absolute and relative position and messages in the infobar
  8077. self.ui.position_label.setText("")
  8078. self.ui.rel_position_label.setText("")
  8079. # first clear previous text in text editor (if any)
  8080. self.text_editor_tab.code_editor.clear()
  8081. self.text_editor_tab.code_editor.setReadOnly(False)
  8082. self.toggle_codeeditor = True
  8083. self.text_editor_tab.code_editor.completer_enable = False
  8084. self.text_editor_tab.buttonRun.hide()
  8085. # make sure to keep a reference to the code editor
  8086. self.reference_code_editor = self.text_editor_tab.code_editor
  8087. # Switch plot_area to CNCJob tab
  8088. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  8089. def on_view_source(self):
  8090. """
  8091. Called when the user wants to see the source file of the selected object
  8092. :return:
  8093. """
  8094. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  8095. self.proc_container.view.set_busy(_("Loading..."))
  8096. try:
  8097. obj = self.collection.get_active()
  8098. except Exception as e:
  8099. log.debug("App.on_view_source() --> %s" % str(e))
  8100. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  8101. return 'fail'
  8102. if obj is None:
  8103. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  8104. return 'fail'
  8105. flt = "All Files (*.*)"
  8106. if obj.kind == 'gerber':
  8107. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  8108. elif obj.kind == 'excellon':
  8109. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  8110. elif obj.kind == 'cncjob':
  8111. "GCode Files (*.NC);;All Files (*.*)"
  8112. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  8113. # add the tab if it was closed
  8114. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  8115. self.source_editor_tab.setObjectName('source_editor_tab')
  8116. # delete the absolute and relative position and messages in the infobar
  8117. self.ui.position_label.setText("")
  8118. self.ui.rel_position_label.setText("")
  8119. # first clear previous text in text editor (if any)
  8120. self.source_editor_tab.code_editor.clear()
  8121. self.source_editor_tab.code_editor.setReadOnly(False)
  8122. self.source_editor_tab.code_editor.completer_enable = False
  8123. self.source_editor_tab.buttonRun.hide()
  8124. # Switch plot_area to CNCJob tab
  8125. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  8126. try:
  8127. self.source_editor_tab.buttonOpen.clicked.disconnect()
  8128. except TypeError:
  8129. pass
  8130. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  8131. try:
  8132. self.source_editor_tab.buttonSave.clicked.disconnect()
  8133. except TypeError:
  8134. pass
  8135. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  8136. # then append the text from GCode to the text editor
  8137. if obj.kind == 'cncjob':
  8138. try:
  8139. file = obj.export_gcode(
  8140. preamble=self.defaults["cncjob_prepend"],
  8141. postamble=self.defaults["cncjob_append"],
  8142. to_file=True)
  8143. if file == 'fail':
  8144. return 'fail'
  8145. except AttributeError:
  8146. self.inform.emit('[WARNING_NOTCL] %s' %
  8147. _("There is no selected object for which to see it's source file code."))
  8148. return 'fail'
  8149. else:
  8150. try:
  8151. file = StringIO(obj.source_file)
  8152. except (AttributeError, TypeError):
  8153. self.inform.emit('[WARNING_NOTCL] %s' %
  8154. _("There is no selected object for which to see it's source file code."))
  8155. return 'fail'
  8156. self.source_editor_tab.t_frame.hide()
  8157. try:
  8158. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  8159. # for line in file:
  8160. # QtWidgets.QApplication.processEvents()
  8161. # proc_line = str(line).strip('\n')
  8162. # self.source_editor_tab.code_editor.append(proc_line)
  8163. except Exception as e:
  8164. log.debug('App.on_view_source() -->%s' % str(e))
  8165. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  8166. return
  8167. self.source_editor_tab.handleTextChanged()
  8168. self.source_editor_tab.t_frame.show()
  8169. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  8170. self.proc_container.view.set_idle()
  8171. # self.ui.show()
  8172. def on_toggle_code_editor(self):
  8173. self.report_usage("on_toggle_code_editor()")
  8174. if self.toggle_codeeditor is False:
  8175. self.init_code_editor(name=_("Code Editor"))
  8176. self.text_editor_tab.buttonOpen.clicked.disconnect()
  8177. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  8178. self.text_editor_tab.buttonSave.clicked.disconnect()
  8179. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  8180. else:
  8181. for idx in range(self.ui.plot_tab_area.count()):
  8182. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  8183. self.ui.plot_tab_area.closeTab(idx)
  8184. break
  8185. self.toggle_codeeditor = False
  8186. def on_code_editor_close(self):
  8187. print("closed")
  8188. self.toggle_codeeditor = False
  8189. def on_filenewscript(self, silent=False, name=None, text=None):
  8190. """
  8191. Will create a new script file and open it in the Code Editor
  8192. :param silent: if True will not display status messages
  8193. :param name: if specified will be the name of the new script
  8194. :param text: pass a source file to the newly created script to be loaded in it
  8195. :return: None
  8196. """
  8197. if silent is False:
  8198. self.inform.emit('[success] %s' %
  8199. _("New TCL script file created in Code Editor."))
  8200. # delete the absolute and relative position and messages in the infobar
  8201. self.ui.position_label.setText("")
  8202. self.ui.rel_position_label.setText("")
  8203. if name is not None:
  8204. self.new_script_object(name=name, text=text)
  8205. else:
  8206. self.new_script_object(text=text)
  8207. # script_text = script_obj.source_file
  8208. #
  8209. # self.proc_container.view.set_busy(_("Loading..."))
  8210. # script_obj.script_editor_tab.t_frame.hide()
  8211. #
  8212. # script_obj.script_editor_tab.t_frame.show()
  8213. # self.proc_container.view.set_idle()
  8214. def on_fileopenscript(self, name=None, silent=False):
  8215. """
  8216. Will open a Tcl script file into the Code Editor
  8217. :param silent: if True will not display status messages
  8218. :param name: name of a Tcl script file to open
  8219. :return:
  8220. """
  8221. self.report_usage("on_fileopenscript")
  8222. App.log.debug("on_fileopenscript()")
  8223. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  8224. if name:
  8225. filenames = [name]
  8226. else:
  8227. try:
  8228. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  8229. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  8230. except TypeError:
  8231. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  8232. if len(filenames) == 0:
  8233. if silent is False:
  8234. self.inform.emit('[WARNING_NOTCL] %s' % _("Open TCL script cancelled."))
  8235. else:
  8236. for filename in filenames:
  8237. if filename != '':
  8238. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  8239. def on_filerunscript(self, name=None, silent=False):
  8240. """
  8241. File menu callback for loading and running a TCL script.
  8242. :param silent: if True will not display status messages
  8243. :param name: name of a Tcl script file to be run by FlatCAM
  8244. :return: None
  8245. """
  8246. self.report_usage("on_filerunscript")
  8247. App.log.debug("on_file_runscript()")
  8248. if name:
  8249. filename = name
  8250. if self.cmd_line_headless != 1:
  8251. self.splash.showMessage('%s: %ssec\n%s' %
  8252. (_("Canvas initialization started.\n"
  8253. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8254. _("Executing FlatCAMScript file.")
  8255. ),
  8256. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8257. color=QtGui.QColor("gray"))
  8258. else:
  8259. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  8260. try:
  8261. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  8262. directory=self.get_last_folder(), filter=_filter_)
  8263. except TypeError:
  8264. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  8265. # The Qt methods above will return a QString which can cause problems later.
  8266. # So far json.dump() will fail to serialize it.
  8267. # TODO: Improve the serialization methods and remove this fix.
  8268. filename = str(filename)
  8269. if filename == "":
  8270. if silent is False:
  8271. self.inform.emit('[WARNING_NOTCL] %s' %
  8272. _("Run TCL script cancelled."))
  8273. else:
  8274. if self.cmd_line_headless != 1:
  8275. if self.ui.shell_dock.isHidden():
  8276. self.ui.shell_dock.show()
  8277. try:
  8278. with open(filename, "r") as tcl_script:
  8279. cmd_line_shellfile_content = tcl_script.read()
  8280. if self.cmd_line_headless != 1:
  8281. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  8282. else:
  8283. self.shell._sysShell.exec_command(cmd_line_shellfile_content, no_echo=True)
  8284. if silent is False:
  8285. self.inform.emit('[success] %s' %
  8286. _("TCL script file opened in Code Editor and executed."))
  8287. except Exception as e:
  8288. log.debug("App.on_filerunscript() -> %s" % str(e))
  8289. sys.exit(2)
  8290. def on_file_saveproject(self, silent=False):
  8291. """
  8292. Callback for menu item File->Save Project. Saves the project to
  8293. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  8294. if set to None. The project is saved by calling ``self.save_project()``.
  8295. :param silent: if True will not display status messages
  8296. :return: None
  8297. """
  8298. self.report_usage("on_file_saveproject")
  8299. if self.project_filename is None:
  8300. self.on_file_saveprojectas()
  8301. else:
  8302. self.worker_task.emit({'fcn': self.save_project,
  8303. 'params': [self.project_filename, silent]})
  8304. if self.defaults["global_open_style"] is False:
  8305. self.file_opened.emit("project", self.project_filename)
  8306. self.file_saved.emit("project", self.project_filename)
  8307. self.set_ui_title(name=self.project_filename)
  8308. self.should_we_save = False
  8309. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  8310. """
  8311. Callback for menu item File->Save Project As... Opens a file
  8312. chooser and saves the project to the given file via
  8313. ``self.save_project()``.
  8314. :param make_copy if to be create a copy of the project; boolean
  8315. :param use_thread: if to be run in a separate thread; boolean
  8316. :param quit_action: if to be followed by quiting the application; boolean
  8317. :return: None
  8318. """
  8319. self.report_usage("on_file_saveprojectas")
  8320. self.date = str(datetime.today()).rpartition('.')[0]
  8321. self.date = ''.join(c for c in self.date if c not in ':-')
  8322. self.date = self.date.replace(' ', '_')
  8323. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  8324. try:
  8325. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8326. caption=_("Save Project As ..."),
  8327. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  8328. filter=filter_)
  8329. except TypeError:
  8330. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  8331. filename = str(filename)
  8332. if filename == '':
  8333. self.inform.emit('[WARNING_NOTCL] %s' %
  8334. _("Save Project cancelled."))
  8335. return
  8336. try:
  8337. f = open(filename, 'r')
  8338. f.close()
  8339. except IOError:
  8340. pass
  8341. if use_thread is True:
  8342. self.worker_task.emit({'fcn': self.save_project,
  8343. 'params': [filename, quit_action]})
  8344. else:
  8345. self.save_project(filename, quit_action)
  8346. # self.save_project(filename)
  8347. if self.defaults["global_open_style"] is False:
  8348. self.file_opened.emit("project", filename)
  8349. self.file_saved.emit("project", filename)
  8350. if not make_copy:
  8351. self.project_filename = filename
  8352. self.set_ui_title(name=self.project_filename)
  8353. self.should_we_save = False
  8354. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  8355. """
  8356. Exports a Geometry Object to an SVG file.
  8357. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8358. :param filename: Path to the SVG file to save to.
  8359. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  8360. :return:
  8361. """
  8362. self.report_usage("export_svg()")
  8363. if filename is None:
  8364. filename = self.defaults["global_last_save_folder"]
  8365. self.log.debug("export_svg()")
  8366. try:
  8367. obj = self.collection.get_by_name(str(obj_name))
  8368. except Exception:
  8369. # TODO: The return behavior has not been established... should raise exception?
  8370. return "Could not retrieve object: %s" % obj_name
  8371. with self.proc_container.new(_("Exporting SVG")) as proc:
  8372. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  8373. # Determine bounding area for svg export
  8374. bounds = obj.bounds()
  8375. size = obj.size()
  8376. # Convert everything to strings for use in the xml doc
  8377. svgwidth = str(size[0])
  8378. svgheight = str(size[1])
  8379. minx = str(bounds[0])
  8380. miny = str(bounds[1] - size[1])
  8381. uom = obj.units.lower()
  8382. # Add a SVG Header and footer to the svg output from shapely
  8383. # The transform flips the Y Axis so that everything renders
  8384. # properly within svg apps such as inkscape
  8385. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8386. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8387. svg_header += 'width="' + svgwidth + uom + '" '
  8388. svg_header += 'height="' + svgheight + uom + '" '
  8389. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  8390. svg_header += '<g transform="scale(1,-1)">'
  8391. svg_footer = '</g> </svg>'
  8392. svg_elem = svg_header + exported_svg + svg_footer
  8393. # Parse the xml through a xml parser just to add line feeds
  8394. # and to make it look more pretty for the output
  8395. svgcode = parse_xml_string(svg_elem)
  8396. svgcode = svgcode.toprettyxml()
  8397. try:
  8398. with open(filename, 'w') as fp:
  8399. fp.write(svgcode)
  8400. except PermissionError:
  8401. self.inform.emit('[WARNING] %s' %
  8402. _("Permission denied, saving not possible.\n"
  8403. "Most likely another app is holding the file open and not accessible."))
  8404. return 'fail'
  8405. if self.defaults["global_open_style"] is False:
  8406. self.file_opened.emit("SVG", filename)
  8407. self.file_saved.emit("SVG", filename)
  8408. self.inform.emit('[success] %s: %s' %
  8409. (_("SVG file exported to"), filename))
  8410. def save_source_file(self, obj_name, filename, use_thread=True):
  8411. """
  8412. Exports a FlatCAM Object to an Gerber/Excellon file.
  8413. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8414. :param filename: Path to the Gerber file to save to.
  8415. :param use_thread: if to be run in a separate thread
  8416. :return:
  8417. """
  8418. self.report_usage("save source file()")
  8419. if filename is None:
  8420. filename = self.defaults["global_last_save_folder"]
  8421. self.log.debug("save source file()")
  8422. obj = self.collection.get_by_name(obj_name)
  8423. file_string = StringIO(obj.source_file)
  8424. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8425. if file_string.getvalue() == '':
  8426. self.inform.emit('[ERROR_NOTCL] %s' %
  8427. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  8428. return 'fail'
  8429. try:
  8430. with open(filename, 'w') as file:
  8431. file.writelines('G04*\n')
  8432. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8433. (obj.kind.upper(), str(self.version), str(self.version_date)))
  8434. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8435. file.writelines('G04 Created on : %s*\n' % time_string)
  8436. for line in file_string:
  8437. file.writelines(line)
  8438. except PermissionError:
  8439. self.inform.emit('[WARNING] %s' %
  8440. _("Permission denied, saving not possible.\n"
  8441. "Most likely another app is holding the file open and not accessible."))
  8442. return 'fail'
  8443. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  8444. """
  8445. Exports a Excellon Object to an Excellon file.
  8446. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  8447. :param filename: Path to the Excellon file to save to.
  8448. :param local_use:
  8449. :param use_thread: if to be run in a separate thread
  8450. :return:
  8451. """
  8452. self.report_usage("export_excellon()")
  8453. if filename is None:
  8454. filename = self.defaults["global_last_save_folder"]
  8455. self.log.debug("export_excellon()")
  8456. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  8457. self.defaults["excellon_exp_decimals"]
  8458. )
  8459. if local_use is None:
  8460. try:
  8461. obj = self.collection.get_by_name(str(obj_name))
  8462. except Exception:
  8463. # TODO: The return behavior has not been established... should raise exception?
  8464. return "Could not retrieve object: %s" % obj_name
  8465. else:
  8466. obj = local_use
  8467. # updated units
  8468. eunits = self.defaults["excellon_exp_units"]
  8469. ewhole = self.defaults["excellon_exp_integer"]
  8470. efract = self.defaults["excellon_exp_decimals"]
  8471. ezeros = self.defaults["excellon_exp_zeros"]
  8472. eformat = self.defaults["excellon_exp_format"]
  8473. slot_type = self.defaults["excellon_exp_slot_type"]
  8474. fc_units = self.defaults['units'].upper()
  8475. if fc_units == 'MM':
  8476. factor = 1 if eunits == 'METRIC' else 0.03937
  8477. else:
  8478. factor = 25.4 if eunits == 'METRIC' else 1
  8479. def make_excellon():
  8480. try:
  8481. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8482. header = 'M48\n'
  8483. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  8484. (str(self.version), str(self.version_date))
  8485. header += ';Filename: %s' % str(obj_name) + '\n'
  8486. header += ';Created on : %s' % time_str + '\n'
  8487. if eformat == 'dec':
  8488. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  8489. header += eunits + '\n'
  8490. for tool in obj.tools:
  8491. if eunits == 'METRIC':
  8492. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8493. tool=str(tool),
  8494. dec=2)
  8495. else:
  8496. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8497. tool=str(tool),
  8498. dec=4)
  8499. else:
  8500. if ezeros == 'LZ':
  8501. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8502. form='ndec', e_zeros='LZ', factor=factor,
  8503. slot_type=slot_type)
  8504. header += '%s,%s\n' % (eunits, 'LZ')
  8505. header += format_exc
  8506. for tool in obj.tools:
  8507. if eunits == 'METRIC':
  8508. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8509. tool=str(tool),
  8510. dec=2)
  8511. else:
  8512. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8513. tool=str(tool),
  8514. dec=4)
  8515. else:
  8516. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8517. form='ndec', e_zeros='TZ', factor=factor,
  8518. slot_type=slot_type)
  8519. header += '%s,%s\n' % (eunits, 'TZ')
  8520. header += format_exc
  8521. for tool in obj.tools:
  8522. if eunits == 'METRIC':
  8523. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8524. tool=str(tool),
  8525. dec=2)
  8526. else:
  8527. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8528. tool=str(tool),
  8529. dec=4)
  8530. header += '%\n'
  8531. footer = 'M30\n'
  8532. exported_excellon = header
  8533. exported_excellon += excellon_code
  8534. exported_excellon += footer
  8535. if local_use is None:
  8536. try:
  8537. with open(filename, 'w') as fp:
  8538. fp.write(exported_excellon)
  8539. except PermissionError:
  8540. self.inform.emit('[WARNING] %s' %
  8541. _("Permission denied, saving not possible.\n"
  8542. "Most likely another app is holding the file open and not accessible."))
  8543. return 'fail'
  8544. if self.defaults["global_open_style"] is False:
  8545. self.file_opened.emit("Excellon", filename)
  8546. self.file_saved.emit("Excellon", filename)
  8547. self.inform.emit('[success] %s: %s' %
  8548. (_("Excellon file exported to"), filename))
  8549. else:
  8550. return exported_excellon
  8551. except Exception as e:
  8552. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  8553. return 'fail'
  8554. if use_thread is True:
  8555. with self.proc_container.new(_("Exporting Excellon")) as proc:
  8556. def job_thread_exc(app_obj):
  8557. ret = make_excellon()
  8558. if ret == 'fail':
  8559. self.inform.emit('[ERROR_NOTCL] %s' %
  8560. _('Could not export Excellon file.'))
  8561. return
  8562. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8563. else:
  8564. ret = make_excellon()
  8565. if ret == 'fail':
  8566. self.inform.emit('[ERROR_NOTCL] %s' %
  8567. _('Could not export Excellon file.'))
  8568. return 'fail'
  8569. if local_use is not None:
  8570. return ret
  8571. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  8572. """
  8573. Exports a Gerber Object to an Gerber file.
  8574. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  8575. :param filename: Path to the Gerber file to save to.
  8576. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8577. When not None, the value will be the actual Gerber object for which to create the Gerber code
  8578. :param use_thread: if to be run in a separate thread
  8579. :return:
  8580. """
  8581. self.report_usage("export_gerber()")
  8582. if filename is None:
  8583. filename = self.defaults["global_last_save_folder"]
  8584. self.log.debug("export_gerber()")
  8585. if local_use is None:
  8586. try:
  8587. obj = self.collection.get_by_name(str(obj_name))
  8588. except Exception:
  8589. # TODO: The return behavior has not been established... should raise exception?
  8590. return "Could not retrieve object: %s" % obj_name
  8591. else:
  8592. obj = local_use
  8593. # updated units
  8594. gunits = self.defaults["gerber_exp_units"]
  8595. gwhole = self.defaults["gerber_exp_integer"]
  8596. gfract = self.defaults["gerber_exp_decimals"]
  8597. gzeros = self.defaults["gerber_exp_zeros"]
  8598. fc_units = self.defaults['units'].upper()
  8599. if fc_units == 'MM':
  8600. factor = 1 if gunits == 'MM' else 0.03937
  8601. else:
  8602. factor = 25.4 if gunits == 'MM' else 1
  8603. def make_gerber():
  8604. try:
  8605. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8606. header = 'G04*\n'
  8607. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  8608. (str(self.version), str(self.version_date))
  8609. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  8610. header += 'G04 Created on : %s*' % time_str + '\n'
  8611. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  8612. header += "%MO{units}*%\n".format(units=gunits)
  8613. for apid in obj.apertures:
  8614. if obj.apertures[apid]['type'] == 'C':
  8615. header += "%ADD{apid}{type},{size}*%\n".format(
  8616. apid=str(apid),
  8617. type='C',
  8618. size=(factor * obj.apertures[apid]['size'])
  8619. )
  8620. elif obj.apertures[apid]['type'] == 'R':
  8621. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8622. apid=str(apid),
  8623. type='R',
  8624. width=(factor * obj.apertures[apid]['width']),
  8625. height=(factor * obj.apertures[apid]['height'])
  8626. )
  8627. elif obj.apertures[apid]['type'] == 'O':
  8628. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8629. apid=str(apid),
  8630. type='O',
  8631. width=(factor * obj.apertures[apid]['width']),
  8632. height=(factor * obj.apertures[apid]['height'])
  8633. )
  8634. header += '\n'
  8635. # obsolete units but some software may need it
  8636. if gunits == 'IN':
  8637. header += 'G70*\n'
  8638. else:
  8639. header += 'G71*\n'
  8640. # Absolute Mode
  8641. header += 'G90*\n'
  8642. header += 'G01*\n'
  8643. # positive polarity
  8644. header += '%LPD*%\n'
  8645. footer = 'M02*\n'
  8646. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8647. exported_gerber = header
  8648. exported_gerber += gerber_code
  8649. exported_gerber += footer
  8650. if local_use is None:
  8651. try:
  8652. with open(filename, 'w') as fp:
  8653. fp.write(exported_gerber)
  8654. except PermissionError:
  8655. self.inform.emit('[WARNING] %s' %
  8656. _("Permission denied, saving not possible.\n"
  8657. "Most likely another app is holding the file open and not accessible."))
  8658. return 'fail'
  8659. if self.defaults["global_open_style"] is False:
  8660. self.file_opened.emit("Gerber", filename)
  8661. self.file_saved.emit("Gerber", filename)
  8662. self.inform.emit('[success] %s: %s' %
  8663. (_("Gerber file exported to"), filename))
  8664. else:
  8665. return exported_gerber
  8666. except Exception as e:
  8667. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8668. return 'fail'
  8669. if use_thread is True:
  8670. with self.proc_container.new(_("Exporting Gerber")) as proc:
  8671. def job_thread_grb(app_obj):
  8672. ret = make_gerber()
  8673. if ret == 'fail':
  8674. self.inform.emit('[ERROR_NOTCL] %s' %
  8675. _('Could not export Gerber file.'))
  8676. return
  8677. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8678. else:
  8679. ret = make_gerber()
  8680. if ret == 'fail':
  8681. self.inform.emit('[ERROR_NOTCL] %s' %
  8682. _('Could not export Gerber file.'))
  8683. return 'fail'
  8684. if local_use is not None:
  8685. return ret
  8686. def export_dxf(self, obj_name, filename, use_thread=True):
  8687. """
  8688. Exports a Geometry Object to an DXF file.
  8689. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8690. :param filename: Path to the DXF file to save to.
  8691. :param use_thread: if to be run in a separate thread
  8692. :return:
  8693. """
  8694. self.report_usage("export_dxf()")
  8695. if filename is None:
  8696. filename = self.defaults["global_last_save_folder"]
  8697. self.log.debug("export_dxf()")
  8698. try:
  8699. obj = self.collection.get_by_name(str(obj_name))
  8700. except Exception:
  8701. # TODO: The return behavior has not been established... should raise exception?
  8702. return "Could not retrieve object: %s" % obj_name
  8703. def make_dxf():
  8704. try:
  8705. dxf_code = obj.export_dxf()
  8706. dxf_code.saveas(filename)
  8707. if self.defaults["global_open_style"] is False:
  8708. self.file_opened.emit("DXF", filename)
  8709. self.file_saved.emit("DXF", filename)
  8710. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  8711. except Exception:
  8712. return 'fail'
  8713. if use_thread is True:
  8714. with self.proc_container.new(_("Exporting DXF")) as proc:
  8715. def job_thread_exc(app_obj):
  8716. ret_dxf_val = make_dxf()
  8717. if ret_dxf_val == 'fail':
  8718. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8719. return
  8720. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8721. else:
  8722. ret = make_dxf()
  8723. if ret == 'fail':
  8724. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8725. return
  8726. def import_svg(self, filename, geo_type='geometry', outname=None):
  8727. """
  8728. Adds a new Geometry Object to the projects and populates
  8729. it with shapes extracted from the SVG file.
  8730. :param filename: Path to the SVG file.
  8731. :param geo_type: Type of FlatCAM object that will be created from SVG
  8732. :param outname:
  8733. :return:
  8734. """
  8735. self.report_usage("import_svg()")
  8736. log.debug("App.import_svg()")
  8737. obj_type = ""
  8738. if geo_type is None or geo_type == "geometry":
  8739. obj_type = "geometry"
  8740. elif geo_type == "gerber":
  8741. obj_type = "gerber"
  8742. else:
  8743. self.inform.emit('[ERROR_NOTCL] %s' %
  8744. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8745. return
  8746. units = self.defaults['units'].upper()
  8747. def obj_init(geo_obj, app_obj):
  8748. geo_obj.import_svg(filename, obj_type, units=units)
  8749. geo_obj.multigeo = False
  8750. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  8751. with self.proc_container.new(_("Importing SVG")) as proc:
  8752. # Object name
  8753. name = outname or filename.split('/')[-1].split('\\')[-1]
  8754. self.new_object(obj_type, name, obj_init, autoselected=False)
  8755. # Register recent file
  8756. self.file_opened.emit("svg", filename)
  8757. # GUI feedback
  8758. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8759. def import_dxf(self, filename, geo_type='geometry', outname=None):
  8760. """
  8761. Adds a new Geometry Object to the projects and populates
  8762. it with shapes extracted from the DXF file.
  8763. :param filename: Path to the DXF file.
  8764. :param geo_type: Type of FlatCAM object that will be created from DXF
  8765. :param outname:
  8766. :type putname: str
  8767. :return:
  8768. """
  8769. self.report_usage("import_dxf()")
  8770. obj_type = ""
  8771. if geo_type is None or geo_type == "geometry":
  8772. obj_type = "geometry"
  8773. elif geo_type == "gerber":
  8774. obj_type = geo_type
  8775. else:
  8776. self.inform.emit('[ERROR_NOTCL] %s' %
  8777. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8778. return
  8779. units = self.defaults['units'].upper()
  8780. def obj_init(geo_obj, app_obj):
  8781. geo_obj.import_dxf(filename, obj_type, units=units)
  8782. geo_obj.multigeo = False
  8783. with self.proc_container.new(_("Importing DXF")) as proc:
  8784. # Object name
  8785. name = outname or filename.split('/')[-1].split('\\')[-1]
  8786. self.new_object(obj_type, name, obj_init, autoselected=False)
  8787. self.progress.emit(20)
  8788. # Register recent file
  8789. self.file_opened.emit("dxf", filename)
  8790. # GUI feedback
  8791. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8792. self.progress.emit(100)
  8793. def open_gerber(self, filename, outname=None):
  8794. """
  8795. Opens a Gerber file, parses it and creates a new object for
  8796. it in the program. Thread-safe.
  8797. :param outname: Name of the resulting object. None causes the
  8798. name to be that of the file.
  8799. :param filename: Gerber file filename
  8800. :type filename: str
  8801. :return: None
  8802. """
  8803. # How the object should be initialized
  8804. def obj_init(gerber_obj, app_obj):
  8805. assert isinstance(gerber_obj, FlatCAMGerber), \
  8806. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  8807. # Opening the file happens here
  8808. self.progress.emit(30)
  8809. try:
  8810. gerber_obj.parse_file(filename)
  8811. except IOError:
  8812. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8813. (_("Failed to open file"), filename))
  8814. app_obj.progress.emit(0)
  8815. return "fail"
  8816. except ParseError as err:
  8817. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' %
  8818. (_("Failed to parse file"), filename, str(err)))
  8819. app_obj.progress.emit(0)
  8820. self.log.error(str(err))
  8821. return "fail"
  8822. except Exception as e:
  8823. log.debug("App.open_gerber() --> %s" % str(e))
  8824. msg = '[ERROR] %s' % \
  8825. _("An internal error has occurred. See shell.\n")
  8826. msg += traceback.format_exc()
  8827. app_obj.inform.emit(msg)
  8828. return "fail"
  8829. if gerber_obj.is_empty():
  8830. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  8831. # self.collection.set_active(gerber_obj.options["name"])
  8832. # self.collection.delete_active()
  8833. self.inform.emit('[ERROR_NOTCL] %s' %
  8834. _("Object is not Gerber file or empty. Aborting object creation."))
  8835. return "fail"
  8836. # Further parsing
  8837. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  8838. App.log.debug("open_gerber()")
  8839. with self.proc_container.new(_("Opening Gerber")) as proc:
  8840. self.progress.emit(10)
  8841. # Object name
  8842. name = outname or filename.split('/')[-1].split('\\')[-1]
  8843. # # ## Object creation # ##
  8844. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  8845. if ret == 'fail':
  8846. self.inform.emit('[ERROR_NOTCL]%s' %
  8847. _(' Open Gerber failed. Probable not a Gerber file.'))
  8848. return
  8849. # Register recent file
  8850. self.file_opened.emit("gerber", filename)
  8851. self.progress.emit(100)
  8852. # GUI feedback
  8853. self.inform.emit('[success] %s: %s' %
  8854. (_("Opened"), filename))
  8855. def open_excellon(self, filename, outname=None, plot=True):
  8856. """
  8857. Opens an Excellon file, parses it and creates a new object for
  8858. it in the program. Thread-safe.
  8859. :param outname: Name of the resulting object. None causes the
  8860. name to be that of the file.
  8861. :param filename: Excellon file filename
  8862. :type filename: str
  8863. :return: None
  8864. """
  8865. App.log.debug("open_excellon()")
  8866. # How the object should be initialized
  8867. def obj_init(excellon_obj, app_obj):
  8868. # self.progress.emit(20)
  8869. try:
  8870. ret = excellon_obj.parse_file(filename=filename)
  8871. if ret == "fail":
  8872. log.debug("Excellon parsing failed.")
  8873. self.inform.emit('[ERROR_NOTCL] %s' %
  8874. _("This is not Excellon file."))
  8875. return "fail"
  8876. except IOError:
  8877. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8878. (_("Cannot open file"), filename))
  8879. log.debug("Could not open Excellon object.")
  8880. self.progress.emit(0) # TODO: self and app_bjj mixed
  8881. return "fail"
  8882. except Exception:
  8883. msg = '[ERROR_NOTCL] %s' % \
  8884. _("An internal error has occurred. See shell.\n")
  8885. msg += traceback.format_exc()
  8886. app_obj.inform.emit(msg)
  8887. return "fail"
  8888. ret = excellon_obj.create_geometry()
  8889. if ret == 'fail':
  8890. log.debug("Could not create geometry for Excellon object.")
  8891. return "fail"
  8892. for tool in excellon_obj.tools:
  8893. if excellon_obj.tools[tool]['solid_geometry']:
  8894. return
  8895. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8896. (_("No geometry found in file"), filename))
  8897. return "fail"
  8898. with self.proc_container.new(_("Opening Excellon.")):
  8899. # Object name
  8900. name = outname or filename.split('/')[-1].split('\\')[-1]
  8901. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8902. if ret_val == 'fail':
  8903. self.inform.emit('[ERROR_NOTCL] %s' %
  8904. _('Open Excellon file failed. Probable not an Excellon file.'))
  8905. return
  8906. # Register recent file
  8907. self.file_opened.emit("excellon", filename)
  8908. # GUI feedback
  8909. self.inform.emit('[success] %s: %s' %
  8910. (_("Opened"), filename))
  8911. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True):
  8912. """
  8913. Opens a G-gcode file, parses it and creates a new object for
  8914. it in the program. Thread-safe.
  8915. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8916. :param filename: G-code file filename
  8917. :type filename: str
  8918. :return: None
  8919. """
  8920. App.log.debug("open_gcode()")
  8921. # How the object should be initialized
  8922. def obj_init(job_obj, app_obj_):
  8923. """
  8924. :param job_obj: the resulting object
  8925. :type app_obj_: App
  8926. """
  8927. assert isinstance(app_obj_, App), \
  8928. "Initializer expected App, got %s" % type(app_obj_)
  8929. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  8930. try:
  8931. f = open(filename)
  8932. gcode = f.read()
  8933. f.close()
  8934. except IOError:
  8935. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  8936. (_("Failed to open"), filename))
  8937. return "fail"
  8938. job_obj.gcode = gcode
  8939. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  8940. if gcode_ret == "fail":
  8941. self.inform.emit('[ERROR_NOTCL] %s' %
  8942. _("This is not GCODE"))
  8943. return "fail"
  8944. job_obj.create_geometry()
  8945. with self.proc_container.new(_("Opening G-Code.")):
  8946. # Object name
  8947. name = outname or filename.split('/')[-1].split('\\')[-1]
  8948. # New object creation and file processing
  8949. obj_ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8950. if obj_ret == 'fail':
  8951. self.inform.emit('[ERROR_NOTCL] %s' %
  8952. _("Failed to create CNCJob Object. Probable not a GCode file. "
  8953. "Try to load it from File menu.\n "
  8954. "Attempting to create a FlatCAM CNCJob Object from "
  8955. "G-Code file failed during processing"))
  8956. return "fail"
  8957. # Register recent file
  8958. self.file_opened.emit("cncjob", filename)
  8959. # GUI feedback
  8960. self.inform.emit('[success] %s: %s' %
  8961. (_("Opened"), filename))
  8962. def open_script(self, filename, outname=None, silent=False):
  8963. """
  8964. Opens a Script file, parses it and creates a new object for
  8965. it in the program. Thread-safe.
  8966. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8967. :param filename: Script file filename
  8968. :type filename: str
  8969. :return: None
  8970. """
  8971. App.log.debug("open_script()")
  8972. with self.proc_container.new(_("Opening TCL Script...")):
  8973. try:
  8974. with open(filename, "r") as opened_script:
  8975. script_content = opened_script.readlines()
  8976. script_content = ''.join(script_content)
  8977. if silent is False:
  8978. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  8979. except Exception as e:
  8980. log.debug("App.open_script() -> %s" % str(e))
  8981. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to open TCL Script."))
  8982. return
  8983. # Object name
  8984. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  8985. # New object creation and file processing
  8986. self.on_filenewscript(name=script_name, text=script_content)
  8987. # Register recent file
  8988. self.file_opened.emit("script", filename)
  8989. # GUI feedback
  8990. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8991. def open_config_file(self, filename, run_from_arg=None):
  8992. """
  8993. Loads a config file from the specified file.
  8994. :param filename: Name of the file from which to load.
  8995. :type filename: str
  8996. :return: None
  8997. """
  8998. App.log.debug("Opening config file: " + filename)
  8999. if run_from_arg:
  9000. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  9001. "Canvas initialization finished in"), '%.2f' % self.used_time,
  9002. _("Opening FlatCAM Config file.")),
  9003. alignment=Qt.AlignBottom | Qt.AlignLeft,
  9004. color=QtGui.QColor("gray"))
  9005. # # add the tab if it was closed
  9006. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  9007. # # first clear previous text in text editor (if any)
  9008. # self.ui.text_editor_tab.code_editor.clear()
  9009. #
  9010. # # Switch plot_area to CNCJob tab
  9011. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  9012. # close the Code editor if already open
  9013. if self.toggle_codeeditor:
  9014. self.on_toggle_code_editor()
  9015. self.on_toggle_code_editor()
  9016. try:
  9017. if filename:
  9018. f = QtCore.QFile(filename)
  9019. if f.open(QtCore.QIODevice.ReadOnly):
  9020. stream = QtCore.QTextStream(f)
  9021. code_edited = stream.readAll()
  9022. self.text_editor_tab.code_editor.setPlainText(code_edited)
  9023. f.close()
  9024. except IOError:
  9025. App.log.error("Failed to open config file: %s" % filename)
  9026. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9027. (_("Failed to open config file"), filename))
  9028. return
  9029. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  9030. """
  9031. Loads a project from the specified file.
  9032. 1) Loads and parses file
  9033. 2) Registers the file as recently opened.
  9034. 3) Calls on_file_new()
  9035. 4) Updates options
  9036. 5) Calls new_object() with the object's from_dict() as init method.
  9037. 6) Calls plot_all() if plot=True
  9038. :param filename: Name of the file from which to load.
  9039. :type filename: str
  9040. :param run_from_arg: True if run for arguments
  9041. :param plot: If True plot all objects in the project
  9042. :param cli: run from command line
  9043. :return: None
  9044. """
  9045. App.log.debug("Opening project: " + filename)
  9046. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9047. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9048. if cli is None:
  9049. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  9050. if run_from_arg:
  9051. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  9052. "Canvas initialization finished in"), '%.2f' % self.used_time,
  9053. _("Opening FlatCAM Project file.")),
  9054. alignment=Qt.AlignBottom | Qt.AlignLeft,
  9055. color=QtGui.QColor("gray"))
  9056. # Open and parse an uncompressed Project file
  9057. try:
  9058. f = open(filename, 'r')
  9059. except IOError:
  9060. App.log.error("Failed to open project file: %s" % filename)
  9061. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9062. (_("Failed to open project file"), filename))
  9063. return
  9064. try:
  9065. d = json.load(f, object_hook=dict2obj)
  9066. except Exception as e:
  9067. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  9068. (filename, str(e)))
  9069. f.close()
  9070. # Open and parse a compressed Project file
  9071. try:
  9072. with lzma.open(filename) as f:
  9073. file_content = f.read().decode('utf-8')
  9074. d = json.loads(file_content, object_hook=dict2obj)
  9075. except Exception as e:
  9076. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  9077. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9078. (_("Failed to open project file"), filename))
  9079. return
  9080. # Clear the current project
  9081. # # NOT THREAD SAFE # ##
  9082. if run_from_arg is True:
  9083. pass
  9084. elif cli is True:
  9085. self.delete_selection_shape()
  9086. else:
  9087. self.on_file_new()
  9088. # Project options
  9089. self.options.update(d['options'])
  9090. self.project_filename = filename
  9091. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9092. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9093. if cli is None:
  9094. self.set_screen_units(self.options["units"])
  9095. # Re create objects
  9096. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  9097. for obj in d['objs']:
  9098. def obj_init(obj_inst, app_inst):
  9099. obj_inst.from_dict(obj)
  9100. App.log.debug("Recreating from opened project an %s object: %s" %
  9101. (obj['kind'].capitalize(), obj['options']['name']))
  9102. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9103. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9104. if cli is None:
  9105. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  9106. obj['kind'].upper(),
  9107. obj['options']['name']
  9108. )
  9109. )
  9110. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  9111. self.inform.emit('[success] %s: %s' %
  9112. (_("Project loaded from"), filename))
  9113. self.should_we_save = False
  9114. self.file_opened.emit("project", filename)
  9115. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9116. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9117. if cli is None:
  9118. self.set_ui_title(name=self.project_filename)
  9119. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  9120. def propagate_defaults(self, silent=False):
  9121. """
  9122. This method is used to set default values in classes. It's
  9123. an alternative to project options but allows the use
  9124. of values invisible to the user.
  9125. :return: None
  9126. """
  9127. if silent is False:
  9128. self.log.debug("propagate_defaults()")
  9129. # Which objects to update the given parameters.
  9130. routes = {
  9131. "global_zdownrate": CNCjob,
  9132. "excellon_zeros": Excellon,
  9133. "excellon_format_upper_in": Excellon,
  9134. "excellon_format_lower_in": Excellon,
  9135. "excellon_format_upper_mm": Excellon,
  9136. "excellon_format_lower_mm": Excellon,
  9137. "excellon_units": Excellon,
  9138. "gerber_use_buffer_for_union": Gerber,
  9139. "geometry_multidepth": Geometry
  9140. }
  9141. for param in routes:
  9142. if param in routes[param].defaults:
  9143. try:
  9144. routes[param].defaults[param] = self.defaults[param]
  9145. if silent is False:
  9146. self.log.debug(" " + param + " OK")
  9147. except KeyError:
  9148. if silent is False:
  9149. self.log.debug("FlatCAMApp.propagate_defaults() --> ERROR: " + param + " not in defaults.")
  9150. else:
  9151. # Try extracting the name:
  9152. # classname_param here is param in the object
  9153. if param.find(routes[param].__name__.lower() + "_") == 0:
  9154. p = param[len(routes[param].__name__) + 1:]
  9155. if p in routes[param].defaults:
  9156. routes[param].defaults[p] = self.defaults[param]
  9157. if silent is False:
  9158. self.log.debug(" " + param + " OK!")
  9159. def plot_all(self, zoom=True):
  9160. """
  9161. Re-generates all plots from all objects.
  9162. :return: None
  9163. """
  9164. self.log.debug("Plot_all()")
  9165. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  9166. for obj in self.collection.get_list():
  9167. def worker_task(obj):
  9168. with self.proc_container.new("Plotting"):
  9169. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  9170. if zoom:
  9171. self.object_plotted.emit(obj)
  9172. # Send to worker
  9173. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  9174. def register_folder(self, filename):
  9175. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  9176. def register_save_folder(self, filename):
  9177. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  9178. def set_progress_bar(self, percentage, text=""):
  9179. self.ui.progress_bar.setValue(int(percentage))
  9180. def setup_shell(self):
  9181. """
  9182. Creates shell functions. Runs once at startup.
  9183. :return: None
  9184. """
  9185. self.log.debug("setup_shell()")
  9186. def shelp(p=None):
  9187. if not p:
  9188. return _("Available commands:\n") + \
  9189. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  9190. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  9191. if p not in commands:
  9192. return "Unknown command: %s" % p
  9193. return commands[p]["help"]
  9194. # --- Migrated to new architecture ---
  9195. # def options(name):
  9196. # ops = self.collection.get_by_name(str(name)).options
  9197. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  9198. def h(*args):
  9199. """
  9200. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  9201. and standalone parameters into list.
  9202. """
  9203. kwa = {}
  9204. a = []
  9205. n = len(args)
  9206. name = None
  9207. for i in range(n):
  9208. match = re.search(r'^-([a-zA-Z].*)', args[i])
  9209. if match:
  9210. assert name is None
  9211. name = match.group(1)
  9212. continue
  9213. if name is None:
  9214. a.append(args[i])
  9215. else:
  9216. kwa[name] = args[i]
  9217. name = None
  9218. return a, kwa
  9219. @contextmanager
  9220. def wait_signal(signal, timeout=10000):
  9221. """
  9222. Block loop until signal emitted, timeout (ms) elapses
  9223. or unhandled exception happens in a thread.
  9224. :param timeout: time after which the loop is exited
  9225. :param signal: Signal to wait for.
  9226. """
  9227. loop = QtCore.QEventLoop()
  9228. # Normal termination
  9229. signal.connect(loop.quit)
  9230. # Termination by exception in thread
  9231. self.thread_exception.connect(loop.quit)
  9232. status = {'timed_out': False}
  9233. def report_quit():
  9234. status['timed_out'] = True
  9235. loop.quit()
  9236. yield
  9237. # Temporarily change how exceptions are managed.
  9238. oeh = sys.excepthook
  9239. ex = []
  9240. def except_hook(type_, value, traceback_):
  9241. ex.append(value)
  9242. oeh(type_, value, traceback_)
  9243. sys.excepthook = except_hook
  9244. # Terminate on timeout
  9245. if timeout is not None:
  9246. QtCore.QTimer.singleShot(timeout, report_quit)
  9247. # # ## Block ## ##
  9248. loop.exec_()
  9249. # Restore exception management
  9250. sys.excepthook = oeh
  9251. if ex:
  9252. self.raiseTclError(str(ex[0]))
  9253. if status['timed_out']:
  9254. raise Exception('Timed out!')
  9255. def make_docs():
  9256. output = ''
  9257. import collections
  9258. od = collections.OrderedDict(sorted(commands.items()))
  9259. for cmd_, val in od.items():
  9260. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  9261. t = val['help']
  9262. usage_i = t.find('>')
  9263. if usage_i < 0:
  9264. expl = t
  9265. output += expl + '\n\n'
  9266. continue
  9267. expl = t[:usage_i - 1]
  9268. output += expl + '\n\n'
  9269. end_usage_i = t[usage_i:].find('\n')
  9270. if end_usage_i < 0:
  9271. end_usage_i = len(t[usage_i:])
  9272. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  9273. else:
  9274. extras = t[usage_i+end_usage_i+1:]
  9275. parts = [s.strip() for s in extras.split('\n')]
  9276. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  9277. for p in parts:
  9278. output += ' ' + p + '\n\n'
  9279. return output
  9280. '''
  9281. Howto implement TCL shell commands:
  9282. All parameters passed to command should be possible to set as None and test it afterwards.
  9283. This is because we need to see error caused in tcl,
  9284. if None value as default parameter is not allowed TCL will return empty error.
  9285. Use:
  9286. def mycommand(name=None,...):
  9287. Test it like this:
  9288. if name is None:
  9289. self.raise_tcl_error('Argument name is missing.')
  9290. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  9291. otherwise we will miss it and processing will silently continue.
  9292. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  9293. which is catched in exec_command and displayed in TCL shell console with red background.
  9294. Error in console is displayed with TCL trace.
  9295. This behavior works only within main thread,
  9296. errors with promissed tasks can be catched and detected only with log.
  9297. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  9298. TCL shell.
  9299. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  9300. '''
  9301. commands = {
  9302. 'help': {
  9303. 'fcn': shelp,
  9304. 'help': _("Shows list of commands.")
  9305. },
  9306. }
  9307. # Import/overwrite tcl commands as objects of TclCommand descendants
  9308. # This modifies the variable 'commands'.
  9309. tclCommands.register_all_commands(self, commands)
  9310. # Add commands to the tcl interpreter
  9311. for cmd in commands:
  9312. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  9313. # Make the tcl puts function return instead of print to stdout
  9314. self.tcl.eval('''
  9315. rename puts original_puts
  9316. proc puts {args} {
  9317. if {[llength $args] == 1} {
  9318. return "[lindex $args 0]"
  9319. } else {
  9320. eval original_puts $args
  9321. }
  9322. }
  9323. ''')
  9324. def setup_recent_items(self):
  9325. # TODO: Move this to constructor
  9326. icons = {
  9327. "gerber": "share/flatcam_icon16.png",
  9328. "excellon": "share/drill16.png",
  9329. 'geometry': "share/geometry16.png",
  9330. "cncjob": "share/cnc16.png",
  9331. "script": "share/script_new24.png",
  9332. "document": "share/notes16_1.png",
  9333. "project": "share/project16.png",
  9334. "svg": "share/geometry16.png",
  9335. "dxf": "share/dxf16.png",
  9336. "pdf": "share/pdf32.png",
  9337. "image": "share/image16.png"
  9338. }
  9339. openers = {
  9340. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  9341. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  9342. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  9343. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  9344. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  9345. "document": None,
  9346. 'project': self.open_project,
  9347. 'svg': self.import_svg,
  9348. 'dxf': self.import_dxf,
  9349. 'image': self.image_tool.import_image,
  9350. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  9351. }
  9352. # Open recent file for files
  9353. try:
  9354. f = open(self.data_path + '/recent.json')
  9355. except IOError:
  9356. App.log.error("Failed to load recent item list.")
  9357. self.inform.emit('[ERROR_NOTCL] %s' %
  9358. _("Failed to load recent item list."))
  9359. return
  9360. try:
  9361. self.recent = json.load(f)
  9362. except json.scanner.JSONDecodeError:
  9363. App.log.error("Failed to parse recent item list.")
  9364. self.inform.emit('[ERROR_NOTCL] %s' %
  9365. _("Failed to parse recent item list."))
  9366. f.close()
  9367. return
  9368. f.close()
  9369. # Open recent file for projects
  9370. try:
  9371. fp = open(self.data_path + '/recent_projects.json')
  9372. except IOError:
  9373. App.log.error("Failed to load recent project item list.")
  9374. self.inform.emit('[ERROR_NOTCL] %s' %
  9375. _("Failed to load recent projects item list."))
  9376. return
  9377. try:
  9378. self.recent_projects = json.load(fp)
  9379. except json.scanner.JSONDecodeError:
  9380. App.log.error("Failed to parse recent project item list.")
  9381. self.inform.emit('[ERROR_NOTCL] %s' %
  9382. _("Failed to parse recent project item list."))
  9383. fp.close()
  9384. return
  9385. fp.close()
  9386. # Closure needed to create callbacks in a loop.
  9387. # Otherwise late binding occurs.
  9388. def make_callback(func, fname):
  9389. def opener():
  9390. func(fname)
  9391. return opener
  9392. def reset_recent_files():
  9393. # Reset menu
  9394. self.ui.recent.clear()
  9395. self.recent = []
  9396. try:
  9397. ff = open(self.data_path + '/recent.json', 'w')
  9398. except IOError:
  9399. App.log.error("Failed to open recent items file for writing.")
  9400. return
  9401. json.dump(self.recent, ff)
  9402. def reset_recent_projects():
  9403. # Reset menu
  9404. self.ui.recent_projects.clear()
  9405. self.recent_projects = []
  9406. try:
  9407. fp = open(self.data_path + '/recent_projects.json', 'w')
  9408. except IOError:
  9409. App.log.error("Failed to open recent projects items file for writing.")
  9410. return
  9411. json.dump(self.recent, fp)
  9412. # Reset menu
  9413. self.ui.recent.clear()
  9414. self.ui.recent_projects.clear()
  9415. # Create menu items for projects
  9416. for recent in self.recent_projects:
  9417. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9418. if recent['kind'] == 'project':
  9419. try:
  9420. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9421. # Attach callback
  9422. o = make_callback(openers[recent["kind"]], recent['filename'])
  9423. action.triggered.connect(o)
  9424. self.ui.recent_projects.addAction(action)
  9425. except KeyError:
  9426. App.log.error("Unsupported file type: %s" % recent["kind"])
  9427. # Last action in Recent Files menu is one that Clear the content
  9428. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent projects")), self)
  9429. clear_action_proj.triggered.connect(reset_recent_projects)
  9430. self.ui.recent_projects.addSeparator()
  9431. self.ui.recent_projects.addAction(clear_action_proj)
  9432. # Create menu items for files
  9433. for recent in self.recent:
  9434. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9435. if recent['kind'] != 'project':
  9436. try:
  9437. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9438. # Attach callback
  9439. o = make_callback(openers[recent["kind"]], recent['filename'])
  9440. action.triggered.connect(o)
  9441. self.ui.recent.addAction(action)
  9442. except KeyError:
  9443. App.log.error("Unsupported file type: %s" % recent["kind"])
  9444. # Last action in Recent Files menu is one that Clear the content
  9445. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  9446. clear_action.triggered.connect(reset_recent_files)
  9447. self.ui.recent.addSeparator()
  9448. self.ui.recent.addAction(clear_action)
  9449. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  9450. # self.ui.menufilerecent.set_submenu(recent_menu)
  9451. # recent_menu.show_all()
  9452. # self.ui.recent.show()
  9453. self.log.debug("Recent items list has been populated.")
  9454. def setup_component_editor(self):
  9455. # label = QtWidgets.QLabel("Choose an item from Project")
  9456. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  9457. sel_title = QtWidgets.QTextEdit(
  9458. _('<b>Shortcut Key List</b>'))
  9459. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  9460. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  9461. settings = QSettings("Open Source", "FlatCAM")
  9462. if settings.contains("notebook_font_size"):
  9463. fsize = settings.value('notebook_font_size', type=int)
  9464. else:
  9465. fsize = 12
  9466. tsize = fsize + int(fsize / 2)
  9467. # selected_text = (_('''
  9468. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  9469. #
  9470. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  9471. # The normal flow when working in FlatCAM is the following:</span></p>
  9472. #
  9473. # <ol>
  9474. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  9475. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  9476. # even dragging and dropping the files on the GUI.<br />
  9477. # <br />
  9478. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  9479. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  9480. # &nbsp;</li>
  9481. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  9482. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  9483. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  9484. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  9485. # <br />
  9486. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  9487. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  9488. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  9489. # it even if it was out of focus.<br />
  9490. # <br />
  9491. # You can change the parameters in this screen and the flow direction is like this:<br />
  9492. # <br />
  9493. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  9494. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  9495. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  9496. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  9497. # </ol>
  9498. #
  9499. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  9500. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  9501. # <strong>F3</strong>.</span></p>
  9502. #
  9503. # ''').format(fsize=fsize, tsize=tsize))
  9504. selected_text = '''
  9505. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  9506. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  9507. {s1}</span></p>
  9508. <ol>
  9509. <li><span style="font-size:{fsize}px">{s2}<br />
  9510. <br />
  9511. {s3}</span><br />
  9512. &nbsp;</li>
  9513. <li><span style="font-size:{fsize}px">{s4}<br />
  9514. &nbsp;</li>
  9515. <br />
  9516. <li><span style="font-size:{fsize}px">{s5}<br />
  9517. &nbsp;</li>
  9518. <br />
  9519. <li><span style="font-size:{fsize}px">{s6}<br />
  9520. <br />
  9521. {s7}</span></li>
  9522. </ol>
  9523. <p><span style="font-size:{fsize}px">{s8}</span></p>
  9524. '''.format(
  9525. title=_("Selected Tab - Choose an Item from Project Tab"),
  9526. subtitle=_("Details"),
  9527. s1=_("The normal flow when working in FlatCAM is the following:"),
  9528. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  9529. "using either the toolbars, key shortcuts or even dragging and dropping the "
  9530. "files on the GUI."),
  9531. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  9532. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  9533. "actions offered within the app."),
  9534. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  9535. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  9536. "SELECTED TAB will be updated with the object properties according to its kind: "
  9537. "Gerber, Excellon, Geometry or CNCJob object."),
  9538. s5=_("If the selection of the object is done on the canvas by single click instead, "
  9539. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  9540. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  9541. "the SELECTED TAB and populate it even if it was out of focus."),
  9542. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  9543. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  9544. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  9545. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  9546. "(again, done in SELECTED TAB) --> Save GCode."),
  9547. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  9548. "or through its own key shortcut: <b>F3</b>."),
  9549. tsize=tsize,
  9550. fsize=fsize
  9551. )
  9552. sel_title.setText(selected_text)
  9553. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  9554. self.ui.selected_scroll_area.setWidget(sel_title)
  9555. def setup_obj_classes(self):
  9556. """
  9557. Sets up application specifics on the FlatCAMObj class.
  9558. :return: None
  9559. """
  9560. FlatCAMObj.app = self
  9561. ObjectCollection.app = self
  9562. Gerber.app = self
  9563. Excellon.app = self
  9564. Geometry.app = self
  9565. CNCjob.app = self
  9566. FCProcess.app = self
  9567. FCProcessContainer.app = self
  9568. def version_check(self):
  9569. """
  9570. Checks for the latest version of the program. Alerts the
  9571. user if theirs is outdated. This method is meant to be run
  9572. in a separate thread.
  9573. :return: None
  9574. """
  9575. self.log.debug("version_check()")
  9576. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  9577. full_url = App.version_url + \
  9578. "?s=" + str(self.defaults['global_serial']) + \
  9579. "&v=" + str(self.version) + \
  9580. "&os=" + str(self.os) + \
  9581. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  9582. else:
  9583. # no_stats dict; just so it won't break things on website
  9584. no_ststs_dict = {}
  9585. no_ststs_dict["global_ststs"] = {}
  9586. full_url = App.version_url + \
  9587. "?s=" + str(self.defaults['global_serial']) + \
  9588. "&v=" + str(self.version) + \
  9589. "&os=" + str(self.os) + \
  9590. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  9591. App.log.debug("Checking for updates @ %s" % full_url)
  9592. # ## Get the data
  9593. try:
  9594. f = urllib.request.urlopen(full_url)
  9595. except Exception:
  9596. # App.log.warning("Failed checking for latest version. Could not connect.")
  9597. self.log.warning("Failed checking for latest version. Could not connect.")
  9598. self.inform.emit('[WARNING_NOTCL] %s' %
  9599. _("Failed checking for latest version. Could not connect."))
  9600. return
  9601. try:
  9602. data = json.load(f)
  9603. except Exception as e:
  9604. App.log.error("Could not parse information about latest version.")
  9605. self.inform.emit('[ERROR_NOTCL] %s' %
  9606. _("Could not parse information about latest version."))
  9607. App.log.debug("json.load(): %s" % str(e))
  9608. f.close()
  9609. return
  9610. f.close()
  9611. # ## Latest version?
  9612. if self.version >= data["version"]:
  9613. App.log.debug("FlatCAM is up to date!")
  9614. self.inform.emit('[success] %s' %
  9615. _("FlatCAM is up to date!"))
  9616. return
  9617. App.log.debug("Newer version available.")
  9618. self.message.emit(
  9619. _("Newer Version Available"),
  9620. _("There is a newer version of FlatCAM available for download:\n\n") +
  9621. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  9622. _("info")
  9623. )
  9624. def on_plotcanvas_setup(self, container=None):
  9625. """
  9626. This is doing the setup for the plot area (VisPy canvas)
  9627. :param container: widget where to install the canvas
  9628. :return: None
  9629. """
  9630. if container:
  9631. plot_container = container
  9632. else:
  9633. plot_container = self.ui.right_layout
  9634. if self.is_legacy is False:
  9635. self.plotcanvas = PlotCanvas(plot_container, self)
  9636. else:
  9637. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  9638. # So it can receive key presses
  9639. self.plotcanvas.native.setFocus()
  9640. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  9641. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  9642. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  9643. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  9644. # Keys over plot enabled
  9645. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  9646. if self.defaults['global_cursor_type'] == 'small':
  9647. self.app_cursor = self.plotcanvas.new_cursor()
  9648. else:
  9649. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  9650. if self.ui.grid_snap_btn.isChecked():
  9651. self.app_cursor.enabled = True
  9652. else:
  9653. self.app_cursor.enabled = False
  9654. if self.is_legacy is False:
  9655. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  9656. else:
  9657. # will use the default Matplotlib axes
  9658. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  9659. def on_zoom_fit(self, event):
  9660. """
  9661. Callback for zoom-out request. This can be either from the corresponding
  9662. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  9663. with axes limits from the geometry bounds of all objects.
  9664. :param event: Ignored.
  9665. :return: None
  9666. """
  9667. if self.is_legacy is False:
  9668. self.plotcanvas.fit_view()
  9669. else:
  9670. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  9671. width = xmax - xmin
  9672. height = ymax - ymin
  9673. xmin -= 0.05 * width
  9674. xmax += 0.05 * width
  9675. ymin -= 0.05 * height
  9676. ymax += 0.05 * height
  9677. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  9678. def on_zoom_in(self):
  9679. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  9680. def on_zoom_out(self):
  9681. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  9682. def disable_all_plots(self):
  9683. self.report_usage("disable_all_plots()")
  9684. self.disable_plots(self.collection.get_list())
  9685. self.inform.emit('[success] %s' %
  9686. _("All plots disabled."))
  9687. def disable_other_plots(self):
  9688. self.report_usage("disable_other_plots()")
  9689. self.disable_plots(self.collection.get_non_selected())
  9690. self.inform.emit('[success] %s' %
  9691. _("All non selected plots disabled."))
  9692. def enable_all_plots(self):
  9693. self.report_usage("enable_all_plots()")
  9694. self.enable_plots(self.collection.get_list())
  9695. self.inform.emit('[success] %s' %
  9696. _("All plots enabled."))
  9697. def on_enable_sel_plots(self):
  9698. log.debug("App.on_enable_sel_plot()")
  9699. object_list = self.collection.get_selected()
  9700. self.enable_plots(objects=object_list)
  9701. self.inform.emit('[success] %s' %
  9702. _("Selected plots enabled..."))
  9703. def on_disable_sel_plots(self):
  9704. log.debug("App.on_disable_sel_plot()")
  9705. # self.inform.emit(_("Disabling plots ..."))
  9706. object_list = self.collection.get_selected()
  9707. self.disable_plots(objects=object_list)
  9708. self.inform.emit('[success] %s' %
  9709. _("Selected plots disabled..."))
  9710. def enable_plots(self, objects):
  9711. """
  9712. Disables plots
  9713. :param objects: list of Objects to be enabled
  9714. :return:
  9715. """
  9716. log.debug("Enabling plots ...")
  9717. # self.inform.emit(_("Working ..."))
  9718. for obj in objects:
  9719. if obj.options['plot'] is False:
  9720. obj.options.set_change_callback(lambda x: None)
  9721. obj.options['plot'] = True
  9722. obj.options.set_change_callback(obj.on_options_change)
  9723. def worker_task(objs):
  9724. with self.proc_container.new(_("Enabling plots ...")):
  9725. for obj in objs:
  9726. # obj.options['plot'] = True
  9727. if isinstance(obj, FlatCAMCNCjob):
  9728. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  9729. else:
  9730. obj.plot(visible=True)
  9731. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9732. # self.plots_updated.emit()
  9733. def disable_plots(self, objects):
  9734. """
  9735. Disables plots
  9736. :param objects: list of Objects to be disabled
  9737. :return:
  9738. """
  9739. # if no objects selected then do nothing
  9740. if not self.collection.get_selected():
  9741. return
  9742. log.debug("Disabling plots ...")
  9743. # self.inform.emit(_("Working ..."))
  9744. for obj in objects:
  9745. if obj.options['plot'] is True:
  9746. obj.options.set_change_callback(lambda x: None)
  9747. obj.options['plot'] = False
  9748. obj.options.set_change_callback(obj.on_options_change)
  9749. try:
  9750. self.delete_selection_shape()
  9751. except Exception as e:
  9752. log.debug("App.disable_plots() --> %s" % str(e))
  9753. # self.plots_updated.emit()
  9754. def worker_task(objs):
  9755. with self.proc_container.new(_("Disabling plots ...")):
  9756. for obj in objs:
  9757. # obj.options['plot'] = True
  9758. if isinstance(obj, FlatCAMCNCjob):
  9759. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  9760. else:
  9761. obj.plot(visible=False)
  9762. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9763. def toggle_plots(self, objects):
  9764. """
  9765. Toggle plots visibility
  9766. :param objects: list of Objects for which to be toggled the visibility
  9767. :return:
  9768. """
  9769. # if no objects selected then do nothing
  9770. if not self.collection.get_selected():
  9771. return
  9772. log.debug("Toggling plots ...")
  9773. self.inform.emit(_("Working ..."))
  9774. for obj in objects:
  9775. if obj.options['plot'] is False:
  9776. obj.options['plot'] = True
  9777. else:
  9778. obj.options['plot'] = False
  9779. self.plots_updated.emit()
  9780. def clear_plots(self):
  9781. objects = self.collection.get_list()
  9782. for obj in objects:
  9783. obj.clear(obj == objects[-1])
  9784. # Clear pool to free memory
  9785. self.clear_pool()
  9786. def generate_cnc_job(self, objects):
  9787. self.report_usage("generate_cnc_job()")
  9788. # for obj in objects:
  9789. # obj.generatecncjob()
  9790. for obj in objects:
  9791. obj.on_generatecnc_button_click()
  9792. def save_project(self, filename, quit_action=False, silent=False):
  9793. """
  9794. Saves the current project to the specified file.
  9795. :param filename: Name of the file in which to save.
  9796. :type filename: str
  9797. :param quit_action: if the project saving will be followed by an app quit; boolean
  9798. :param silent: if True will not display status messages
  9799. :return: None
  9800. """
  9801. self.log.debug("save_project()")
  9802. self.save_in_progress = True
  9803. with self.proc_container.new(_("Saving FlatCAM Project")):
  9804. # Capture the latest changes
  9805. # Current object
  9806. try:
  9807. self.collection.get_active().read_form()
  9808. except Exception as e:
  9809. self.log.debug("There was no active object. %s" % str(e))
  9810. pass
  9811. # Serialize the whole project
  9812. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  9813. "options": self.options,
  9814. "version": self.version}
  9815. if self.defaults["global_save_compressed"] is True:
  9816. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  9817. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  9818. # # Write
  9819. f.write(g)
  9820. self.inform.emit('[success] %s: %s' %
  9821. (_("Project saved to"), filename))
  9822. else:
  9823. # Open file
  9824. try:
  9825. f = open(filename, 'w')
  9826. except IOError:
  9827. App.log.error("Failed to open file for saving: %s", filename)
  9828. return
  9829. # Write
  9830. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  9831. f.close()
  9832. # verification of the saved project
  9833. # Open and parse
  9834. try:
  9835. saved_f = open(filename, 'r')
  9836. except IOError:
  9837. if silent is False:
  9838. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9839. (_("Failed to verify project file"), filename, _("Retry to save it."))
  9840. )
  9841. return
  9842. try:
  9843. saved_d = json.load(saved_f, object_hook=dict2obj)
  9844. except Exception:
  9845. if silent is False:
  9846. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9847. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9848. )
  9849. f.close()
  9850. return
  9851. saved_f.close()
  9852. if silent is False:
  9853. if 'version' in saved_d:
  9854. self.inform.emit('[success] %s: %s' %
  9855. (_("Project saved to"), filename))
  9856. else:
  9857. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9858. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9859. )
  9860. tb_settings = QSettings("Open Source", "FlatCAM")
  9861. lock_state = self.ui.lock_action.isChecked()
  9862. tb_settings.setValue('toolbar_lock', lock_state)
  9863. # This will write the setting to the platform specific storage.
  9864. del tb_settings
  9865. # if quit:
  9866. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  9867. # t.start()
  9868. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  9869. def start_delayed_quit(self, delay, filename, should_quit=None):
  9870. """
  9871. :param delay: period of checking if project file size is more than zero; in seconds
  9872. :param filename: the name of the project file to be checked periodically for size more than zero
  9873. :param should_quit: if the task finished will be followed by an app quit; boolean
  9874. :return:
  9875. """
  9876. to_quit = should_quit
  9877. self.save_timer = QtCore.QTimer()
  9878. self.save_timer.setInterval(delay)
  9879. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  9880. self.save_timer.start()
  9881. def check_project_file_size(self, filename, should_quit=None):
  9882. """
  9883. :param filename: the name of the project file to be checked periodically for size more than zero
  9884. :param should_quit: will quit the app if True; boolean
  9885. :return:
  9886. """
  9887. try:
  9888. if os.stat(filename).st_size > 0:
  9889. self.save_in_progress = False
  9890. self.save_timer.stop()
  9891. if should_quit:
  9892. self.app_quit.emit()
  9893. except Exception:
  9894. traceback.print_exc()
  9895. def on_plotarea_tab_closed(self, tab_idx):
  9896. widget = self.ui.plot_tab_area.widget(tab_idx)
  9897. if widget is not None:
  9898. widget.deleteLater()
  9899. self.ui.plot_tab_area.removeTab(tab_idx)
  9900. def on_options_app2project(self):
  9901. """
  9902. Callback for Options->Transfer Options->App=>Project. Copies options
  9903. from application defaults to project defaults.
  9904. :return: None
  9905. """
  9906. self.report_usage("on_options_app2project")
  9907. self.defaults_read_form()
  9908. self.options.update(self.defaults)
  9909. # self.options_write_form()
  9910. class ArgsThread(QtCore.QObject):
  9911. open_signal = pyqtSignal(list)
  9912. start = pyqtSignal()
  9913. if sys.platform == 'win32':
  9914. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  9915. else:
  9916. address = ('/tmp/testipc', 'AF_UNIX')
  9917. def __init__(self):
  9918. super(ArgsThread, self).__init__()
  9919. self.start.connect(self.run)
  9920. def my_loop(self, address):
  9921. try:
  9922. listener = Listener(*address)
  9923. while True:
  9924. conn = listener.accept()
  9925. self.serve(conn)
  9926. except socket.error:
  9927. conn = Client(*address)
  9928. conn.send(sys.argv)
  9929. conn.send('close')
  9930. # close the current instance only if there are args
  9931. if len(sys.argv) > 1:
  9932. sys.exit()
  9933. def serve(self, conn):
  9934. while True:
  9935. msg = conn.recv()
  9936. if msg == 'close':
  9937. break
  9938. self.open_signal.emit(msg)
  9939. conn.close()
  9940. # the decorator is a must; without it this technique will not work unless the start signal is connected
  9941. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  9942. @pyqtSlot()
  9943. def run(self):
  9944. self.my_loop(self.address)
  9945. class GracefulException(Exception):
  9946. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  9947. def __init__(self):
  9948. super().__init__()
  9949. def __str__(self):
  9950. return '\n\n%s' % _("The user requested a graceful exit of the current task.")
  9951. # end of file