FlatCAMApp.py 528 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ###########################################################
  8. import urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import threading
  16. import shutil
  17. from stat import S_IREAD, S_IRGRP, S_IROTH
  18. import subprocess
  19. import ctypes
  20. import tkinter as tk
  21. from PyQt5 import QtPrintSupport
  22. from contextlib import contextmanager
  23. import gc
  24. from xml.dom.minidom import parseString as parse_xml_string
  25. from multiprocessing.connection import Listener, Client
  26. from multiprocessing import Pool
  27. import socket
  28. from array import array
  29. # #######################################
  30. # # Imports part of FlatCAM ##
  31. # #######################################
  32. from ObjectCollection import *
  33. from FlatCAMObj import *
  34. from flatcamGUI.PlotCanvas import *
  35. from flatcamGUI.PlotCanvasLegacy import *
  36. from flatcamGUI.FlatCAMGUI import *
  37. from FlatCAMCommon import LoudDict
  38. from FlatCAMPostProc import load_postprocessors
  39. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  40. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  41. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  42. from FlatCAMProcess import *
  43. from FlatCAMWorkerStack import WorkerStack
  44. from flatcamGUI.VisPyVisuals import Color
  45. from vispy.gloo.util import _screenshot
  46. from vispy.io import write_png
  47. from flatcamTools import *
  48. import tclCommands
  49. import gettext
  50. import FlatCAMTranslation as fcTranslate
  51. import builtins
  52. if sys.platform == 'win32':
  53. import winreg
  54. fcTranslate.apply_language('strings')
  55. if '_' not in builtins.__dict__:
  56. _ = gettext.gettext
  57. # ########################################
  58. # # App ###
  59. # ########################################
  60. class App(QtCore.QObject):
  61. """
  62. The main application class. The constructor starts the GUI.
  63. """
  64. # Get Cmd Line Options
  65. cmd_line_shellfile = ''
  66. cmd_line_shellvar = ''
  67. cmd_line_headless = None
  68. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  69. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  70. "FlatCam.py --headless=1"
  71. try:
  72. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  73. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  74. "shellvar=",
  75. "headless=",
  76. "multiprocessing-fork="])
  77. except getopt.GetoptError:
  78. print(cmd_line_help)
  79. sys.exit(2)
  80. for opt, arg in cmd_line_options:
  81. if opt == '-h':
  82. print(cmd_line_help)
  83. sys.exit()
  84. elif opt == '--shellfile':
  85. cmd_line_shellfile = arg
  86. elif opt == '--shellvar':
  87. cmd_line_shellvar = arg
  88. elif opt == '--headless':
  89. try:
  90. cmd_line_headless = eval(arg)
  91. except NameError:
  92. pass
  93. # ## Logging ###
  94. log = logging.getLogger('base')
  95. log.setLevel(logging.DEBUG)
  96. # log.setLevel(logging.WARNING)
  97. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  98. handler = logging.StreamHandler()
  99. handler.setFormatter(formatter)
  100. log.addHandler(handler)
  101. # ##########################################################################
  102. # ################## Version and VERSION DATE ##############################
  103. # ##########################################################################
  104. version = 8.98
  105. version_date = "2019/10/7"
  106. beta = True
  107. engine = '3D'
  108. # current date now
  109. date = str(datetime.today()).rpartition('.')[0]
  110. date = ''.join(c for c in date if c not in ':-')
  111. date = date.replace(' ', '_')
  112. # URL for update checks and statistics
  113. version_url = "http://flatcam.org/version"
  114. # App URL
  115. app_url = "http://flatcam.org"
  116. # Manual URL
  117. manual_url = "http://flatcam.org/manual/index.html"
  118. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  119. gerber_spec_url ="https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  120. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  121. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  122. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  123. # this variable will hold the project status
  124. # if True it will mean that the project was modified and not saved
  125. should_we_save = False
  126. # flag is True if saving action has been triggered
  127. save_in_progress = False
  128. # ###########################################################################
  129. # ############################# Signals ################################
  130. # ###########################################################################
  131. # Inform the user
  132. # Handled by:
  133. # * App.info() --> Print on the status bar
  134. inform = QtCore.pyqtSignal(str)
  135. app_quit = QtCore.pyqtSignal()
  136. # General purpose background task
  137. worker_task = QtCore.pyqtSignal(dict)
  138. # File opened
  139. # Handled by:
  140. # * register_folder()
  141. # * register_recent()
  142. # Note: Setting the parameters to unicode does not seem
  143. # to have an effect. Then are received as Qstring
  144. # anyway.
  145. # File type and filename
  146. file_opened = QtCore.pyqtSignal(str, str)
  147. # File type and filename
  148. file_saved = QtCore.pyqtSignal(str, str)
  149. # Percentage of progress
  150. progress = QtCore.pyqtSignal(int)
  151. plots_updated = QtCore.pyqtSignal()
  152. # Emitted by new_object() and passes the new object as argument, plot flag.
  153. # on_object_created() adds the object to the collection, plots on appropriate flag
  154. # and emits new_object_available.
  155. object_created = QtCore.pyqtSignal(object, bool, bool)
  156. # Emitted when a object has been changed (like scaled, mirrored)
  157. object_changed = QtCore.pyqtSignal(object)
  158. # Emitted after object has been plotted.
  159. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  160. object_plotted = QtCore.pyqtSignal(object)
  161. # Emitted when a new object has been added or deleted from/to the collection
  162. object_status_changed = QtCore.pyqtSignal(object, str)
  163. message = QtCore.pyqtSignal(str, str, str)
  164. # Emmited when shell command is finished(one command only)
  165. shell_command_finished = QtCore.pyqtSignal(object)
  166. # Emitted when multiprocess pool has been recreated
  167. pool_recreated = QtCore.pyqtSignal(object)
  168. # Emitted when an unhandled exception happens
  169. # in the worker task.
  170. thread_exception = QtCore.pyqtSignal(object)
  171. # used to signal that there are arguments for the app
  172. args_at_startup = QtCore.pyqtSignal(list)
  173. # a reusable signal to replot a list of objects
  174. # should be disconnected after use so it can be reused
  175. replot_signal = pyqtSignal(list)
  176. def __init__(self, user_defaults=True, post_gui=None):
  177. """
  178. Starts the application.
  179. :return: app
  180. :rtype: App
  181. """
  182. App.log.info("FlatCAM Starting...")
  183. self.main_thread = QtWidgets.QApplication.instance().thread()
  184. # ############################################################################
  185. # # ################# OS-specific ############################################
  186. # ############################################################################
  187. portable = False
  188. # Folder for user settings.
  189. if sys.platform == 'win32':
  190. # #########################################################################
  191. # Setup the listening thread for another instance launching with args #####
  192. # #########################################################################
  193. # make sure the thread is stored by using a self. otherwise it's garbage collected
  194. self.th = QtCore.QThread()
  195. self.th.start(priority=QtCore.QThread.LowestPriority)
  196. self.new_launch = ArgsThread()
  197. self.new_launch.open_signal[list].connect(self.on_startup_args)
  198. self.new_launch.moveToThread(self.th)
  199. self.new_launch.start.emit()
  200. from win32com.shell import shell, shellcon
  201. if platform.architecture()[0] == '32bit':
  202. App.log.debug("Win32!")
  203. else:
  204. App.log.debug("Win64!")
  205. # #########################################################################
  206. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  207. # #########################################################################
  208. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  209. try:
  210. with open(config_file, 'r'):
  211. pass
  212. except FileNotFoundError:
  213. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  214. try:
  215. with open(config_file, 'r') as f:
  216. try:
  217. for line in f:
  218. param = str(line).replace('\n', '').rpartition('=')
  219. if param[0] == 'portable':
  220. try:
  221. portable = eval(param[2])
  222. except NameError:
  223. portable = False
  224. if param[0] == 'headless':
  225. if param[2].lower() == 'true':
  226. self.cmd_line_headless = 1
  227. else:
  228. self.cmd_line_headless = None
  229. except Exception as e:
  230. log.debug('App.__init__() -->%s' % str(e))
  231. return
  232. except FileNotFoundError as e:
  233. log.debug(str(e))
  234. pass
  235. if portable is False:
  236. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  237. else:
  238. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  239. self.os = 'windows'
  240. else: # Linux/Unix/MacOS
  241. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  242. self.os = 'unix'
  243. # ##########################################################################
  244. # ################## Setup folders and files ###############################
  245. # ##########################################################################
  246. if not os.path.exists(self.data_path):
  247. os.makedirs(self.data_path)
  248. App.log.debug('Created data folder: ' + self.data_path)
  249. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  250. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  251. self.postprocessorpaths = os.path.join(self.data_path, 'postprocessors')
  252. if not os.path.exists(self.postprocessorpaths):
  253. os.makedirs(self.postprocessorpaths)
  254. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  255. # create current_defaults.FlatConfig file if there is none
  256. try:
  257. f = open(self.data_path + '/current_defaults.FlatConfig')
  258. f.close()
  259. except IOError:
  260. App.log.debug('Creating empty current_defaults.FlatConfig')
  261. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  262. json.dump({}, f)
  263. f.close()
  264. # create factory_defaults.FlatConfig file if there is none
  265. try:
  266. f = open(self.data_path + '/factory_defaults.FlatConfig')
  267. f.close()
  268. except IOError:
  269. App.log.debug('Creating empty factory_defaults.FlatConfig')
  270. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  271. json.dump({}, f)
  272. f.close()
  273. # create a recent files json file if there is none
  274. try:
  275. f = open(self.data_path + '/recent.json')
  276. f.close()
  277. except IOError:
  278. App.log.debug('Creating empty recent.json')
  279. f = open(self.data_path + '/recent.json', 'w')
  280. json.dump([], f)
  281. f.close()
  282. # create a recent projects json file if there is none
  283. try:
  284. fp = open(self.data_path + '/recent_projects.json')
  285. fp.close()
  286. except IOError:
  287. App.log.debug('Creating empty recent_projects.json')
  288. fp = open(self.data_path + '/recent_projects.json', 'w')
  289. json.dump([], fp)
  290. fp.close()
  291. # Application directory. CHDIR to it. Otherwise, trying to load
  292. # GUI icons will fail as their path is relative.
  293. # This will fail under cx_freeze ...
  294. self.app_home = os.path.dirname(os.path.realpath(__file__))
  295. App.log.debug("Application path is " + self.app_home)
  296. App.log.debug("Started in " + os.getcwd())
  297. # cx_freeze workaround
  298. if os.path.isfile(self.app_home):
  299. self.app_home = os.path.dirname(self.app_home)
  300. os.chdir(self.app_home)
  301. # #############################################################################
  302. # ##################### CREATE MULTIPROCESSING POOL ###########################
  303. # #############################################################################
  304. self.pool = Pool()
  305. # ##########################################################################
  306. # ################## Setting the Splash Screen #############################
  307. # ##########################################################################
  308. settings = QSettings("Open Source", "FlatCAM")
  309. if settings.contains("splash_screen"):
  310. show_splash = settings.value("splash_screen")
  311. else:
  312. settings.setValue('splash_screen', 1)
  313. # This will write the setting to the platform specific storage.
  314. del settings
  315. show_splash = 1
  316. if show_splash and self.cmd_line_headless != 1:
  317. splash_pix = QtGui.QPixmap('share/splash.png')
  318. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  319. # self.splash.setMask(splash_pix.mask())
  320. # move splashscreen to the current monitor
  321. desktop = QtWidgets.QApplication.desktop()
  322. screen = desktop.screenNumber(QtGui.QCursor.pos())
  323. current_screen_center = desktop.availableGeometry(screen).center()
  324. self.splash.move(current_screen_center - self.splash.rect().center())
  325. self.splash.show()
  326. self.splash.showMessage(_("FlatCAM is initializing ..."),
  327. alignment=Qt.AlignBottom | Qt.AlignLeft,
  328. color=QtGui.QColor("gray"))
  329. else:
  330. show_splash = 0
  331. # #############################################################################
  332. # ##################### Initialize GUI ########################################
  333. # #############################################################################
  334. # FlatCAM colors used in plotting
  335. self.FC_light_green = '#BBF268BF'
  336. self.FC_dark_green = '#006E20BF'
  337. self.FC_light_blue = '#a5a5ffbf'
  338. self.FC_dark_blue = '#0000ffbf'
  339. QtCore.QObject.__init__(self)
  340. self.ui = FlatCAMGUI(self.version, self.beta, self)
  341. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  342. self.ui.final_save.connect(self.final_save)
  343. # #############################################################################
  344. # ############################## Data #########################################
  345. # #############################################################################
  346. self.recent = []
  347. self.recent_projects = []
  348. self.clipboard = QtWidgets.QApplication.clipboard()
  349. self.project_filename = None
  350. self.toggle_units_ignore = False
  351. # self.defaults_form = PreferencesUI()
  352. # when adding entries here read the comments in the method found bellow named:
  353. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  354. self.defaults_form_fields = {
  355. # General App
  356. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  357. "global_graphic_engine": self.ui.general_defaults_form.general_app_group.ge_radio,
  358. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  359. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  360. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  361. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  362. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  363. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  364. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  365. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  366. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  367. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  368. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  369. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  370. # General GUI Preferences
  371. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  372. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  373. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  374. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  375. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  376. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  377. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  378. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  379. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  380. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  381. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  382. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  383. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  384. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  385. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  386. "global_activity_icon": self.ui.general_defaults_form.general_gui_group.activity_combo,
  387. # General GUI Settings
  388. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  389. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  390. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  391. "global_systray_icon": self.ui.general_defaults_form.general_gui_set_group.systray_cb,
  392. "global_shell_at_startup": self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb,
  393. "global_project_at_startup": self.ui.general_defaults_form.general_gui_set_group.project_startup_cb,
  394. "global_project_autohide": self.ui.general_defaults_form.general_gui_set_group.project_autohide_cb,
  395. "global_toggle_tooltips": self.ui.general_defaults_form.general_gui_set_group.toggle_tooltips_cb,
  396. "global_delete_confirmation": self.ui.general_defaults_form.general_gui_set_group.delete_conf_cb,
  397. "global_cursor_type": self.ui.general_defaults_form.general_gui_set_group.cursor_radio,
  398. "global_cursor_size": self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry,
  399. # Gerber General
  400. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  401. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  402. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  403. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  404. # Gerber Options
  405. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  406. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  407. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  408. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  409. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  410. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  411. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  412. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  413. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  414. # Gerber Advanced Options
  415. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  416. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  417. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  418. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  419. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  420. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  421. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  422. # Gerber Export
  423. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  424. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  425. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  426. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  427. # Gerber Editor
  428. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  429. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  430. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  431. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  432. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  433. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  434. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  435. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  436. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  437. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  438. "gerber_editor_circ_angle":
  439. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  440. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  441. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  442. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  443. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  444. # Excellon General
  445. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  446. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  447. "excellon_format_upper_in":
  448. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  449. "excellon_format_lower_in":
  450. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  451. "excellon_format_upper_mm":
  452. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  453. "excellon_format_lower_mm":
  454. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  455. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  456. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  457. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  458. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  459. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  460. # Excellon Options
  461. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  462. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  463. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.eendz_entry,
  464. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  465. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  466. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  467. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  468. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  469. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  470. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  471. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  472. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  473. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  474. # Excellon Advanced Options
  475. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  476. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  477. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  478. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  479. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  480. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  481. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  482. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  483. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  484. # Excellon Export
  485. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  486. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  487. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  488. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  489. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  490. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  491. # Excellon Editor
  492. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  493. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  494. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  495. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  496. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  497. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  498. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  499. "excellon_editor_circ_angle":
  500. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  501. # Excellon Slots
  502. "excellon_editor_slot_direction":
  503. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  504. "excellon_editor_slot_angle":
  505. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  506. "excellon_editor_slot_length":
  507. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  508. # Excellon Slots
  509. "excellon_editor_slot_array_size":
  510. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  511. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  512. "excellon_editor_slot_lin_pitch":
  513. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  514. "excellon_editor_slot_lin_angle":
  515. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  516. "excellon_editor_slot_circ_dir":
  517. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  518. "excellon_editor_slot_circ_angle":
  519. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  520. # Geometry General
  521. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  522. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  523. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  524. # Geometry Options
  525. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  526. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  527. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  528. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  529. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  530. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  531. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  532. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  533. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  534. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  535. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.gendz_entry,
  536. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  537. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  538. # Geometry Advanced Options
  539. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  540. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  541. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  542. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  543. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  544. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  545. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  546. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  547. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  548. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  549. # Geometry Editor
  550. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  551. "geometry_editor_milling_type": self.ui.geometry_defaults_form.geometry_editor_group.milling_type_radio,
  552. # CNCJob General
  553. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  554. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  555. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  556. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  557. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  558. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  559. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  560. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  561. # CNC Job Options
  562. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  563. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  564. # CNC Job Advanced Options
  565. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  566. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  567. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  568. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  569. # NCC Tool
  570. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  571. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  572. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  573. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  574. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  575. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  576. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  577. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  578. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  579. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  580. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  581. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  582. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  583. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  584. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  585. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  586. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  587. # CutOut Tool
  588. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  589. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  590. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  591. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  592. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  593. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  594. # Paint Area Tool
  595. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  596. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  597. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  598. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  599. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  600. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  601. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  602. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  603. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  604. # 2-sided Tool
  605. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  606. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  607. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  608. # Film Tool
  609. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  610. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  611. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  612. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  613. # Panelize Tool
  614. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  615. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  616. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  617. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  618. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  619. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  620. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  621. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  622. # Calculators Tool
  623. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  624. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  625. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  626. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  627. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  628. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  629. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  630. # Transformations Tool
  631. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  632. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  633. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  634. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  635. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  636. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  637. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  638. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  639. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  640. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  641. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  642. # SolderPaste Dispensing Tool
  643. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  644. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  645. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  646. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  647. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  648. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  649. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  650. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  651. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  652. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  653. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  654. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  655. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  656. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  657. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  658. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  659. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  660. # Utilities
  661. # File associations
  662. "fa_excellon": self.ui.util_defaults_form.fa_excellon_group.exc_list_text,
  663. "fa_gcode": self.ui.util_defaults_form.fa_gcode_group.gco_list_text,
  664. # "fa_geometry": self.ui.util_defaults_form.fa_geometry_group.close_paths_cb,
  665. "fa_gerber": self.ui.util_defaults_form.fa_gerber_group.grb_list_text,
  666. "util_autocomplete_keywords": self.ui.util_defaults_form.kw_group.kw_list_text,
  667. }
  668. # ############################
  669. # ### LOAD POSTPROCESSORS ####
  670. # ############################
  671. self.postprocessors = load_postprocessors(self)
  672. for name in list(self.postprocessors.keys()):
  673. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  674. if name.partition('_')[0] == 'Paste':
  675. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  676. continue
  677. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  678. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  679. if name == 'hpgl':
  680. continue
  681. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  682. # ############################
  683. # ### LOAD LANGUAGES ####
  684. # ############################
  685. self.languages = fcTranslate.load_languages()
  686. for name in sorted(self.languages.values()):
  687. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  688. # #################################################################################
  689. # #################### DEFAULTS - PREFERENCES STORAGE #############################
  690. # #################################################################################
  691. self.defaults = LoudDict()
  692. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  693. self.defaults.update({
  694. # Global APP Preferences
  695. "first_run": True,
  696. "units": "IN",
  697. "global_serial": 0,
  698. "global_stats": {},
  699. "global_tabs_detachable": True,
  700. "global_graphic_engine": '3D',
  701. "global_app_level": 'b',
  702. "global_portable": False,
  703. "global_language": 'English',
  704. "global_version_check": True,
  705. "global_send_stats": True,
  706. "global_pan_button": '2',
  707. "global_mselect_key": 'Control',
  708. "global_project_at_startup": False,
  709. "global_systray_icon": True,
  710. "global_project_autohide": True,
  711. "global_toggle_tooltips": True,
  712. "global_worker_number": 2,
  713. "global_tolerance": 0.005,
  714. "global_open_style": True,
  715. "global_delete_confirmation": True,
  716. "global_compression_level": 3,
  717. "global_save_compressed": True,
  718. # Global GUI Preferences
  719. "global_gridx": 0.0393701,
  720. "global_gridy": 0.0393701,
  721. "global_snap_max": 0.001968504,
  722. "global_workspace": False,
  723. "global_workspaceT": "A4P",
  724. "global_grid_context_menu": {
  725. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  726. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  727. },
  728. "global_plot_fill": '#BBF268BF',
  729. "global_plot_line": '#006E20BF',
  730. "global_sel_fill": '#a5a5ffbf',
  731. "global_sel_line": '#0000ffbf',
  732. "global_alt_sel_fill": '#BBF268BF',
  733. "global_alt_sel_line": '#006E20BF',
  734. "global_draw_color": '#FF0000',
  735. "global_sel_draw_color": '#0000FF',
  736. "global_proj_item_color": '#000000',
  737. "global_proj_item_dis_color": '#b7b7cb',
  738. "global_activity_icon": 'Ball green',
  739. "global_toolbar_view": 511,
  740. "global_background_timeout": 300000, # Default value is 5 minutes
  741. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  742. # (python trace only for unknown errors),
  743. # 1 = show trace(show trace always),
  744. # 2 = (For the future).
  745. # Persistence
  746. "global_last_folder": None,
  747. "global_last_save_folder": None,
  748. # Default window geometry
  749. "global_def_win_x": 100,
  750. "global_def_win_y": 100,
  751. "global_def_win_w": 1024,
  752. "global_def_win_h": 650,
  753. "global_def_notebook_width": 1,
  754. # Constants...
  755. "global_defaults_save_period_ms": 20000, # Time between default saves.
  756. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  757. "global_shell_at_startup": False, # Show the shell at startup.
  758. "global_recent_limit": 10, # Max. items in recent list.
  759. "fit_key": 'V',
  760. "zoom_out_key": '-',
  761. "zoom_in_key": '=',
  762. "grid_toggle_key": 'G',
  763. "global_zoom_ratio": 1.5,
  764. "global_point_clipboard_format": "(%.4f, %.4f)",
  765. "global_zdownrate": None,
  766. # General GUI Settings
  767. "global_hover": False,
  768. "global_selection_shape": True,
  769. "global_layout": "compact",
  770. "global_cursor_type": "small",
  771. "global_cursor_size": 20,
  772. # Gerber General
  773. "gerber_plot": True,
  774. "gerber_solid": True,
  775. "gerber_multicolored": False,
  776. "gerber_circle_steps": 128,
  777. "gerber_use_buffer_for_union": True,
  778. # Gerber Options
  779. "gerber_isotooldia": 0.00787402,
  780. "gerber_isopasses": 1,
  781. "gerber_isooverlap": 0.00393701,
  782. "gerber_milling_type": "cl",
  783. "gerber_combine_passes": False,
  784. "gerber_noncoppermargin": 0.00393701,
  785. "gerber_noncopperrounded": False,
  786. "gerber_bboxmargin": 0.00393701,
  787. "gerber_bboxrounded": False,
  788. # Gerber Advanced Options
  789. "gerber_aperture_display": False,
  790. "gerber_aperture_scale_factor": 1.0,
  791. "gerber_aperture_buffer_factor": 0.0,
  792. "gerber_follow": False,
  793. "gerber_buffering": "full",
  794. "gerber_simplification": False,
  795. "gerber_simp_tolerance": 0.0005,
  796. # Gerber Export
  797. "gerber_exp_units": 'IN',
  798. "gerber_exp_integer": 2,
  799. "gerber_exp_decimals": 4,
  800. "gerber_exp_zeros": 'L',
  801. # Gerber Editor
  802. "gerber_editor_sel_limit": 30,
  803. "gerber_editor_newcode": 10,
  804. "gerber_editor_newsize": 0.8,
  805. "gerber_editor_newtype": 'C',
  806. "gerber_editor_newdim": "0.5, 0.5",
  807. "gerber_editor_array_size": 5,
  808. "gerber_editor_lin_axis": 'X',
  809. "gerber_editor_lin_pitch": 1,
  810. "gerber_editor_lin_angle": 0.0,
  811. "gerber_editor_circ_dir": 'CW',
  812. "gerber_editor_circ_angle": 0.0,
  813. "gerber_editor_scale_f": 1.0,
  814. "gerber_editor_buff_f": 0.1,
  815. "gerber_editor_ma_low": 0.0,
  816. "gerber_editor_ma_high": 1.0,
  817. # Excellon General
  818. "excellon_plot": True,
  819. "excellon_solid": True,
  820. "excellon_format_upper_in": 2,
  821. "excellon_format_lower_in": 4,
  822. "excellon_format_upper_mm": 3,
  823. "excellon_format_lower_mm": 3,
  824. "excellon_zeros": "L",
  825. "excellon_units": "INCH",
  826. "excellon_update": True,
  827. "excellon_optimization_type": 'B',
  828. "excellon_search_time": 3,
  829. # Excellon Options
  830. "excellon_drillz": -0.0590551,
  831. "excellon_travelz": 0.0787402,
  832. "excellon_endz": 0.5,
  833. "excellon_feedrate": 3.14961,
  834. "excellon_spindlespeed": None,
  835. "excellon_dwell": False,
  836. "excellon_dwelltime": 1,
  837. "excellon_toolchange": False,
  838. "excellon_toolchangez": 0.5,
  839. "excellon_ppname_e": 'default',
  840. "excellon_tooldia": 0.0314961,
  841. "excellon_slot_tooldia": 0.0708661,
  842. "excellon_gcode_type": "drills",
  843. # Excellon Advanced Options
  844. "excellon_offset": 0.0,
  845. "excellon_toolchangexy": "0.0, 0.0",
  846. "excellon_startz": None,
  847. "excellon_feedrate_rapid": 31.4961,
  848. "excellon_z_pdepth": -0.02,
  849. "excellon_feedrate_probe": 3.14961,
  850. "excellon_spindledir": 'CW',
  851. "excellon_f_plunge": False,
  852. "excellon_f_retract": False,
  853. # Excellon Export
  854. "excellon_exp_units": 'INCH',
  855. "excellon_exp_format": 'ndec',
  856. "excellon_exp_integer": 2,
  857. "excellon_exp_decimals": 4,
  858. "excellon_exp_zeros": 'LZ',
  859. "excellon_exp_slot_type": 'routing',
  860. # Excellon Editor
  861. "excellon_editor_sel_limit": 30,
  862. "excellon_editor_newdia": 0.039,
  863. "excellon_editor_array_size": 5,
  864. "excellon_editor_lin_dir": 'X',
  865. "excellon_editor_lin_pitch": 0.1,
  866. "excellon_editor_lin_angle": 0.0,
  867. "excellon_editor_circ_dir": 'CW',
  868. "excellon_editor_circ_angle": 12,
  869. # Excellon Slots
  870. "excellon_editor_slot_direction": 'X',
  871. "excellon_editor_slot_angle": 0.0,
  872. "excellon_editor_slot_length": 5.0,
  873. # Excellon Slot Array
  874. "excellon_editor_slot_array_size": 5,
  875. "excellon_editor_slot_lin_dir": 'X',
  876. "excellon_editor_slot_lin_pitch": 0.1,
  877. "excellon_editor_slot_lin_angle": 0.0,
  878. "excellon_editor_slot_circ_dir": 'CW',
  879. "excellon_editor_slot_circ_angle": 0.0,
  880. # Geometry General
  881. "geometry_plot": True,
  882. "geometry_circle_steps": 128,
  883. "geometry_cnctooldia": "0.0944882",
  884. # Geometry Options
  885. "geometry_cutz": -0.0944882,
  886. "geometry_vtipdia": 0.1,
  887. "geometry_vtipangle": 30,
  888. "geometry_multidepth": False,
  889. "geometry_depthperpass": 0.0314961,
  890. "geometry_travelz": 0.0787402,
  891. "geometry_toolchange": False,
  892. "geometry_toolchangez": 0.5,
  893. "geometry_endz": 0.5,
  894. "geometry_feedrate": 3.14961,
  895. "geometry_feedrate_z": 3.14961,
  896. "geometry_spindlespeed": None,
  897. "geometry_dwell": False,
  898. "geometry_dwelltime": 1,
  899. "geometry_ppname_g": 'default',
  900. # Geometry Advanced Options
  901. "geometry_toolchangexy": "0.0, 0.0",
  902. "geometry_startz": None,
  903. "geometry_feedrate_rapid": 3.14961,
  904. "geometry_extracut": False,
  905. "geometry_z_pdepth": -0.02,
  906. "geometry_f_plunge": False,
  907. "geometry_spindledir": 'CW',
  908. "geometry_feedrate_probe": 3.14961,
  909. "geometry_segx": 0.0,
  910. "geometry_segy": 0.0,
  911. # Geometry Editor
  912. "geometry_editor_sel_limit": 30,
  913. "geometry_editor_milling_type": "cl",
  914. # CNC Job General
  915. "cncjob_plot": True,
  916. "cncjob_plot_kind": 'all',
  917. "cncjob_annotation": True,
  918. "cncjob_tooldia": 0.0393701,
  919. "cncjob_coords_type": "G90",
  920. "cncjob_coords_decimals": 4,
  921. "cncjob_fr_decimals": 2,
  922. "cncjob_steps_per_circle": 128,
  923. # CNC Job Options
  924. "cncjob_prepend": "",
  925. "cncjob_append": "",
  926. # CNC Job Advanced Options
  927. "cncjob_toolchange_macro": "",
  928. "cncjob_toolchange_macro_enable": False,
  929. "cncjob_annotation_fontsize": 9,
  930. "cncjob_annotation_fontcolor": '#990000',
  931. # NCC Tool
  932. "tools_ncctools": "0.0393701, 0.019685",
  933. "tools_nccorder": 'rev',
  934. "tools_nccoverlap": 0.015748,
  935. "tools_nccmargin": 0.0393701,
  936. "tools_nccmethod": "seed",
  937. "tools_nccconnect": True,
  938. "tools_ncccontour": True,
  939. "tools_nccrest": False,
  940. "tools_ncc_offset_choice": False,
  941. "tools_ncc_offset_value": 0.0000,
  942. "tools_nccref": 'itself',
  943. "tools_ncc_plotting": 'normal',
  944. "tools_nccmilling_type": 'cl',
  945. "tools_ncctool_type": 'V',
  946. "tools_ncccutz": -0.001968504,
  947. "tools_ncctipdia": 0.00393701,
  948. "tools_ncctipangle": 30,
  949. # Cutout Tool
  950. "tools_cutouttooldia": 0.0944882,
  951. "tools_cutoutkind": "single",
  952. "tools_cutoutmargin": 0.00393701,
  953. "tools_cutoutgapsize": 0.15748,
  954. "tools_gaps_ff": "4",
  955. "tools_cutout_convexshape": False,
  956. # Paint Tool
  957. "tools_painttooldia": 0.023622,
  958. "tools_paintorder": 'rev',
  959. "tools_paintoverlap": 0.015748,
  960. "tools_paintmargin": 0.0,
  961. "tools_paintmethod": "seed",
  962. "tools_selectmethod": "all",
  963. "tools_pathconnect": True,
  964. "tools_paintcontour": True,
  965. "tools_paint_plotting": 'normal',
  966. # 2-Sided Tool
  967. "tools_2sided_mirror_axis": "X",
  968. "tools_2sided_axis_loc": "point",
  969. "tools_2sided_drilldia": 0.11811,
  970. # Film Tool
  971. "tools_film_type": 'neg',
  972. "tools_film_boundary": 0.0393701,
  973. "tools_film_scale": 0,
  974. "tools_film_color": '#000000',
  975. # Panel Tool
  976. "tools_panelize_spacing_columns": 0,
  977. "tools_panelize_spacing_rows": 0,
  978. "tools_panelize_columns": 1,
  979. "tools_panelize_rows": 1,
  980. "tools_panelize_constrain": False,
  981. "tools_panelize_constrainx": 0.0,
  982. "tools_panelize_constrainy": 0.0,
  983. "tools_panelize_panel_type": 'gerber',
  984. # Calculators Tool
  985. "tools_calc_vshape_tip_dia": 0.007874,
  986. "tools_calc_vshape_tip_angle": 30,
  987. "tools_calc_vshape_cut_z": 0.000787,
  988. "tools_calc_electro_length": 10.0,
  989. "tools_calc_electro_width": 10.0,
  990. "tools_calc_electro_cdensity": 13.0,
  991. "tools_calc_electro_growth": 10.0,
  992. # Transform Tool
  993. "tools_transform_rotate": 90,
  994. "tools_transform_skew_x": 0.0,
  995. "tools_transform_skew_y": 0.0,
  996. "tools_transform_scale_x": 1.0,
  997. "tools_transform_scale_y": 1.0,
  998. "tools_transform_scale_link": True,
  999. "tools_transform_scale_reference": True,
  1000. "tools_transform_offset_x": 0.0,
  1001. "tools_transform_offset_y": 0.0,
  1002. "tools_transform_mirror_reference": False,
  1003. "tools_transform_mirror_point": (0, 0),
  1004. # SolderPaste Tool
  1005. "tools_solderpaste_tools": "0.0393701, 0.011811",
  1006. "tools_solderpaste_new": 0.011811,
  1007. "tools_solderpaste_z_start": 0.00019685039,
  1008. "tools_solderpaste_z_dispense": 0.00393701,
  1009. "tools_solderpaste_z_stop": 0.00019685039,
  1010. "tools_solderpaste_z_travel": 0.00393701,
  1011. "tools_solderpaste_z_toolchange": 0.0393701,
  1012. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  1013. "tools_solderpaste_frxy": 3.0,
  1014. "tools_solderpaste_frz": 3.0,
  1015. "tools_solderpaste_frz_dispense": 0.0393701,
  1016. "tools_solderpaste_speedfwd": 20,
  1017. "tools_solderpaste_dwellfwd": 1,
  1018. "tools_solderpaste_speedrev": 10,
  1019. "tools_solderpaste_dwellrev": 1,
  1020. "tools_solderpaste_pp": 'Paste_1',
  1021. # Subtract Tool
  1022. "tools_sub_close_paths": True,
  1023. # Utilities
  1024. # file associations
  1025. "fa_excellon": 'drd, drl, exc, ncd, tap, xln',
  1026. "fa_gcode": 'cnc, din, dnc, ecs, eia, fan, fgc, fnc, gc, gcd, gcode, h, hnc, i, min, mpf, mpr, nc, ncc, '
  1027. 'ncg, ncp, out, plt, ply, rol, sbp, tap, xpi',
  1028. "fa_gerber": 'art, bot, bsm, cmp, crc, crs, dim, g4, gb0, gb1, gb2, gb3, gb5, gb6, gb7, gb8, gb9, gbd, '
  1029. 'gbl, gbo, gbp, gbr, gbs, gdo, ger, gko, gm1, gm2, gm3, grb, gtl, gto, gtp, gts, ly15, ly2, '
  1030. 'mil, pho, plc, pls, smb, smt, sol, spb, spt, ssb, sst, stc, sts, top, tsm',
  1031. # Keyword list
  1032. "util_autocomplete_keywords": 'Desktop, Documents, FlatConfig, FlatPrj, Marius, My Documents, Paste_1, '
  1033. 'Repetier, Roland_MDX_20, Users, Toolchange_Custom, Toolchange_Probe_MACH3, '
  1034. 'Toolchange_manual, Users, all, angle_x, angle_y, axis, auto, axisoffset, '
  1035. 'box, center_x, center_y, columns, combine, connect, contour, default, '
  1036. 'depthperpass, dia, diatol, dist, drilled_dias, drillz, dwell, dwelltime, '
  1037. 'feedrate_z, grbl_11, grbl_laser, gridoffsety, gridx, gridy, has_offset, '
  1038. 'holes, hpgl, iso_type, line_xyz, margin, marlin, method, milled_dias, '
  1039. 'minoffset, multidepth, name, offset, opt_type, order, outname, overlap, '
  1040. 'passes, postamble, pp, ppname_e, ppname_g, preamble, radius, ref, rest, '
  1041. 'rows, shellvar_, scale_factor, spacing_columns, spacing_rows, spindlespeed, '
  1042. 'toolchange_xy, use_threads, value, x, x0, x1, y, y0, y1, z_cut, z_move'
  1043. ,
  1044. })
  1045. # ############################################################
  1046. # ############### Load defaults from file ####################
  1047. # ############################################################
  1048. if user_defaults:
  1049. self.load_defaults(filename='current_defaults')
  1050. # #############################################################
  1051. # ############## APPLY APP LANGUAGE ###########################
  1052. # #############################################################
  1053. ret_val = fcTranslate.apply_language('strings')
  1054. if ret_val == "no language":
  1055. self.inform.emit('[ERROR] %s' %
  1056. _("Could not find the Language files. The App strings are missing."))
  1057. log.debug("Could not find the Language files. The App strings are missing.")
  1058. else:
  1059. # make the current language the current selection on the language combobox
  1060. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1061. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1062. # ##############################################################
  1063. # ################# CREATE UNIQUE SERIAL NUMBER ################
  1064. # ##############################################################
  1065. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1066. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1067. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  1068. self.save_defaults(silent=True, first_time=True)
  1069. self.propagate_defaults(silent=True)
  1070. self.restore_main_win_geom()
  1071. # def auto_save_defaults():
  1072. # try:
  1073. # self.save_defaults(silent=True)
  1074. # self.propagate_defaults(silent=True)
  1075. # finally:
  1076. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1077. # the following lines activates automatic defaults save
  1078. # if user_defaults:
  1079. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1080. # self.options_form = PreferencesUI()
  1081. self.options_form_fields = {
  1082. "units": self.ui.general_options_form.general_app_group.units_radio,
  1083. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  1084. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  1085. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  1086. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  1087. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  1088. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  1089. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  1090. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  1091. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  1092. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  1093. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  1094. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  1095. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  1096. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  1097. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  1098. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  1099. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  1100. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  1101. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  1102. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  1103. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  1104. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  1105. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  1106. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  1107. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  1108. "excellon_endz": self.ui.excellon_options_form.excellon_opt_group.eendz_entry,
  1109. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  1110. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  1111. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  1112. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  1113. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  1114. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  1115. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  1116. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  1117. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1118. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  1119. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  1120. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  1121. "excellon_spindledir": self.ui.excellon_options_form.excellon_adv_opt_group.spindledir_radio,
  1122. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  1123. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  1124. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  1125. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  1126. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  1127. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  1128. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  1129. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  1130. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  1131. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  1132. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  1133. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  1134. "geometry_endz": self.ui.geometry_options_form.geometry_opt_group.gendz_entry,
  1135. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  1136. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  1137. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  1138. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  1139. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1140. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  1141. "geometry_spindledir": self.ui.geometry_options_form.geometry_adv_opt_group.spindledir_radio,
  1142. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  1143. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  1144. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  1145. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  1146. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  1147. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  1148. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  1149. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  1150. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  1151. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  1152. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  1153. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  1154. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  1155. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  1156. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  1157. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  1158. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  1159. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  1160. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  1161. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  1162. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  1163. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  1164. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  1165. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  1166. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  1167. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  1168. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  1169. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  1170. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  1171. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  1172. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  1173. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  1174. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  1175. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  1176. }
  1177. for name in list(self.postprocessors.keys()):
  1178. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1179. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1180. self.options = LoudDict()
  1181. self.options.set_change_callback(self.on_options_dict_change)
  1182. self.options.update({
  1183. "units": "IN",
  1184. "global_gridx": 1.0,
  1185. "global_gridy": 1.0,
  1186. "global_snap_max": 0.05,
  1187. "global_background_timeout": 300000, # Default value is 5 minutes
  1188. "global_verbose_error_level": 0, # Shell verbosity:
  1189. # 0 = default(python trace only for unknown errors),
  1190. # 1 = show trace(show trace allways), 2 = (For the future).
  1191. "gerber_plot": True,
  1192. "gerber_solid": True,
  1193. "gerber_multicolored": False,
  1194. "gerber_isotooldia": 0.016,
  1195. "gerber_isopasses": 1,
  1196. "gerber_isooverlap": 0.15,
  1197. "gerber_combine_passes": True,
  1198. "gerber_noncoppermargin": 0.0,
  1199. "gerber_noncopperrounded": False,
  1200. "gerber_bboxmargin": 0.0,
  1201. "gerber_bboxrounded": False,
  1202. "excellon_plot": True,
  1203. "excellon_solid": False,
  1204. "excellon_format_upper_in": 2,
  1205. "excellon_format_lower_in": 4,
  1206. "excellon_format_upper_mm": 3,
  1207. "excellon_format_lower_mm": 3,
  1208. "excellon_units": 'INCH',
  1209. "excellon_optimization_type": 'B',
  1210. "excellon_search_time": 3,
  1211. "excellon_zeros": "L",
  1212. "excellon_drillz": -0.1,
  1213. "excellon_travelz": 0.1,
  1214. "excellon_feedrate": 3.0,
  1215. "excellon_feedrate_rapid": 3.0,
  1216. "excellon_spindlespeed": None,
  1217. "excellon_spindledir": 'CW',
  1218. "excellon_dwell": True,
  1219. "excellon_dwelltime": 1000,
  1220. "excellon_toolchange": False,
  1221. "excellon_toolchangez": 1.0,
  1222. "excellon_toolchangexy": "0.0, 0.0",
  1223. "excellon_tooldia": 0.016,
  1224. "excellon_ppname_e": 'default',
  1225. "excellon_f_plunge": False,
  1226. "excellon_startz": None,
  1227. "excellon_endz": 2.0,
  1228. "geometry_plot": True,
  1229. "geometry_segx": 0.0,
  1230. "geometry_segy": 0.0,
  1231. "geometry_cutz": -0.002,
  1232. "geometry_vtipdia": 0.1,
  1233. "geometry_vtipangle": 30,
  1234. "geometry_travelz": 0.1,
  1235. "geometry_feedrate": 3.0,
  1236. "geometry_feedrate_z": 3.0,
  1237. "geometry_feedrate_rapid": 3.0,
  1238. "geometry_spindlespeed": None,
  1239. "geometry_spindledir": 'CW',
  1240. "geometry_dwell": True,
  1241. "geometry_dwelltime": 1000,
  1242. "geometry_cnctooldia": 0.016,
  1243. "geometry_toolchange": False,
  1244. "geometry_toolchangez": 2.0,
  1245. "geometry_toolchangexy": "0.0, 0.0",
  1246. "geometry_startz": None,
  1247. "geometry_endz": 2.0,
  1248. "geometry_ppname_g": "default",
  1249. "geometry_f_plunge": False,
  1250. "geometry_depthperpass": 0.002,
  1251. "geometry_multidepth": False,
  1252. "geometry_extracut": False,
  1253. "cncjob_plot": True,
  1254. "cncjob_tooldia": 0.016,
  1255. "cncjob_prepend": "",
  1256. "cncjob_append": "",
  1257. "tools_ncctools": "1.0, 0.5",
  1258. "tools_nccoverlap": 0.4,
  1259. "tools_nccmargin": 1,
  1260. "tools_cutouttooldia": 0.07,
  1261. "tools_cutoutmargin": 0.1,
  1262. "tools_cutoutgapsize": 0.15,
  1263. "tools_gaps_ff": "8",
  1264. "tools_painttooldia": 0.07,
  1265. "tools_paintoverlap": 0.15,
  1266. "tools_paintmargin": 0.0,
  1267. "tools_paintmethod": "seed",
  1268. "tools_selectmethod": "single",
  1269. "tools_pathconnect": True,
  1270. "tools_paintcontour": True,
  1271. "tools_2sided_mirror_axis": "X",
  1272. "tools_2sided_axis_loc": 'point',
  1273. "tools_2sided_drilldia": 1,
  1274. "tools_film_type": 'neg',
  1275. "tools_film_boundary": 1,
  1276. "tools_film_scale": 0,
  1277. "tools_panelize_spacing_columns": 0,
  1278. "tools_panelize_spacing_rows": 0,
  1279. "tools_panelize_columns": 1,
  1280. "tools_panelize_rows": 1,
  1281. "tools_panelize_constrain": False,
  1282. "tools_panelize_constrainx": 0.0,
  1283. "tools_panelize_constrainy": 0.0
  1284. })
  1285. self.options.update(self.defaults) # Copy app defaults to project options
  1286. self.gen_form = None
  1287. self.ger_form = None
  1288. self.exc_form = None
  1289. self.geo_form = None
  1290. self.cnc_form = None
  1291. self.tools_form = None
  1292. self.fa_form = None
  1293. self.on_options_combo_change(0) # Will show the initial form
  1294. # ################################
  1295. # ### Initialize the color box's color in Preferences -> Global -> Color
  1296. # Init Plot Colors
  1297. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  1298. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  1299. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  1300. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  1301. int(self.defaults['global_plot_fill'][7:9], 16))
  1302. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  1303. int(self.defaults['global_plot_fill'][7:9], 16))
  1304. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  1305. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  1306. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  1307. # Init Left-Right Selection colors
  1308. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  1309. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  1310. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  1311. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1312. int(self.defaults['global_sel_fill'][7:9], 16))
  1313. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1314. int(self.defaults['global_sel_fill'][7:9], 16))
  1315. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1316. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1317. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  1318. # Init Right-Left Selection colors
  1319. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1320. self.defaults['global_alt_sel_fill'])
  1321. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1322. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  1323. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1324. int(self.defaults['global_sel_fill'][7:9], 16))
  1325. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1326. int(self.defaults['global_sel_fill'][7:9], 16))
  1327. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1328. self.defaults['global_alt_sel_line'])
  1329. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1330. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  1331. # Init Draw color and Selection Draw Color
  1332. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1333. self.defaults['global_draw_color'])
  1334. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1335. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1336. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1337. self.defaults['global_sel_draw_color'])
  1338. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1339. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1340. # Init Project Items color
  1341. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1342. self.defaults['global_proj_item_color'])
  1343. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1344. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1345. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1346. self.defaults['global_proj_item_dis_color'])
  1347. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1348. "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1349. # Init the Annotation CNC Job color
  1350. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  1351. self.defaults['cncjob_annotation_fontcolor'])
  1352. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  1353. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  1354. # Init the Tool Film color
  1355. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  1356. self.defaults['tools_film_color'])
  1357. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  1358. "background-color:%s" % str(self.defaults['tools_film_color'])[:7])
  1359. # ### End of Data ####
  1360. # ##############################################
  1361. # ######### SETUP OBJECT COLLECTION ############
  1362. # ##############################################
  1363. self.collection = ObjectCollection(self)
  1364. self.ui.project_tab_layout.addWidget(self.collection.view)
  1365. # ### Adjust tabs width ## ##
  1366. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1367. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1368. self.collection.view.setMinimumWidth(290)
  1369. self.log.debug("Finished creating Object Collection.")
  1370. # ###############################################
  1371. # ############# SETUP Plot Area #################
  1372. # ###############################################
  1373. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  1374. if self.defaults["global_graphic_engine"] == '3D':
  1375. self.is_legacy = False
  1376. else:
  1377. self.is_legacy = True
  1378. # Matplotlib axis
  1379. self.axes = None
  1380. if show_splash:
  1381. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1382. "Canvas initialization started."),
  1383. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1384. color=QtGui.QColor("gray"))
  1385. start_plot_time = time.time() # debug
  1386. self.plotcanvas = None
  1387. self.app_cursor = None
  1388. self.hover_shapes = None
  1389. self.on_plotcanvas_setup()
  1390. end_plot_time = time.time()
  1391. self.used_time = end_plot_time - start_plot_time
  1392. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1393. if show_splash:
  1394. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1395. "Canvas initialization started.\n"
  1396. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1397. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1398. color=QtGui.QColor("gray"))
  1399. self.ui.splitter.setStretchFactor(1, 2)
  1400. # #################################################################
  1401. # ####################### SYS TRAY ################################
  1402. # #################################################################
  1403. if self.defaults["global_systray_icon"]:
  1404. self.parent_w = QtWidgets.QWidget()
  1405. if self.cmd_line_headless == 1:
  1406. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1407. headless=True,
  1408. parent=self.parent_w)
  1409. else:
  1410. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1411. parent=self.parent_w)
  1412. # ###############################################
  1413. # ############# Worker SETUP ####################
  1414. # ###############################################
  1415. if self.defaults["global_worker_number"]:
  1416. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1417. else:
  1418. self.workers = WorkerStack(workers_number=2)
  1419. self.worker_task.connect(self.workers.add_task)
  1420. self.log.debug("Finished creating Workers crew.")
  1421. # ################################################
  1422. # ############### Activity Monitor ###############
  1423. # ################################################
  1424. if self.defaults["global_activity_icon"] == "Ball green":
  1425. icon = 'share/active_2_static.png'
  1426. movie = "share/active_2.gif"
  1427. elif self.defaults["global_activity_icon"] == "Ball black":
  1428. icon = 'share/active_static.png'
  1429. movie = "share/active.gif"
  1430. elif self.defaults["global_activity_icon"] == "Arrow green":
  1431. icon = 'share/active_3_static.png'
  1432. movie = "share/active_3.gif"
  1433. elif self.defaults["global_activity_icon"] == "Eclipse green":
  1434. icon = 'share/active_4_static.png'
  1435. movie = "share/active_4.gif"
  1436. else:
  1437. icon = 'share/active_static.png'
  1438. movie = "share/active.gif"
  1439. self.activity_view = FlatCAMActivityView(icon=icon, movie=movie)
  1440. self.ui.infobar.addWidget(self.activity_view)
  1441. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  1442. # ################################################
  1443. # ############### Signal handling ################
  1444. # ################################################
  1445. # ############# Custom signals ##################
  1446. # signal for displaying messages in status bar
  1447. self.inform.connect(self.info)
  1448. # signal to be called when the app is quiting
  1449. self.app_quit.connect(self.quit_application)
  1450. self.message.connect(self.message_dialog)
  1451. self.progress.connect(self.set_progress_bar)
  1452. # signals that are emitted when object state changes
  1453. self.object_created.connect(self.on_object_created)
  1454. self.object_changed.connect(self.on_object_changed)
  1455. self.object_plotted.connect(self.on_object_plotted)
  1456. self.plots_updated.connect(self.on_plots_updated)
  1457. # signals emitted when file state change
  1458. self.file_opened.connect(self.register_recent)
  1459. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1460. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1461. # ############# Standard signals ###################
  1462. # ### Menu
  1463. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1464. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1465. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1466. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1467. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1468. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1469. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1470. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1471. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1472. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1473. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1474. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1475. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1476. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1477. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1478. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1479. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1480. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1481. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1482. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1483. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1484. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1485. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1486. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1487. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1488. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1489. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1490. self.ui.menufile_exit.triggered.connect(self.final_save)
  1491. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1492. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1493. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1494. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1495. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1496. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1497. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1498. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1499. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1500. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1501. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1502. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1503. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1504. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1505. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1506. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1507. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1508. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1509. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1510. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1511. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1512. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1513. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1514. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1515. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1516. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1517. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1518. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  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.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1531. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1532. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1533. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1534. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1535. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1536. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1537. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1538. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1539. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1540. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1541. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1542. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1543. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1544. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1545. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1546. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1547. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1548. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1549. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1550. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1551. # ToolBar signals
  1552. self.connect_toolbar_signals()
  1553. # Notebook signals
  1554. # make the right click on the notebook tab connect to a function
  1555. self.ui.notebook.setupContextMenu()
  1556. self.ui.notebook.addContextMenu(
  1557. _("Detachable Tabs"), self.on_notebook_tab_rmb_click,
  1558. initial_checked=self.defaults["global_tabs_detachable"])
  1559. # activate initial state
  1560. self.on_notebook_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.options_combo.activated.connect(self.on_options_combo_change)
  1579. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1580. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1581. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1582. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1583. # ##############################
  1584. # ### GUI PREFERENCES SIGNALS ##
  1585. # ##############################
  1586. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  1587. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1588. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1589. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1590. )
  1591. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1592. lambda: self.on_toggle_units(no_pref=False))
  1593. # ###############################################################
  1594. # ################### GUI COLORS SIGNALS ########################
  1595. # ###############################################################
  1596. # Setting plot colors signals
  1597. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1598. self.on_pf_color_entry)
  1599. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1600. self.on_pf_color_button)
  1601. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1602. self.on_pf_color_spinner)
  1603. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1604. self.on_pf_color_slider)
  1605. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1606. self.on_pl_color_entry)
  1607. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1608. self.on_pl_color_button)
  1609. # Setting selection (left - right) colors signals
  1610. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1611. self.on_sf_color_entry)
  1612. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1613. self.on_sf_color_button)
  1614. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1615. self.on_sf_color_spinner)
  1616. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1617. self.on_sf_color_slider)
  1618. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1619. self.on_sl_color_entry)
  1620. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1621. self.on_sl_color_button)
  1622. # Setting selection (right - left) colors signals
  1623. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1624. self.on_alt_sf_color_entry)
  1625. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1626. self.on_alt_sf_color_button)
  1627. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1628. self.on_alt_sf_color_spinner)
  1629. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1630. self.on_alt_sf_color_slider)
  1631. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1632. self.on_alt_sl_color_entry)
  1633. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1634. self.on_alt_sl_color_button)
  1635. # Setting Editor Draw colors signals
  1636. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1637. self.on_draw_color_entry)
  1638. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1639. self.on_draw_color_button)
  1640. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1641. self.on_sel_draw_color_entry)
  1642. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1643. self.on_sel_draw_color_button)
  1644. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1645. self.on_proj_color_entry)
  1646. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1647. self.on_proj_color_button)
  1648. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1649. self.on_proj_color_dis_entry)
  1650. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1651. self.on_proj_color_dis_button)
  1652. # ########## workspace setting signals ###########
  1653. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1654. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1655. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1656. # #################################################
  1657. # ############ GUI SETTINGS SIGNALS ###############
  1658. # #################################################
  1659. self.ui.general_defaults_form.general_gui_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  1660. # ########## CNC Job related signals #############
  1661. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1662. self.on_cnc_custom_parameters)
  1663. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.editingFinished.connect(
  1664. self.on_annotation_fontcolor_entry)
  1665. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.clicked.connect(
  1666. self.on_annotation_fontcolor_button)
  1667. # ########## Tools related signals #############
  1668. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1669. self.on_film_color_entry)
  1670. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1671. self.on_film_color_button)
  1672. # ########## Modify G-CODE Plot Area TAB ###########
  1673. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1674. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1675. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1676. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1677. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1678. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1679. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1680. self.ui.button_copy_all.clicked.connect(self.handleCopyAll)
  1681. # portability changed signal
  1682. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1683. # Object list
  1684. self.collection.view.activated.connect(self.on_row_activated)
  1685. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1686. self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1687. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1688. # Export Excellon parameters.
  1689. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1690. self.on_update_exc_export
  1691. )
  1692. # call it once to make sure it is updated at startup
  1693. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1694. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1695. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1696. self.on_excellon_defaults_button)
  1697. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1698. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1699. self.on_excellon_options_button)
  1700. # when there are arguments at application startup this get launched
  1701. self.args_at_startup[list].connect(self.on_startup_args)
  1702. # ##############################################################
  1703. # ############### FILE ASSOCIATIONS SIGNALS ####################
  1704. # ##############################################################
  1705. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1706. lambda: self.restore_extensions(ext_type='excellon'))
  1707. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1708. lambda: self.restore_extensions(ext_type='gcode'))
  1709. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1710. lambda: self.restore_extensions(ext_type='gerber'))
  1711. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1712. lambda: self.delete_all_extensions(ext_type='excellon'))
  1713. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1714. lambda: self.delete_all_extensions(ext_type='gcode'))
  1715. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1716. lambda: self.delete_all_extensions(ext_type='gerber'))
  1717. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1718. lambda: self.add_extension(ext_type='excellon'))
  1719. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1720. lambda: self.add_extension(ext_type='gcode'))
  1721. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1722. lambda: self.add_extension(ext_type='gerber'))
  1723. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1724. lambda: self.del_extension(ext_type='excellon'))
  1725. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1726. lambda: self.del_extension(ext_type='gcode'))
  1727. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1728. lambda: self.del_extension(ext_type='gerber'))
  1729. # connect the 'Apply' buttons from the Preferences/File Associations
  1730. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1731. lambda: self.on_register_files(obj_type='excellon'))
  1732. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1733. lambda: self.on_register_files(obj_type='gcode'))
  1734. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1735. lambda: self.on_register_files(obj_type='gerber'))
  1736. # ##############################################################
  1737. # ###################### KEYWORDS SIGNALS ######################
  1738. # ##############################################################
  1739. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1740. lambda: self.restore_extensions(ext_type='keyword'))
  1741. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1742. lambda: self.delete_all_extensions(ext_type='keyword'))
  1743. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1744. lambda: self.add_extension(ext_type='keyword'))
  1745. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1746. lambda: self.del_extension(ext_type='keyword'))
  1747. # splash screen button signal
  1748. self.ui.general_defaults_form.general_gui_set_group.splash_cb.stateChanged.connect(self.on_splash_changed)
  1749. # connect the abort_all_tasks related slots to the related signals
  1750. self.proc_container.idle_flag.connect(self.app_is_idle)
  1751. # #####################################################################################
  1752. # ########### FINISHED CONNECTING SIGNALS #############################################
  1753. # #####################################################################################
  1754. self.log.debug("Finished connecting Signals.")
  1755. # #####################################################################################
  1756. # ########################## Other setups #############################################
  1757. # #####################################################################################
  1758. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  1759. # depending on from where those tools are called different actions can be done
  1760. self.call_source = 'app'
  1761. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1762. self.tool_tab_locked = False
  1763. # decide if to show or hide the Notebook side of the screen at startup
  1764. if self.defaults["global_project_at_startup"] is True:
  1765. self.ui.splitter.setSizes([1, 1])
  1766. else:
  1767. self.ui.splitter.setSizes([0, 1])
  1768. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1769. self.setup_obj_classes()
  1770. self.setup_recent_items()
  1771. self.setup_component_editor()
  1772. # this does not work in Legacy Mode
  1773. if self.is_legacy is True:
  1774. self.ui.general_defaults_form.general_gui_group.workspace_cb.setDisabled(True)
  1775. self.ui.general_defaults_form.general_gui_group.workspace_type_lbl.setDisabled(True)
  1776. self.ui.general_defaults_form.general_gui_group.wk_cb.setDisabled(True)
  1777. # #####################################################################################
  1778. # ######################### Auto-complete KEYWORDS ####################################
  1779. # #####################################################################################
  1780. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1781. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1782. 'delete', 'drillcncjob', 'export_gcode', 'export_svg', 'ext', 'exteriors', 'follow',
  1783. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1784. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1785. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1786. 'mirror', 'ncc',
  1787. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1788. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'origin',
  1789. 'paint', 'pan', 'panel', 'panelize', 'plot_all', 'plot_objects', 'quit_flatcam',
  1790. 'save', 'save_project',
  1791. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_sys',
  1792. 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1793. 'version', 'write_gcode'
  1794. ]
  1795. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'Marius', 'My Documents', 'Paste_1',
  1796. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  1797. 'Toolchange_manual', 'Users', 'all', 'angle_x', 'angle_y', 'auto', 'axis', 'axisoffset',
  1798. 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect', 'contour', 'default',
  1799. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dwell',
  1800. 'dwelltime', 'feedrate_z', 'grbl_11', 'grbl_laser', 'gridoffsety', 'gridx', 'gridy',
  1801. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  1802. 'milled_dias', 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order',
  1803. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  1804. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  1805. 'spacing_columns',
  1806. 'spacing_rows', 'spindlespeed', 'toolchange_xy', 'use_threads', 'value', 'x',
  1807. 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1808. ]
  1809. self.tcl_keywords = [
  1810. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1811. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1812. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1813. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1814. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1815. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1816. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1817. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1818. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1819. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1820. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1821. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1822. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1823. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1824. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1825. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1826. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1827. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1828. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1829. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1830. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1831. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1832. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1833. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1834. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1835. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1836. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1837. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1838. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1839. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1840. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1841. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1842. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1843. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1844. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1845. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1846. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1847. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1848. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1849. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1850. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1851. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1852. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1853. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1854. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1855. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1856. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1857. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1858. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1859. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1860. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1861. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1862. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1863. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1864. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1865. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1866. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1867. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1868. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1869. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1870. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1871. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1872. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1873. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1874. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1875. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1876. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1877. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1878. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1879. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1880. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1881. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1882. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1883. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1884. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1885. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1886. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1887. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1888. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1889. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1890. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1891. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1892. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1893. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1894. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1895. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1896. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1897. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1898. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1899. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1900. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1901. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1902. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1903. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1904. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1905. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1906. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1907. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1908. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1909. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1910. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1911. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1912. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1913. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1914. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1915. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1916. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1917. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1918. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1919. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1920. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1921. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1922. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1923. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1924. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1925. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1926. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1927. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1928. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1929. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1930. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1931. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1932. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1933. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1934. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1935. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1936. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1937. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1938. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1939. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1940. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1941. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1942. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1943. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1944. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1945. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1946. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1947. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1948. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1949. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1950. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1951. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1952. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1953. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1954. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1955. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1956. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1957. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1958. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1959. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1960. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1961. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1962. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1963. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1964. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1965. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1966. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1967. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1968. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1969. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1970. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1971. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1972. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1973. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1974. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1975. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1976. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1977. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1978. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1979. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1980. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1981. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1982. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1983. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1984. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1985. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1986. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1987. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1988. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1989. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1990. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1991. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1992. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1993. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1994. ]
  1995. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1996. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1997. # ####################################################################################
  1998. # ####################### Shell SETUP ################################################
  1999. # ####################################################################################
  2000. self.shell = FCShell(self, version=self.version)
  2001. self.shell._edit.set_model_data(self.myKeywords)
  2002. self.ui.code_editor.set_model_data(self.myKeywords)
  2003. self.shell.setWindowIcon(self.ui.app_icon)
  2004. self.shell.setWindowTitle("FlatCAM Shell")
  2005. self.shell.resize(*self.defaults["global_shell_shape"])
  2006. self.shell.append_output("FlatCAM %s - " % self.version)
  2007. self.shell.append_output(_("Open Source Software - Type help to get started\n\n"))
  2008. self.init_tcl()
  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. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  2045. self.install_tools()
  2046. # ### System Font Parsing ###
  2047. # self.f_parse = ParseFont(self)
  2048. # self.parse_system_fonts()
  2049. # #####################################################################################
  2050. # ######################## Check for updates ##########################################
  2051. # #####################################################################################
  2052. # Separate thread (Not worker)
  2053. # Check for updates on startup but only if the user consent and the app is not in Beta version
  2054. if (self.beta is False or self.beta is None) and \
  2055. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  2056. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  2057. self.thr2 = QtCore.QThread()
  2058. self.worker_task.emit({'fcn': self.version_check,
  2059. 'params': []})
  2060. self.thr2.start(QtCore.QThread.LowPriority)
  2061. # #####################################################################################
  2062. # ######################### Register files with FlatCAM; #############################
  2063. # ######################### It works only for Windows for now ########################
  2064. # #####################################################################################
  2065. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  2066. self.on_register_files()
  2067. # #####################################################################################
  2068. # ###################### Variables for global usage ###################################
  2069. # #####################################################################################
  2070. # coordinates for relative position display
  2071. self.rel_point1 = (0, 0)
  2072. self.rel_point2 = (0, 0)
  2073. # variable to store coordinates
  2074. self.pos = (0, 0)
  2075. self.pos_jump = (0, 0)
  2076. # variable to store mouse coordinates
  2077. self.mouse = [0, 0]
  2078. # decide if we have a double click or single click
  2079. self.doubleclick = False
  2080. # variable to store if a command is active (then the var is not None) and which one it is
  2081. self.command_active = None
  2082. # variable to store the status of moving selection action
  2083. # None value means that it's not an selection action
  2084. # True value = a selection from left to right
  2085. # False value = a selection from right to left
  2086. self.selection_type = None
  2087. # List to store the objects that are currently loaded in FlatCAM
  2088. # This list is updated on each object creation or object delete
  2089. self.all_objects_list = list()
  2090. # List to store the objects that are selected
  2091. self.sel_objects_list = list()
  2092. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  2093. self.key_modifiers = None
  2094. # Variable to hold the status of the axis
  2095. self.toggle_axis = True
  2096. # Variable to store the status of the fullscreen event
  2097. self.toggle_fscreen = False
  2098. # Variable to store the status of the code editor
  2099. self.toggle_codeeditor = False
  2100. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  2101. self.click_noproject = False
  2102. self.cursor = None
  2103. # Variable to store the GCODE that was edited
  2104. self.gcode_edited = ""
  2105. # reference for the self.ui.code_editor
  2106. self.reference_code_editor = None
  2107. self.script_code = ''
  2108. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  2109. self.preferences_changed_flag = False
  2110. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  2111. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  2112. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'pho',
  2113. 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top', 'tsm']
  2114. self.exc_list = ['drd', 'drl', 'exc', 'ncd', 'tap', 'txt', 'xln']
  2115. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  2116. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ncp', 'out', 'plt', 'ply', 'rol', 'sbp',
  2117. 'tap', 'xpi']
  2118. self.svg_list = ['svg']
  2119. self.dxf_list = ['dxf']
  2120. self.pdf_list = ['pdf']
  2121. self.prj_list = ['flatprj']
  2122. self.conf_list = ['flatconfig']
  2123. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  2124. # flag for polygons not cleared
  2125. self.poly_not_cleared = False
  2126. # VisPy visuals
  2127. self.isHovering = False
  2128. self.notHovering = True
  2129. # Window geometry
  2130. self.x_pos = None
  2131. self.y_pos = None
  2132. self.width = None
  2133. self.height = None
  2134. # Event signals disconnect id holders
  2135. self.mp = None
  2136. self.mm = None
  2137. self.mr = None
  2138. self.mp_zc = None
  2139. # when True, the app has to return from any thread
  2140. self.abort_flag = False
  2141. # set the value used in the Windows Title
  2142. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  2143. # ###############################################################################
  2144. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  2145. # ############# It's done only once after install ###############
  2146. # ###############################################################################
  2147. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  2148. fac_def_from_file = factory_file.read()
  2149. factory_defaults = json.loads(fac_def_from_file)
  2150. # if the file contain an empty dictionary then save the factory defaults into the file
  2151. if not factory_defaults:
  2152. self.save_factory_defaults(silent=False)
  2153. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  2154. initial_lay = 'compact'
  2155. self.on_layout(lay=initial_lay)
  2156. # Set the combobox in Preferences to the current layout
  2157. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  2158. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  2159. factory_file.close()
  2160. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  2161. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  2162. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  2163. # after the first run, this object should be False
  2164. self.defaults["first_run"] = False
  2165. # ###############################################################################
  2166. # ################# ADDING FlatCAM EDITORS section ##############################
  2167. # ###############################################################################
  2168. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2169. # at the first launch of the App , the editors will not be functional.
  2170. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  2171. self.exc_editor = FlatCAMExcEditor(self)
  2172. self.grb_editor = FlatCAMGrbEditor(self)
  2173. self.log.debug("Finished adding FlatCAM Editor's.")
  2174. self.set_ui_title(name=_("New Project - Not saved"))
  2175. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2176. current_platform = platform.architecture()[0]
  2177. if current_platform != '64bit':
  2178. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2179. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2180. # ###############################################################################
  2181. # ####################### Finished the CONSTRUCTOR ##############################
  2182. # ###############################################################################
  2183. App.log.debug("END of constructor. Releasing control.")
  2184. # #####################################################################################
  2185. # ########################## SHOW GUI #################################################
  2186. # #####################################################################################
  2187. # if the app is not started as headless, show it
  2188. if self.cmd_line_headless != 1:
  2189. if show_splash:
  2190. # finish the splash
  2191. self.splash.finish(self.ui)
  2192. settings = QSettings("Open Source", "FlatCAM")
  2193. if settings.contains("maximized_gui"):
  2194. maximized_ui = settings.value('maximized_gui', type=bool)
  2195. if maximized_ui is True:
  2196. self.ui.showMaximized()
  2197. else:
  2198. self.ui.show()
  2199. else:
  2200. self.ui.show()
  2201. if self.defaults["global_systray_icon"]:
  2202. self.trayIcon.show()
  2203. else:
  2204. log.warning("******************* RUNNING HEADLESS *******************")
  2205. # #####################################################################################
  2206. # ########################## START-UP ARGUMENTS #######################################
  2207. # #####################################################################################
  2208. # test if the program was started with a script as parameter
  2209. if self.cmd_line_shellvar:
  2210. try:
  2211. cnt = 0
  2212. command_tcl = 0
  2213. for i in self.cmd_line_shellvar.split(','):
  2214. if i is not None:
  2215. try:
  2216. command_tcl = eval(i)
  2217. except:
  2218. command_tcl = i
  2219. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  2220. cnt += 1
  2221. # if there are Windows paths then replace the path separator with a Unix like one
  2222. if sys.platform == 'win32':
  2223. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  2224. self.shell._sysShell.exec_command(command_tcl_formatted, no_echo=True)
  2225. except Exception as ext:
  2226. print("ERROR: ", ext)
  2227. sys.exit(2)
  2228. if self.cmd_line_shellfile:
  2229. try:
  2230. if self.ui.shell_dock.isHidden():
  2231. self.ui.shell_dock.show()
  2232. with open(self.cmd_line_shellfile, "r") as myfile:
  2233. if show_splash:
  2234. self.splash.showMessage('%s: %ssec\n%s' % (
  2235. _("Canvas initialization started.\n"
  2236. "Canvas initialization finished in"), '%.2f' % self.used_time,
  2237. _("Executing Tcl Script ...")),
  2238. alignment=Qt.AlignBottom | Qt.AlignLeft,
  2239. color=QtGui.QColor("gray"))
  2240. cmd_line_shellfile_text = myfile.read()
  2241. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  2242. except Exception as ext:
  2243. print("ERROR: ", ext)
  2244. sys.exit(2)
  2245. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2246. # the path/file_name must be enclosed in quotes if it contain spaces
  2247. if App.args:
  2248. self.args_at_startup.emit(App.args)
  2249. @staticmethod
  2250. def copy_and_overwrite(from_path, to_path):
  2251. """
  2252. From here:
  2253. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2254. :param from_path: source path
  2255. :param to_path: destination path
  2256. :return: None
  2257. """
  2258. if os.path.exists(to_path):
  2259. shutil.rmtree(to_path)
  2260. try:
  2261. shutil.copytree(from_path, to_path)
  2262. except FileNotFoundError:
  2263. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2264. shutil.copytree(from_new_path, to_path)
  2265. def on_startup_args(self, args, silent=False):
  2266. """
  2267. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2268. :param args: a list containing the application args at startup
  2269. :return: None
  2270. """
  2271. if args is not None:
  2272. args_to_process = args
  2273. else:
  2274. args_to_process = App.args
  2275. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2276. for argument in args_to_process:
  2277. if '.FlatPrj'.lower() in argument.lower():
  2278. try:
  2279. project_name = str(argument)
  2280. if project_name == "":
  2281. if silent is False:
  2282. self.inform.emit(_("Open cancelled."))
  2283. else:
  2284. # self.open_project(project_name)
  2285. run_from_arg = True
  2286. # self.worker_task.emit({'fcn': self.open_project,
  2287. # 'params': [project_name, run_from_arg]})
  2288. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2289. except Exception as e:
  2290. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2291. elif '.FlatConfig'.lower() in argument.lower():
  2292. try:
  2293. file_name = str(argument)
  2294. if file_name == "":
  2295. if silent is False:
  2296. self.inform.emit(_("Open Config file failed."))
  2297. else:
  2298. run_from_arg = True
  2299. # self.worker_task.emit({'fcn': self.open_config_file,
  2300. # 'params': [file_name, run_from_arg]})
  2301. self.open_config_file(file_name, run_from_arg=run_from_arg)
  2302. except Exception as e:
  2303. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2304. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  2305. try:
  2306. file_name = str(argument)
  2307. if file_name == "":
  2308. if silent is False:
  2309. self.inform.emit(_("Open Script file failed."))
  2310. else:
  2311. if silent is False:
  2312. self.on_fileopenscript(name=file_name)
  2313. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  2314. self.on_filerunscript(name=file_name)
  2315. except Exception as e:
  2316. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2317. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  2318. log.debug("App.on_startup_args() --> Quit event.")
  2319. sys.exit()
  2320. elif 'save'.lower() in argument.lower():
  2321. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  2322. self.save_defaults()
  2323. else:
  2324. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2325. proc_arg = argument.lower()
  2326. for ext in exc_list:
  2327. proc_ext = ext.replace(' ', '')
  2328. proc_ext = '.%s' % proc_ext
  2329. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2330. file_name = str(argument)
  2331. if file_name == "":
  2332. if silent is False:
  2333. self.inform.emit(_("Open Excellon file failed."))
  2334. else:
  2335. self.on_fileopenexcellon(name=file_name)
  2336. return
  2337. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2338. for ext in gco_list:
  2339. proc_ext = ext.replace(' ', '')
  2340. proc_ext = '.%s' % proc_ext
  2341. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2342. file_name = str(argument)
  2343. if file_name == "":
  2344. if silent is False:
  2345. self.inform.emit(_("Open GCode file failed."))
  2346. else:
  2347. self.on_fileopengcode(name=file_name)
  2348. return
  2349. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2350. for ext in grb_list:
  2351. proc_ext = ext.replace(' ', '')
  2352. proc_ext = '.%s' % proc_ext
  2353. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2354. file_name = str(argument)
  2355. if file_name == "":
  2356. if silent is False:
  2357. self.inform.emit(_("Open Gerber file failed."))
  2358. else:
  2359. self.on_fileopengerber(name=file_name)
  2360. return
  2361. # if it reached here without already returning then the app was registered with a file that it does not
  2362. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  2363. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  2364. for arg in args_to_process:
  2365. if 'FlatCAM.exe' in arg:
  2366. continue
  2367. else:
  2368. sys.exit(2)
  2369. def set_ui_title(self, name):
  2370. """
  2371. Sets the title of the main window.
  2372. :param name: String that store the project path and project name
  2373. :return: None
  2374. """
  2375. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  2376. (self.version,
  2377. ('BETA' if self.beta else ''),
  2378. platform.architecture()[0],
  2379. self.engine,
  2380. name)
  2381. )
  2382. def on_app_restart(self):
  2383. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  2384. # be left in the SySTray
  2385. try:
  2386. self.trayIcon.hide()
  2387. except Exception as e:
  2388. log.debug("App.on_app_restart() --> %s" % str(e))
  2389. fcTranslate.restart_program(app=self)
  2390. def defaults_read_form(self):
  2391. """
  2392. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2393. :return: None
  2394. """
  2395. for option in self.defaults_form_fields:
  2396. try:
  2397. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2398. except Exception as e:
  2399. log.debug("App.defaults_read_form() --> %s" % str(e))
  2400. def defaults_write_form(self, factor=None, fl_units=None):
  2401. """
  2402. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2403. self.defaults dictionary.
  2404. :param factor: will apply a factor to the values that written in the GUI elements
  2405. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2406. :return: None
  2407. """
  2408. for option in self.defaults:
  2409. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2410. # try:
  2411. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2412. # except KeyError:
  2413. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2414. # # TODO: Rethink this?
  2415. # pass
  2416. def defaults_write_form_field(self, field, factor=None, units=None):
  2417. """
  2418. Basically it is the worker in the self.defaults_write_form()
  2419. :param field: the GUI element in Preferences GUI to be updated
  2420. :param factor: factor to be applied to the field parameter
  2421. :param units: current FLatCAM measuring units
  2422. :return: None, it updates GUI elements
  2423. """
  2424. try:
  2425. if factor is None:
  2426. if units is None:
  2427. self.defaults_form_fields[field].set_value(self.defaults[field])
  2428. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2429. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=6)
  2430. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2431. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=4)
  2432. else:
  2433. if units is None:
  2434. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2435. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2436. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=6)
  2437. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2438. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=4)
  2439. except KeyError:
  2440. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2441. # TODO: Rethink this?
  2442. pass
  2443. except AttributeError:
  2444. log.debug(field)
  2445. def clear_pool(self):
  2446. """
  2447. Clear the multiprocessing pool and calls garbage collector.
  2448. :return: None
  2449. """
  2450. self.pool.close()
  2451. self.pool = Pool()
  2452. self.pool_recreated.emit(self.pool)
  2453. gc.collect()
  2454. def install_tools(self):
  2455. """
  2456. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2457. Instantiation of the Tools classes.
  2458. The order that the tools are installed is important as they can depend on each other install position.
  2459. :return: None
  2460. """
  2461. self.dblsidedtool = DblSidedTool(self)
  2462. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2463. self.distance_tool = Distance(self)
  2464. self.distance_tool.install(icon=QtGui.QIcon('share/measure16.png'), pos=self.ui.menuedit,
  2465. before=self.ui.menueditorigin,
  2466. separator=False)
  2467. self.distance_min_tool = DistanceMin(self)
  2468. self.distance_min_tool.install(icon=QtGui.QIcon('share/measure16.png'), pos=self.ui.menuedit,
  2469. before=self.ui.menueditorigin,
  2470. separator=True)
  2471. self.panelize_tool = Panelize(self)
  2472. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  2473. self.film_tool = Film(self)
  2474. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2475. self.paste_tool = SolderPaste(self)
  2476. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2477. self.calculator_tool = ToolCalculator(self)
  2478. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'), separator=True)
  2479. self.sub_tool = ToolSub(self)
  2480. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2481. self.rules_tool = RulesCheck(self)
  2482. self.rules_tool.install(icon=QtGui.QIcon('share/rules32.png'), pos=self.ui.menutool, separator=False)
  2483. self.optimal_tool = ToolOptimal(self)
  2484. self.optimal_tool.install(icon=QtGui.QIcon('share/open_excellon32.png'), pos=self.ui.menutool, separator=True)
  2485. self.move_tool = ToolMove(self)
  2486. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2487. before=self.ui.menueditorigin, separator=True)
  2488. self.cutout_tool = CutOut(self)
  2489. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2490. before=self.sub_tool.menuAction)
  2491. self.ncclear_tool = NonCopperClear(self)
  2492. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2493. before=self.sub_tool.menuAction, separator=True)
  2494. self.paint_tool = ToolPaint(self)
  2495. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2496. before=self.sub_tool.menuAction, separator=True)
  2497. self.transform_tool = ToolTransform(self)
  2498. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2499. self.properties_tool = Properties(self)
  2500. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2501. self.pdf_tool = ToolPDF(self)
  2502. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2503. separator=True)
  2504. self.image_tool = ToolImage(self)
  2505. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2506. separator=True)
  2507. self.pcb_wizard_tool = PcbWizard(self)
  2508. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2509. self.log.debug("Tools are installed.")
  2510. def remove_tools(self):
  2511. """
  2512. Will remove all the actions in the Tool menu.
  2513. :return: None
  2514. """
  2515. for act in self.ui.menutool.actions():
  2516. self.ui.menutool.removeAction(act)
  2517. def init_tools(self):
  2518. """
  2519. Initialize the Tool tab in the notebook side of the central widget.
  2520. Remove the actions in the Tools menu.
  2521. Instantiate again the FlatCAM tools (plugins).
  2522. All this is required when changing the layout: standard, compact etc.
  2523. :return: None
  2524. """
  2525. log.debug("init_tools()")
  2526. # delete the data currently in the Tools Tab and the Tab itself
  2527. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2528. if widget is not None:
  2529. widget.deleteLater()
  2530. self.ui.notebook.removeTab(2)
  2531. # rebuild the Tools Tab
  2532. self.ui.tool_tab = QtWidgets.QWidget()
  2533. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2534. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2535. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2536. self.ui.tool_scroll_area = VerticalScrollArea()
  2537. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2538. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2539. # first remove all of them
  2540. self.remove_tools()
  2541. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2542. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2543. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2544. # third install all of them
  2545. self.install_tools()
  2546. self.log.debug("Tools are initialized.")
  2547. # def parse_system_fonts(self):
  2548. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2549. # 'params': []})
  2550. def connect_toolbar_signals(self):
  2551. """
  2552. Reconnect the signals to the actions in the toolbar.
  2553. This has to be done each time after the FlatCAM tools are removed/installed.
  2554. :return: None
  2555. """
  2556. # Toolbar
  2557. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2558. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2559. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2560. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2561. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2562. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2563. self.ui.replot_btn.triggered.connect(self.plot_all)
  2564. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2565. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2566. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2567. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2568. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2569. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2570. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2571. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2572. self.ui.delete_btn.triggered.connect(self.on_delete)
  2573. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2574. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2575. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2576. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2577. # Tools Toolbar Signals
  2578. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2579. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2580. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2581. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2582. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2583. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2584. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2585. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2586. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  2587. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  2588. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2589. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2590. def object2editor(self):
  2591. """
  2592. Send the current Geometry or Excellon object (if any) into the it's editor.
  2593. :return: None
  2594. """
  2595. self.report_usage("object2editor()")
  2596. edited_object = self.collection.get_active()
  2597. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2598. isinstance(edited_object, FlatCAMExcellon):
  2599. pass
  2600. else:
  2601. self.inform.emit('[WARNING_NOTCL] %s' %
  2602. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2603. return
  2604. if isinstance(edited_object, FlatCAMGeometry):
  2605. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2606. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2607. # we set the notebook to hidden
  2608. self.ui.splitter.setSizes([0, 1])
  2609. if edited_object.multigeo is True:
  2610. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  2611. if len(edited_tools) > 1:
  2612. self.inform.emit('[WARNING_NOTCL] %s' %
  2613. _("Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  2614. "is not possible.\n"
  2615. "Edit only one geometry at a time."))
  2616. # determine the tool dia of the selected tool
  2617. selected_tooldia = float(edited_object.ui.geo_tools_table.item((edited_tools[0] - 1), 1).text())
  2618. # now find the key in the edited_object.tools that has this tooldia
  2619. multi_tool = 1
  2620. for tool in edited_object.tools:
  2621. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2622. multi_tool = tool
  2623. break
  2624. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2625. else:
  2626. self.geo_editor.edit_fcgeometry(edited_object)
  2627. # set call source to the Editor we go into
  2628. self.call_source = 'geo_editor'
  2629. elif isinstance(edited_object, FlatCAMExcellon):
  2630. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2631. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2632. if self.ui.splitter.sizes()[0] == 0:
  2633. self.ui.splitter.setSizes([1, 1])
  2634. self.exc_editor.edit_fcexcellon(edited_object)
  2635. # set call source to the Editor we go into
  2636. self.call_source = 'exc_editor'
  2637. elif isinstance(edited_object, FlatCAMGerber):
  2638. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2639. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2640. if self.ui.splitter.sizes()[0] == 0:
  2641. self.ui.splitter.setSizes([1, 1])
  2642. self.grb_editor.edit_fcgerber(edited_object)
  2643. # set call source to the Editor we go into
  2644. self.call_source = 'grb_editor'
  2645. # make sure that we can't select another object while in Editor Mode:
  2646. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2647. self.ui.project_frame.setDisabled(True)
  2648. # delete any selection shape that might be active as they are not relevant in Editor
  2649. self.delete_selection_shape()
  2650. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2651. self.ui.plot_tab_area.protectTab(0)
  2652. self.inform.emit('[WARNING_NOTCL] %s' %
  2653. _("Editor is activated ..."))
  2654. self.should_we_save = True
  2655. def editor2object(self, cleanup=None):
  2656. """
  2657. Transfers the Geometry or Excellon from it's editor to the current object.
  2658. :return: None
  2659. """
  2660. self.report_usage("editor2object()")
  2661. # do not update a geometry or excellon object unless it comes out of an editor
  2662. if self.call_source != 'app':
  2663. edited_obj = self.collection.get_active()
  2664. if cleanup is None:
  2665. msgbox = QtWidgets.QMessageBox()
  2666. msgbox.setText(_("Do you want to save the edited object?"))
  2667. msgbox.setWindowTitle(_("Close Editor"))
  2668. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2669. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2670. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2671. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2672. msgbox.setDefaultButton(bt_yes)
  2673. msgbox.exec_()
  2674. response = msgbox.clickedButton()
  2675. if response == bt_yes:
  2676. # clean the Tools Tab
  2677. self.ui.tool_scroll_area.takeWidget()
  2678. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2679. self.ui.notebook.setTabText(2, "Tool")
  2680. if isinstance(edited_obj, FlatCAMGeometry):
  2681. obj_type = "Geometry"
  2682. if cleanup is None:
  2683. self.geo_editor.update_fcgeometry(edited_obj)
  2684. self.geo_editor.update_options(edited_obj)
  2685. self.geo_editor.deactivate()
  2686. # update the geo object options so it is including the bounding box values
  2687. try:
  2688. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2689. edited_obj.options['xmin'] = xmin
  2690. edited_obj.options['ymin'] = ymin
  2691. edited_obj.options['xmax'] = xmax
  2692. edited_obj.options['ymax'] = ymax
  2693. except AttributeError as e:
  2694. self.inform.emit('[WARNING] %s' %
  2695. _("Object empty after edit."))
  2696. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2697. elif isinstance(edited_obj, FlatCAMGerber):
  2698. obj_type = "Gerber"
  2699. if cleanup is None:
  2700. self.grb_editor.update_fcgerber()
  2701. self.grb_editor.update_options(edited_obj)
  2702. self.grb_editor.deactivate_grb_editor()
  2703. # delete the old object (the source object) if it was an empty one
  2704. if len(edited_obj.solid_geometry) == 0:
  2705. old_name = edited_obj.options['name']
  2706. self.collection.set_active(old_name)
  2707. self.collection.delete_active()
  2708. # restore GUI to the Selected TAB
  2709. # Remove anything else in the GUI
  2710. self.ui.selected_scroll_area.takeWidget()
  2711. # Switch notebook to Selected page
  2712. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2713. elif isinstance(edited_obj, FlatCAMExcellon):
  2714. obj_type = "Excellon"
  2715. if cleanup is None:
  2716. self.exc_editor.update_fcexcellon(edited_obj)
  2717. self.exc_editor.update_options(edited_obj)
  2718. self.exc_editor.deactivate()
  2719. # delete the old object (the source object) if it was an empty one
  2720. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  2721. old_name = edited_obj.options['name']
  2722. self.collection.set_active(old_name)
  2723. self.collection.delete_active()
  2724. # restore GUI to the Selected TAB
  2725. # Remove anything else in the GUI
  2726. self.ui.tool_scroll_area.takeWidget()
  2727. # Switch notebook to Selected page
  2728. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2729. else:
  2730. self.inform.emit('[WARNING_NOTCL] %s' %
  2731. _("Select a Gerber, Geometry or Excellon Object to update."))
  2732. return
  2733. self.inform.emit('[selected] %s %s' %
  2734. (obj_type, _("is updated, returning to App...")))
  2735. elif response == bt_no:
  2736. # clean the Tools Tab
  2737. self.ui.tool_scroll_area.takeWidget()
  2738. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2739. self.ui.notebook.setTabText(2, "Tool")
  2740. if isinstance(edited_obj, FlatCAMGeometry):
  2741. self.geo_editor.deactivate()
  2742. elif isinstance(edited_obj, FlatCAMGerber):
  2743. self.grb_editor.deactivate_grb_editor()
  2744. elif isinstance(edited_obj, FlatCAMExcellon):
  2745. self.exc_editor.deactivate()
  2746. # set focus on the project tab
  2747. else:
  2748. self.inform.emit('[WARNING_NOTCL] %s' %
  2749. _("Select a Gerber, Geometry or Excellon Object to update."))
  2750. return
  2751. edited_obj.set_ui(edited_obj.ui_type())
  2752. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2753. elif response == bt_cancel:
  2754. return
  2755. else:
  2756. if isinstance(edited_obj, FlatCAMGeometry):
  2757. self.geo_editor.deactivate()
  2758. elif isinstance(edited_obj, FlatCAMGerber):
  2759. self.grb_editor.deactivate_grb_editor()
  2760. elif isinstance(edited_obj, FlatCAMExcellon):
  2761. self.exc_editor.deactivate()
  2762. else:
  2763. self.inform.emit('[WARNING_NOTCL] %s' %
  2764. _("Select a Gerber, Geometry or Excellon Object to update."))
  2765. return
  2766. # if notebook is hidden we show it
  2767. if self.ui.splitter.sizes()[0] == 0:
  2768. self.ui.splitter.setSizes([1, 1])
  2769. # restore the call_source to app
  2770. self.call_source = 'app'
  2771. edited_obj.plot()
  2772. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2773. self.ui.plot_tab_area.protectTab(0)
  2774. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2775. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2776. self.ui.project_frame.setDisabled(False)
  2777. def get_last_folder(self):
  2778. """
  2779. Get the folder path from where the last file was opened.
  2780. :return: String, last opened folder path
  2781. """
  2782. return self.defaults["global_last_folder"]
  2783. def get_last_save_folder(self):
  2784. """
  2785. Get the folder path from where the last file was saved.
  2786. :return: String, last saved folder path
  2787. """
  2788. loc = self.defaults["global_last_save_folder"]
  2789. if loc is None:
  2790. loc = self.defaults["global_last_folder"]
  2791. if loc is None:
  2792. loc = os.path.dirname(__file__)
  2793. return loc
  2794. def report_usage(self, resource):
  2795. """
  2796. Increments usage counter for the given resource
  2797. in self.defaults['global_stats'].
  2798. :param resource: Name of the resource.
  2799. :return: None
  2800. """
  2801. if resource in self.defaults['global_stats']:
  2802. self.defaults['global_stats'][resource] += 1
  2803. else:
  2804. self.defaults['global_stats'][resource] = 1
  2805. def init_tcl(self):
  2806. """
  2807. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2808. :return: None
  2809. """
  2810. if hasattr(self, 'tcl'):
  2811. # self.tcl = None
  2812. # TODO we need to clean non default variables and procedures here
  2813. # new object cannot be used here as it will not remember values created for next passes,
  2814. # because tcl was execudted in old instance of TCL
  2815. pass
  2816. else:
  2817. self.tcl = tk.Tcl()
  2818. self.setup_shell()
  2819. self.log.debug("TCL Shell has been initialized.")
  2820. # TODO: This shouldn't be here.
  2821. class TclErrorException(Exception):
  2822. """
  2823. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2824. """
  2825. pass
  2826. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2827. """
  2828. Shows a message on the FlatCAM Shell
  2829. :param msg: Message to display.
  2830. :param show: Opens the shell.
  2831. :param error: Shows the message as an error.
  2832. :param warning: Shows the message as an warning.
  2833. :param success: Shows the message as an success.
  2834. :param selected: Indicate that something was selected on canvas
  2835. :return: None
  2836. """
  2837. if show:
  2838. self.ui.shell_dock.show()
  2839. try:
  2840. if error:
  2841. self.shell.append_error(msg + "\n")
  2842. elif warning:
  2843. self.shell.append_warning(msg + "\n")
  2844. elif success:
  2845. self.shell.append_success(msg + "\n")
  2846. elif selected:
  2847. self.shell.append_selected(msg + "\n")
  2848. else:
  2849. self.shell.append_output(msg + "\n")
  2850. except AttributeError:
  2851. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2852. def raise_tcl_unknown_error(self, unknownException):
  2853. """
  2854. Raise exception if is different type than TclErrorException
  2855. this is here mainly to show unknown errors inside TCL shell console.
  2856. :param unknownException:
  2857. :return:
  2858. """
  2859. if not isinstance(unknownException, self.TclErrorException):
  2860. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2861. else:
  2862. raise unknownException
  2863. def display_tcl_error(self, error, error_info=None):
  2864. """
  2865. Escape bracket [ with '\' otherwise there is error
  2866. "ERROR: missing close-bracket" instead of real error
  2867. :param error: it may be text or exception
  2868. :param error_info: Some informations about the error
  2869. :return: None
  2870. """
  2871. if isinstance(error, Exception):
  2872. exc_type, exc_value, exc_traceback = error_info
  2873. if not isinstance(error, self.TclErrorException):
  2874. show_trace = 1
  2875. else:
  2876. show_trace = int(self.defaults['global_verbose_error_level'])
  2877. if show_trace > 0:
  2878. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2879. trc_formated = []
  2880. for a in reversed(trc):
  2881. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2882. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2883. else:
  2884. text = "%s" % error
  2885. else:
  2886. text = error
  2887. text = text.replace('[', '\\[').replace('"', '\\"')
  2888. self.tcl.eval('return -code error "%s"' % text)
  2889. def raise_tcl_error(self, text):
  2890. """
  2891. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2892. :param text: text of error
  2893. :return: raise exception
  2894. """
  2895. self.display_tcl_error(text)
  2896. raise self.TclErrorException(text)
  2897. def exec_command(self, text, no_echo=False):
  2898. """
  2899. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2900. Also handles execution in separated threads
  2901. :param text: FlatCAM TclCommand with parameters
  2902. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2903. will create crashes of the _Expandable_Edit widget
  2904. :return: output if there was any
  2905. """
  2906. self.report_usage('exec_command')
  2907. result = self.exec_command_test(text, False, no_echo=no_echo)
  2908. # MS: added this method call so the geometry is updated once the TCL command is executed
  2909. # if no_plot is None:
  2910. # self.plot_all()
  2911. return result
  2912. def exec_command_test(self, text, reraise=True, no_echo=False):
  2913. """
  2914. Same as exec_command(...) with additional control over exceptions.
  2915. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2916. :param text: Input command
  2917. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2918. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2919. will create crashes of the _Expandable_Edit widget
  2920. :return: Output from the command
  2921. """
  2922. tcl_command_string = str(text)
  2923. try:
  2924. if no_echo is False:
  2925. self.shell.open_proccessing() # Disables input box.
  2926. result = self.tcl.eval(str(tcl_command_string))
  2927. if result != 'None' and no_echo is False:
  2928. self.shell.append_output(result + '\n')
  2929. except tk.TclError as e:
  2930. # This will display more precise answer if something in TCL shell fails
  2931. result = self.tcl.eval("set errorInfo")
  2932. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2933. if no_echo is False:
  2934. self.shell.append_error('ERROR: ' + result + '\n')
  2935. # Show error in console and just return or in test raise exception
  2936. if reraise:
  2937. raise e
  2938. finally:
  2939. if no_echo is False:
  2940. self.shell.close_proccessing()
  2941. pass
  2942. return result
  2943. # """
  2944. # Code below is unsused. Saved for later.
  2945. # """
  2946. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2947. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2948. # self.log.debug(parts)
  2949. # try:
  2950. # if parts[0] not in commands:
  2951. # self.shell.append_error("Unknown command\n")
  2952. # return
  2953. #
  2954. # #import inspect
  2955. # #inspect.getargspec(someMethod)
  2956. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2957. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2958. # self.shell.append_error(
  2959. # "Command %s takes %d arguments. %d given.\n" %
  2960. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2961. # )
  2962. # return
  2963. #
  2964. # cmdfcn = commands[parts[0]]["fcn"]
  2965. # cmdconv = commands[parts[0]]["converters"]
  2966. # if len(parts) - 1 > 0:
  2967. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2968. # else:
  2969. # retval = cmdfcn()
  2970. # retfcn = commands[parts[0]]["retfcn"]
  2971. # if retval and retfcn(retval):
  2972. # self.shell.append_output(retfcn(retval) + "\n")
  2973. #
  2974. # except Exception as e:
  2975. # #self.shell.append_error(''.join(traceback.format_exc()))
  2976. # #self.shell.append_error("?\n")
  2977. # self.shell.append_error(str(e) + "\n")
  2978. def info(self, msg):
  2979. """
  2980. Informs the user. Normally on the status bar, optionally
  2981. also on the shell.
  2982. :param msg: Text to write.
  2983. :return: None
  2984. """
  2985. # Type of message in brackets at the beginning of the message.
  2986. match = re.search("\[([^\]]+)\](.*)", msg)
  2987. if match:
  2988. level = match.group(1)
  2989. msg_ = match.group(2)
  2990. self.ui.fcinfo.set_status(str(msg_), level=level)
  2991. if level.lower() == "error":
  2992. self.shell_message(msg, error=True, show=True)
  2993. elif level.lower() == "warning":
  2994. self.shell_message(msg, warning=True, show=True)
  2995. elif level.lower() == "error_notcl":
  2996. self.shell_message(msg, error=True, show=False)
  2997. elif level.lower() == "warning_notcl":
  2998. self.shell_message(msg, warning=True, show=False)
  2999. elif level.lower() == "success":
  3000. self.shell_message(msg, success=True, show=False)
  3001. elif level.lower() == "selected":
  3002. self.shell_message(msg, selected=True, show=False)
  3003. else:
  3004. self.shell_message(msg, show=False)
  3005. else:
  3006. self.ui.fcinfo.set_status(str(msg), level="info")
  3007. # make sure that if the message is to clear the infobar with a space
  3008. # is not printed over and over on the shell
  3009. if msg != '':
  3010. self.shell_message(msg)
  3011. def restore_toolbar_view(self):
  3012. """
  3013. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  3014. was saved in the defaults dictionary.
  3015. :return: None
  3016. """
  3017. tb = self.defaults["global_toolbar_view"]
  3018. if tb & 1:
  3019. self.ui.toolbarfile.setVisible(True)
  3020. else:
  3021. self.ui.toolbarfile.setVisible(False)
  3022. if tb & 2:
  3023. self.ui.toolbargeo.setVisible(True)
  3024. else:
  3025. self.ui.toolbargeo.setVisible(False)
  3026. if tb & 4:
  3027. self.ui.toolbarview.setVisible(True)
  3028. else:
  3029. self.ui.toolbarview.setVisible(False)
  3030. if tb & 8:
  3031. self.ui.toolbartools.setVisible(True)
  3032. else:
  3033. self.ui.toolbartools.setVisible(False)
  3034. if tb & 16:
  3035. self.ui.exc_edit_toolbar.setVisible(True)
  3036. else:
  3037. self.ui.exc_edit_toolbar.setVisible(False)
  3038. if tb & 32:
  3039. self.ui.geo_edit_toolbar.setVisible(True)
  3040. else:
  3041. self.ui.geo_edit_toolbar.setVisible(False)
  3042. if tb & 64:
  3043. self.ui.grb_edit_toolbar.setVisible(True)
  3044. else:
  3045. self.ui.grb_edit_toolbar.setVisible(False)
  3046. if tb & 128:
  3047. self.ui.snap_toolbar.setVisible(True)
  3048. else:
  3049. self.ui.snap_toolbar.setVisible(False)
  3050. if tb & 256:
  3051. self.ui.toolbarshell.setVisible(True)
  3052. else:
  3053. self.ui.toolbarshell.setVisible(False)
  3054. def load_defaults(self, filename):
  3055. """
  3056. Loads the aplication's default settings from current_defaults.FlatConfig into
  3057. ``self.defaults``.
  3058. :return: None
  3059. """
  3060. try:
  3061. f = open(self.data_path + "/" + filename + ".FlatConfig")
  3062. options = f.read()
  3063. f.close()
  3064. except IOError:
  3065. self.log.error("Could not load defaults file.")
  3066. self.inform.emit('[ERROR] %s' %
  3067. _("Could not load defaults file."))
  3068. # in case the defaults file can't be loaded, show all toolbars
  3069. self.defaults["global_toolbar_view"] = 511
  3070. return
  3071. try:
  3072. defaults = json.loads(options)
  3073. except:
  3074. # in case the defaults file can't be loaded, show all toolbars
  3075. self.defaults["global_toolbar_view"] = 511
  3076. e = sys.exc_info()[0]
  3077. App.log.error(str(e))
  3078. self.inform.emit('[ERROR] %s' %
  3079. _("Failed to parse defaults file."))
  3080. return
  3081. self.defaults.update(defaults)
  3082. log.debug("FlatCAM defaults loaded from: %s" % filename)
  3083. # restore the toolbar view
  3084. self.restore_toolbar_view()
  3085. def on_import_preferences(self):
  3086. """
  3087. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  3088. ``self.defaults``.
  3089. :return: None
  3090. """
  3091. self.report_usage("on_import_preferences")
  3092. App.log.debug("on_import_preferences()")
  3093. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  3094. try:
  3095. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3096. directory=self.data_path,
  3097. filter=filter_)
  3098. except TypeError:
  3099. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3100. filter=filter_)
  3101. filename = str(filename)
  3102. if filename == "":
  3103. self.inform.emit('[WARNING_NOTCL] %s' %
  3104. _("FlatCAM preferences import cancelled."))
  3105. else:
  3106. try:
  3107. f = open(filename)
  3108. options = f.read()
  3109. f.close()
  3110. except IOError:
  3111. self.log.error("Could not load defaults file.")
  3112. self.inform.emit('[ERROR_NOTCL] %s' %
  3113. _("Could not load defaults file."))
  3114. return
  3115. try:
  3116. defaults_from_file = json.loads(options)
  3117. except Exception as e:
  3118. e = sys.exc_info()[0]
  3119. App.log.error(str(e))
  3120. self.inform.emit('[ERROR_NOTCL] %s' %
  3121. _("Failed to parse defaults file."))
  3122. return
  3123. self.defaults.update(defaults_from_file)
  3124. self.on_preferences_edited()
  3125. self.inform.emit('[success] %s: %s' %
  3126. (_("Imported Defaults from"), filename))
  3127. def on_export_preferences(self):
  3128. """
  3129. Save the defaults dictionary to a file.
  3130. :return: None
  3131. """
  3132. self.report_usage("on_export_preferences")
  3133. App.log.debug("on_export_preferences()")
  3134. defaults_file_content = None
  3135. self.date = str(datetime.today()).rpartition('.')[0]
  3136. self.date = ''.join(c for c in self.date if c not in ':-')
  3137. self.date = self.date.replace(' ', '_')
  3138. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  3139. try:
  3140. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  3141. caption=_("Export FlatCAM Preferences"),
  3142. directory=self.data_path + '/preferences_' + self.date,
  3143. filter=filter__
  3144. )
  3145. except TypeError:
  3146. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  3147. filter=filter__)
  3148. filename = str(filename)
  3149. defaults_from_file = {}
  3150. if filename == "":
  3151. self.inform.emit('[WARNING_NOTCL] %s' %
  3152. _("FlatCAM preferences export cancelled."))
  3153. return
  3154. else:
  3155. try:
  3156. f = open(filename, 'w')
  3157. defaults_file_content = f.read()
  3158. f.close()
  3159. except PermissionError:
  3160. self.inform.emit('[WARNING] %s' %
  3161. _("Permission denied, saving not possible.\n"
  3162. "Most likely another app is holding the file open and not accessible."))
  3163. return
  3164. except IOError:
  3165. App.log.debug('Creating a new preferences file ...')
  3166. f = open(filename, 'w')
  3167. json.dump({}, f)
  3168. f.close()
  3169. except:
  3170. e = sys.exc_info()[0]
  3171. App.log.error("Could not load defaults file.")
  3172. App.log.error(str(e))
  3173. self.inform.emit('[ERROR_NOTCL] %s' %
  3174. _("Could not load preferences file."))
  3175. return
  3176. try:
  3177. defaults_from_file = json.loads(defaults_file_content)
  3178. except:
  3179. App.log.warning("Trying to read an empty Preferences file. Continue.")
  3180. # Update options
  3181. self.defaults_read_form()
  3182. defaults_from_file.update(self.defaults)
  3183. self.propagate_defaults(silent=True)
  3184. # Save update options
  3185. try:
  3186. f = open(filename, "w")
  3187. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  3188. f.close()
  3189. except:
  3190. self.inform.emit('[ERROR_NOTCL] %s' %
  3191. _("Failed to write defaults to file."))
  3192. return
  3193. if self.defaults["global_open_style"] is False:
  3194. self.file_opened.emit("preferences", filename)
  3195. self.file_saved.emit("preferences", filename)
  3196. self.inform.emit('[success] %s: %s' %
  3197. (_("Exported preferences to"), filename))
  3198. def on_preferences_open_folder(self):
  3199. """
  3200. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  3201. :return: None
  3202. """
  3203. self.report_usage("on_preferences_open_folder()")
  3204. if sys.platform == 'win32':
  3205. subprocess.Popen('explorer %s' % self.data_path)
  3206. elif sys.platform == 'darwin':
  3207. os.system('open "%s"' % self.data_path)
  3208. else:
  3209. subprocess.Popen(['xdg-open', self.data_path])
  3210. self.inform.emit('[success] %s' %
  3211. _("FlatCAM Preferences Folder opened."))
  3212. def save_geometry(self, x, y, width, height, notebook_width):
  3213. """
  3214. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  3215. launch of the application.
  3216. :param x: X position of the main window
  3217. :param y: Y position of the main window
  3218. :param width: width of the main window
  3219. :param height: height of the main window
  3220. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  3221. :return: None
  3222. """
  3223. self.defaults["global_def_win_x"] = x
  3224. self.defaults["global_def_win_y"] = y
  3225. self.defaults["global_def_win_w"] = width
  3226. self.defaults["global_def_win_h"] = height
  3227. self.defaults["global_def_notebook_width"] = notebook_width
  3228. self.save_defaults()
  3229. def restore_main_win_geom(self):
  3230. try:
  3231. self.ui.setGeometry(self.defaults["global_def_win_x"],
  3232. self.defaults["global_def_win_y"],
  3233. self.defaults["global_def_win_w"],
  3234. self.defaults["global_def_win_h"])
  3235. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  3236. except KeyError as e:
  3237. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  3238. def message_dialog(self, title, message, kind="info"):
  3239. """
  3240. Builds and show a custom QMessageBox to be used in FlatCAM.
  3241. :param title: title of the QMessageBox
  3242. :param message: message to be displayed
  3243. :param kind: type of QMessageBox; will display a specific icon.
  3244. :return:
  3245. """
  3246. icon = {"info": QtWidgets.QMessageBox.Information,
  3247. "warning": QtWidgets.QMessageBox.Warning,
  3248. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3249. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  3250. dlg.setText(message)
  3251. dlg.exec_()
  3252. def register_recent(self, kind, filename):
  3253. """
  3254. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  3255. dictionary.
  3256. :param kind: type of file that was opened
  3257. :param filename: the path and file name for the file that was opened
  3258. :return:
  3259. """
  3260. self.log.debug("register_recent()")
  3261. self.log.debug(" %s" % kind)
  3262. self.log.debug(" %s" % filename)
  3263. record = {'kind': str(kind), 'filename': str(filename)}
  3264. if record in self.recent:
  3265. return
  3266. if record in self.recent_projects:
  3267. return
  3268. if record['kind'] == 'project':
  3269. self.recent_projects.insert(0, record)
  3270. else:
  3271. self.recent.insert(0, record)
  3272. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3273. self.recent.pop()
  3274. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3275. self.recent_projects.pop()
  3276. try:
  3277. f = open(self.data_path + '/recent.json', 'w')
  3278. except IOError:
  3279. App.log.error("Failed to open recent items file for writing.")
  3280. self.inform.emit('[ERROR_NOTCL] %s' %
  3281. _('Failed to open recent files file for writing.'))
  3282. return
  3283. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3284. f.close()
  3285. try:
  3286. fp = open(self.data_path + '/recent_projects.json', 'w')
  3287. except IOError:
  3288. App.log.error("Failed to open recent items file for writing.")
  3289. self.inform.emit('[ERROR_NOTCL] %s' %
  3290. _('Failed to open recent projects file for writing.'))
  3291. return
  3292. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3293. fp.close()
  3294. # Re-build the recent items menu
  3295. self.setup_recent_items()
  3296. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3297. """
  3298. Creates a new specialized FlatCAMObj and attaches it to the application,
  3299. this is, updates the GUI accordingly, any other records and plots it.
  3300. This method is thread-safe.
  3301. Notes:
  3302. * If the name is in use, the self.collection will modify it
  3303. when appending it to the collection. There is no need to handle
  3304. name conflicts here.
  3305. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3306. :type kind: str
  3307. :param name: Name for the object.
  3308. :type name: str
  3309. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3310. The function is called with 2 parameters: the new object and the App instance.
  3311. :type initialize: function
  3312. :param active:
  3313. :param fit:
  3314. :param plot: If to plot the resulting object
  3315. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3316. self.colleaction
  3317. :return: None
  3318. :rtype: None
  3319. """
  3320. App.log.debug("new_object()")
  3321. obj_plot = plot
  3322. obj_autoselected = autoselected
  3323. t0 = time.time() # Debug
  3324. # ## Create object
  3325. classdict = {
  3326. "gerber": FlatCAMGerber,
  3327. "excellon": FlatCAMExcellon,
  3328. "cncjob": FlatCAMCNCjob,
  3329. "geometry": FlatCAMGeometry
  3330. }
  3331. App.log.debug("Calling object constructor...")
  3332. obj = classdict[kind](name)
  3333. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3334. # Set options from "Project options" form
  3335. self.options_read_form()
  3336. # IMPORTANT
  3337. # The key names in defaults and options dictionary's are not random:
  3338. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3339. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  3340. # the options from project options form into the self.options. After that, below, depending on the type of
  3341. # object that is created, it will strip the name of the object and the underline (if the original key was
  3342. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3343. # "toolchange"
  3344. for option in self.options:
  3345. if option.find(kind + "_") == 0:
  3346. oname = option[len(kind) + 1:]
  3347. obj.options[oname] = self.options[option]
  3348. obj.isHovering = False
  3349. obj.notHovering = True
  3350. # Initialize as per user request
  3351. # User must take care to implement initialize
  3352. # in a thread-safe way as is is likely that we
  3353. # have been invoked in a separate thread.
  3354. t1 = time.time()
  3355. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3356. try:
  3357. return_value = initialize(obj, self)
  3358. except Exception as e:
  3359. msg = '[ERROR_NOTCL] %s' % \
  3360. _("An internal error has ocurred. See shell.\n")
  3361. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3362. msg += traceback.format_exc()
  3363. self.inform.emit(msg)
  3364. # if str(e) == "Empty Geometry":
  3365. # self.inform.emit("[ERROR_NOTCL] )
  3366. # else:
  3367. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  3368. return "fail"
  3369. t2 = time.time()
  3370. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3371. if return_value == 'fail':
  3372. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3373. return "fail"
  3374. # Check units and convert if necessary
  3375. # This condition CAN be true because initialize() can change obj.units
  3376. if self.options["units"].upper() != obj.units.upper():
  3377. self.inform.emit('%s: %s' %
  3378. (_("Converting units to "), self.options["units"]))
  3379. obj.convert_units(self.options["units"])
  3380. t3 = time.time()
  3381. self.log.debug("%f seconds converting units." % (t3 - t2))
  3382. # Create the bounding box for the object and then add the results to the obj.options
  3383. try:
  3384. xmin, ymin, xmax, ymax = obj.bounds()
  3385. obj.options['xmin'] = xmin
  3386. obj.options['ymin'] = ymin
  3387. obj.options['xmax'] = xmax
  3388. obj.options['ymax'] = ymax
  3389. except Exception as e:
  3390. log.warning("The object has no bounds properties. %s" % str(e))
  3391. return "fail"
  3392. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3393. # Move the object to the main thread and let the app know that it is available.
  3394. obj.moveToThread(self.main_thread)
  3395. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3396. return obj
  3397. def new_excellon_object(self):
  3398. """
  3399. Creates a new, blank Excellon object.
  3400. :return: None
  3401. """
  3402. self.report_usage("new_excellon_object()")
  3403. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3404. def new_geometry_object(self):
  3405. """
  3406. Creates a new, blank and single-tool Geometry object.
  3407. :return: None
  3408. """
  3409. self.report_usage("new_geometry_object()")
  3410. def initialize(obj, self):
  3411. obj.multitool = False
  3412. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3413. def new_gerber_object(self):
  3414. """
  3415. Creates a new, blank Gerber object.
  3416. :return: None
  3417. """
  3418. self.report_usage("new_gerber_object()")
  3419. def initialize(grb_obj, self):
  3420. grb_obj.multitool = False
  3421. grb_obj.source_file = []
  3422. grb_obj.multigeo = False
  3423. grb_obj.follow = False
  3424. grb_obj.apertures = {}
  3425. grb_obj.solid_geometry = []
  3426. try:
  3427. grb_obj.options['xmin'] = 0
  3428. grb_obj.options['ymin'] = 0
  3429. grb_obj.options['xmax'] = 0
  3430. grb_obj.options['ymax'] = 0
  3431. except KeyError:
  3432. pass
  3433. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3434. def on_object_created(self, obj, plot, autoselect):
  3435. """
  3436. Event callback for object creation.
  3437. It will add the new object to the collection. After that it will plot the object in a threaded way
  3438. :param obj: The newly created FlatCAM object.
  3439. :param plot: if the newly create object t obe plotted
  3440. :param autoselect: if the newly created object to be autoselected after creation
  3441. :return: None
  3442. """
  3443. t0 = time.time() # DEBUG
  3444. self.log.debug("on_object_created()")
  3445. # The Collection might change the name if there is a collision
  3446. self.collection.append(obj)
  3447. # after adding the object to the collection always update the list of objects that are in the collection
  3448. self.all_objects_list = self.collection.get_list()
  3449. # self.inform.emit('[selected] %s created & selected: %s' %
  3450. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3451. if obj.kind == 'gerber':
  3452. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3453. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3454. elif obj.kind == 'excellon':
  3455. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3456. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3457. elif obj.kind == 'cncjob':
  3458. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3459. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3460. elif obj.kind == 'geometry':
  3461. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3462. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3463. # update the SHELL auto-completer model with the name of the new object
  3464. self.myKeywords.append(obj.options['name'])
  3465. self.shell._edit.set_model_data(self.myKeywords)
  3466. self.ui.code_editor.set_model_data(self.myKeywords)
  3467. if autoselect:
  3468. # select the just opened object but deselect the previous ones
  3469. self.collection.set_all_inactive()
  3470. self.collection.set_active(obj.options["name"])
  3471. else:
  3472. self.collection.set_all_inactive()
  3473. # here it is done the object plotting
  3474. def worker_task(t_obj):
  3475. with self.proc_container.new(_("Plotting")):
  3476. if isinstance(t_obj, FlatCAMCNCjob):
  3477. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3478. else:
  3479. t_obj.plot()
  3480. t1 = time.time() # DEBUG
  3481. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3482. self.object_plotted.emit(t_obj)
  3483. # Send to worker
  3484. # self.worker.add_task(worker_task, [self])
  3485. if plot is True:
  3486. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3487. def on_object_changed(self, obj):
  3488. """
  3489. Called whenever the geometry of the object was changed in some way.
  3490. This require the update of it's bounding values so it can be the selected on canvas.
  3491. Update the bounding box data from obj.options
  3492. :param obj: the object that was changed
  3493. :return: None
  3494. """
  3495. xmin, ymin, xmax, ymax = obj.bounds()
  3496. obj.options['xmin'] = xmin
  3497. obj.options['ymin'] = ymin
  3498. obj.options['xmax'] = xmax
  3499. obj.options['ymax'] = ymax
  3500. log.debug("Object changed, updating the bounding box data on self.options")
  3501. # delete the old selection shape
  3502. self.delete_selection_shape()
  3503. self.should_we_save = True
  3504. def on_object_plotted(self, obj):
  3505. """
  3506. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3507. :param obj: object to be fit into view
  3508. :return: None
  3509. """
  3510. self.on_zoom_fit(None)
  3511. def options_read_form(self):
  3512. """
  3513. Same as it's equivalent from the defaults.
  3514. self.options use to store the preferences per project. No longer used.
  3515. :return: None
  3516. """
  3517. for option in self.options_form_fields:
  3518. self.options[option] = self.options_form_fields[option].get_value()
  3519. def options_write_form(self):
  3520. """
  3521. Same as it's equivalent from the defaults.
  3522. self.options use to store the preferences per project. No longer used.
  3523. :return: None
  3524. """
  3525. for option in self.options:
  3526. self.options_write_form_field(option)
  3527. def options_write_form_field(self, field):
  3528. """
  3529. Same as it's equivalent from the defaults.
  3530. self.options use to store the preferences per project. No longer used.
  3531. :return: None
  3532. """
  3533. try:
  3534. self.options_form_fields[field].set_value(self.options[field])
  3535. except KeyError:
  3536. # Changed from error to debug. This allows to have data stored
  3537. # which is not user-editable.
  3538. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  3539. pass
  3540. def on_about(self):
  3541. """
  3542. Displays the "about" dialog found in the Menu --> Help.
  3543. :return: None
  3544. """
  3545. self.report_usage("on_about")
  3546. version = self.version
  3547. version_date = self.version_date
  3548. beta = self.beta
  3549. class AboutDialog(QtWidgets.QDialog):
  3550. def __init__(self, parent=None):
  3551. QtWidgets.QDialog.__init__(self, parent)
  3552. # Icon and title
  3553. self.setWindowIcon(parent.app_icon)
  3554. self.setWindowTitle(_("About FlatCAM"))
  3555. self.resize(600, 200)
  3556. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3557. # self.setStyleSheet(
  3558. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3559. # "background-attachment: fixed"
  3560. # )
  3561. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3562. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3563. # palette = QtGui.QPalette()
  3564. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3565. # self.setPalette(palette)
  3566. logo = QtWidgets.QLabel()
  3567. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3568. title = QtWidgets.QLabel(
  3569. "<font size=8><B>FlatCAM</B></font><BR>"
  3570. "{title}<BR>"
  3571. "<BR>"
  3572. "<BR>"
  3573. # "<B>{devel}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3574. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3575. # "<b>{down}</B> area &nbsp;&nbsp;&nbsp;&nbsp;"
  3576. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3577. # "<b> {issue}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3578. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3579. "<B>{issue}</B></a><BR>".format(
  3580. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3581. devel=_("Development"),
  3582. down=_("DOWNLOAD"),
  3583. issue=_("Issue tracker"))
  3584. )
  3585. title.setOpenExternalLinks(True)
  3586. closebtn = QtWidgets.QPushButton(_("Close"))
  3587. tab_widget = QtWidgets.QTabWidget()
  3588. description_label = QtWidgets.QLabel(
  3589. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3590. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3591. version=version,
  3592. beta=('BETA' if beta else ''),
  3593. date=version_date,
  3594. arch=platform.architecture()[0])
  3595. )
  3596. description_label.setOpenExternalLinks(True)
  3597. license_label = QtWidgets.QLabel(
  3598. _(
  3599. '(c) Copyright 2014 Juan Pablo Caram.\n\n'
  3600. 'Licensed under the MIT license:\n'
  3601. 'http://www.opensource.org/licenses/mit-license.php\n\n'
  3602. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3603. 'of this software and associated documentation files (the "Software"), to deal\n'
  3604. 'in the Software without restriction, including without limitation the rights\n'
  3605. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3606. 'copies of the Software, and to permit persons to whom the Software is\n'
  3607. ' furnished to do so, subject to the following conditions:\n\n'
  3608. 'The above copyright notice and this permission notice shall be included in\n'
  3609. 'all copies or substantial portions of the Software.\n\n'
  3610. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3611. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3612. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3613. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3614. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3615. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3616. 'THE SOFTWARE.'
  3617. )
  3618. )
  3619. license_label.setOpenExternalLinks(True)
  3620. # layouts
  3621. layout1 = QtWidgets.QVBoxLayout()
  3622. layout1_1 = QtWidgets.QHBoxLayout()
  3623. layout1_2 = QtWidgets.QHBoxLayout()
  3624. layout2 = QtWidgets.QHBoxLayout()
  3625. layout3 = QtWidgets.QHBoxLayout()
  3626. self.setLayout(layout1)
  3627. layout1.addLayout(layout1_1)
  3628. layout1.addLayout(layout1_2)
  3629. layout1.addLayout(layout2)
  3630. layout1.addLayout(layout3)
  3631. layout1_1.addStretch()
  3632. layout1_1.addWidget(description_label)
  3633. layout1_2.addWidget(tab_widget)
  3634. self.splash_tab = QtWidgets.QWidget()
  3635. self.splash_tab.setObjectName("splash_about")
  3636. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3637. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3638. tab_widget.addTab(self.splash_tab, _("Splash"))
  3639. self.programmmers_tab = QtWidgets.QWidget()
  3640. self.programmmers_tab.setObjectName("programmers_about")
  3641. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3642. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3643. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3644. self.translators_tab = QtWidgets.QWidget()
  3645. self.translators_tab.setObjectName("translators_about")
  3646. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3647. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3648. tab_widget.addTab(self.translators_tab, _("Translators"))
  3649. self.license_tab = QtWidgets.QWidget()
  3650. self.license_tab.setObjectName("license_about")
  3651. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3652. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3653. tab_widget.addTab(self.license_tab, _("License"))
  3654. self.splash_tab_layout.addWidget(logo, stretch=0)
  3655. self.splash_tab_layout.addWidget(title, stretch=1)
  3656. pal = QtGui.QPalette()
  3657. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3658. self.prog_form_lay = QtWidgets.QFormLayout()
  3659. self.prog_form_lay.setHorizontalSpacing(20)
  3660. prog_widget = QtWidgets.QWidget()
  3661. prog_widget.setLayout(self.prog_form_lay)
  3662. prog_scroll = QtWidgets.QScrollArea()
  3663. prog_scroll.setWidget(prog_widget)
  3664. prog_scroll.setWidgetResizable(True)
  3665. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3666. prog_scroll.setPalette(pal)
  3667. self.programmmers_tab_layout.addWidget(prog_scroll)
  3668. self.prog_form_lay.addRow(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")),
  3669. QtWidgets.QLabel('<b>%s</b>' % _("Status")))
  3670. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Juan Pablo Caram"),
  3671. QtWidgets.QLabel('%s' % _("Program Author")))
  3672. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Denis Hayrullin"))
  3673. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Kamil Sopko"))
  3674. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marius Stanciu"),
  3675. QtWidgets.QLabel('%s' % _("Maintainer >=2019")))
  3676. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3677. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Alexandru Lazar"))
  3678. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Matthieu Berthomé"))
  3679. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Evans"))
  3680. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Victor Benso"))
  3681. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3682. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Barnaby Walters"))
  3683. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"))
  3684. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lei Zheng"))
  3685. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marco A Quezada"))
  3686. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3687. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Cedric Dussud"))
  3688. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Chris Hemingway"))
  3689. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Damian Wrobel"))
  3690. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Daniel Sallin"))
  3691. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3692. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Bruno Vunderl"))
  3693. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Gonzalo Lopez"))
  3694. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jakob Staudt"))
  3695. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Smith"))
  3696. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3697. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lubos Medovarsky"))
  3698. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Steve Martina"))
  3699. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Thomas Duffin"))
  3700. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3701. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Idechix"))
  3702. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@SM"))
  3703. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@grbf"))
  3704. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Symonty"))
  3705. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@mgix"))
  3706. self.translator_grid_lay = QtWidgets.QGridLayout()
  3707. # trans_widget = QtWidgets.QWidget()
  3708. # trans_widget.setLayout(self.translator_grid_lay)
  3709. # self.translators_tab_layout.addWidget(trans_widget)
  3710. # self.translators_tab_layout.addStretch()
  3711. trans_widget = QtWidgets.QWidget()
  3712. trans_widget.setLayout(self.translator_grid_lay)
  3713. trans_scroll = QtWidgets.QScrollArea()
  3714. trans_scroll.setWidget(trans_widget)
  3715. trans_scroll.setWidgetResizable(True)
  3716. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3717. trans_scroll.setPalette(pal)
  3718. self.translators_tab_layout.addWidget(trans_scroll)
  3719. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  3720. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  3721. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3722. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Brasilian - Portuguese"), 1, 0)
  3723. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  3724. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 1, 2)
  3725. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  3726. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 2, 1)
  3727. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 2)
  3728. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  3729. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 3, 1)
  3730. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  3731. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  3732. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  3733. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  3734. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  3735. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  3736. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 2)
  3737. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  3738. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 6, 1)
  3739. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 2)
  3740. self.translator_grid_lay.setColumnStretch(0, 0)
  3741. self.translators_tab_layout.addStretch()
  3742. self.license_tab_layout.addWidget(license_label)
  3743. self.license_tab_layout.addStretch()
  3744. layout3.addStretch()
  3745. layout3.addWidget(closebtn)
  3746. closebtn.clicked.connect(self.accept)
  3747. AboutDialog(self.ui).exec_()
  3748. def on_file_savedefaults(self):
  3749. """
  3750. Callback for menu item File->Save Defaults. Saves application default options
  3751. ``self.defaults`` to current_defaults.FlatConfig.
  3752. :return: None
  3753. """
  3754. self.save_defaults()
  3755. # def on_app_exit(self):
  3756. # self.report_usage("on_app_exit()")
  3757. #
  3758. # if self.collection.get_list():
  3759. # msgbox = QtWidgets.QMessageBox()
  3760. # # msgbox.setText("<B>Save changes ...</B>")
  3761. # msgbox.setText("There are files/objects opened in FlatCAM. "
  3762. # "\n"
  3763. # "Do you want to Save the project?")
  3764. # msgbox.setWindowTitle("Save changes")
  3765. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3766. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  3767. # QtWidgets.QMessageBox.Cancel)
  3768. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  3769. #
  3770. # response = msgbox.exec_()
  3771. #
  3772. # if response == QtWidgets.QMessageBox.Yes:
  3773. # self.on_file_saveprojectas(thread=False)
  3774. # elif response == QtWidgets.QMessageBox.Cancel:
  3775. # return
  3776. # self.save_defaults()
  3777. # else:
  3778. # self.save_defaults()
  3779. # log.debug("Application defaults saved ... Exit event.")
  3780. # QtWidgets.qApp.quit()
  3781. def save_defaults(self, silent=False, data_path=None, first_time=False):
  3782. """
  3783. Saves application default options
  3784. ``self.defaults`` to current_defaults.FlatConfig file.
  3785. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  3786. used at the next launch of the application.
  3787. :param silent: whether to display a message in status bar or not; boolean
  3788. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  3789. When the application is portable it should be a mobile location.
  3790. :return: None
  3791. """
  3792. self.report_usage("save_defaults")
  3793. if data_path is None:
  3794. data_path = self.data_path
  3795. # Read options from file
  3796. try:
  3797. f = open(data_path + "/current_defaults.FlatConfig")
  3798. defaults_file_content = f.read()
  3799. f.close()
  3800. except:
  3801. e = sys.exc_info()[0]
  3802. App.log.error("Could not load defaults file.")
  3803. App.log.error(str(e))
  3804. self.inform.emit('[ERROR_NOTCL] %s' %
  3805. _("Could not load defaults file."))
  3806. return
  3807. try:
  3808. defaults = json.loads(defaults_file_content)
  3809. except:
  3810. e = sys.exc_info()[0]
  3811. App.log.error("Failed to parse defaults file.")
  3812. App.log.error(str(e))
  3813. self.inform.emit('[ERROR_NOTCL] %s' %
  3814. _("Failed to parse defaults file."))
  3815. return
  3816. # Update options
  3817. self.defaults_read_form()
  3818. defaults.update(self.defaults)
  3819. self.propagate_defaults(silent=True)
  3820. # Save the toolbar view
  3821. tb_status = 0
  3822. if self.ui.toolbarfile.isVisible():
  3823. tb_status += 1
  3824. if self.ui.toolbargeo.isVisible():
  3825. tb_status += 2
  3826. if self.ui.toolbarview.isVisible():
  3827. tb_status += 4
  3828. if self.ui.toolbartools.isVisible():
  3829. tb_status += 8
  3830. if self.ui.exc_edit_toolbar.isVisible():
  3831. tb_status += 16
  3832. if self.ui.geo_edit_toolbar.isVisible():
  3833. tb_status += 32
  3834. if self.ui.grb_edit_toolbar.isVisible():
  3835. tb_status += 64
  3836. if self.ui.snap_toolbar.isVisible():
  3837. tb_status += 128
  3838. if self.ui.toolbarshell.isVisible():
  3839. tb_status += 256
  3840. if first_time is False:
  3841. self.defaults["global_toolbar_view"] = tb_status
  3842. # Save update options
  3843. try:
  3844. f = open(data_path + "/current_defaults.FlatConfig", "w")
  3845. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  3846. f.close()
  3847. except:
  3848. self.inform.emit('[ERROR_NOTCL] %s' %
  3849. _("Failed to write defaults to file."))
  3850. return
  3851. if not silent:
  3852. self.inform.emit('[success] %s' %
  3853. _("Preferences saved."))
  3854. def save_factory_defaults(self, silent=False, data_path=None):
  3855. """
  3856. Saves application factory default options
  3857. ``self.defaults`` to factory_defaults.FlatConfig.
  3858. It's a one time job done just after the first install.
  3859. :param silent: whether to display a message in status bar or not; boolean
  3860. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  3861. When the application is portable it should be a mobile location.
  3862. :return: None
  3863. """
  3864. self.report_usage("save_factory_defaults")
  3865. if data_path is None:
  3866. data_path = self.data_path
  3867. # Read options from file
  3868. try:
  3869. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  3870. factory_defaults_file_content = f_f_def.read()
  3871. f_f_def.close()
  3872. except:
  3873. e = sys.exc_info()[0]
  3874. App.log.error("Could not load factory defaults file.")
  3875. App.log.error(str(e))
  3876. self.inform.emit('[ERROR_NOTCL] %s' %
  3877. _("Could not load factory defaults file."))
  3878. return
  3879. try:
  3880. factory_defaults = json.loads(factory_defaults_file_content)
  3881. except:
  3882. e = sys.exc_info()[0]
  3883. App.log.error("Failed to parse factory defaults file.")
  3884. App.log.error(str(e))
  3885. self.inform.emit('[ERROR_NOTCL] %s' %
  3886. _("Failed to parse factory defaults file."))
  3887. return
  3888. # Update options
  3889. self.defaults_read_form()
  3890. factory_defaults.update(self.defaults)
  3891. self.propagate_defaults(silent=True)
  3892. # Save update options
  3893. try:
  3894. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  3895. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3896. f_f_def_s.close()
  3897. except:
  3898. self.inform.emit('[ERROR_NOTCL] %s' %
  3899. _("Failed to write factory defaults to file."))
  3900. return
  3901. if silent is False:
  3902. self.inform.emit(_("Factory defaults saved."))
  3903. def final_save(self):
  3904. """
  3905. Callback for doing a preferences save to file whenever the application is about to quit.
  3906. If the project has changes, it will ask the user to save the project.
  3907. :return: None
  3908. """
  3909. if self.save_in_progress:
  3910. self.inform.emit('[WARNING_NOTCL] %s' %
  3911. _("Application is saving the project. Please wait ..."))
  3912. return
  3913. if self.should_we_save and self.collection.get_list():
  3914. msgbox = QtWidgets.QMessageBox()
  3915. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  3916. "\n"
  3917. "Do you want to Save the project?"))
  3918. msgbox.setWindowTitle(_("Save changes"))
  3919. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3920. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  3921. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  3922. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3923. msgbox.setDefaultButton(bt_yes)
  3924. msgbox.exec_()
  3925. response = msgbox.clickedButton()
  3926. if response == bt_yes:
  3927. try:
  3928. self.trayIcon.hide()
  3929. except:
  3930. pass
  3931. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  3932. elif response == bt_no:
  3933. try:
  3934. self.trayIcon.hide()
  3935. except:
  3936. pass
  3937. self.quit_application()
  3938. elif response == bt_cancel:
  3939. return
  3940. else:
  3941. try:
  3942. self.trayIcon.hide()
  3943. except:
  3944. pass
  3945. self.quit_application()
  3946. def quit_application(self):
  3947. """
  3948. Called (as a pyslot or not) when the application is quit.
  3949. :return: None
  3950. """
  3951. self.save_defaults()
  3952. log.debug("App.final_save() --> App Defaults saved.")
  3953. if self.cmd_line_headless != 1:
  3954. # save app state to file
  3955. settings = QSettings("Open Source", "FlatCAM")
  3956. settings.setValue('saved_gui_state', self.ui.saveState())
  3957. settings.setValue('maximized_gui', self.ui.isMaximized())
  3958. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  3959. settings.setValue(
  3960. 'notebook_font_size',
  3961. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  3962. )
  3963. settings.setValue('axis_font_size',
  3964. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value())
  3965. settings.setValue(
  3966. 'textbox_font_size',
  3967. self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  3968. )
  3969. settings.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  3970. # This will write the setting to the platform specific storage.
  3971. del settings
  3972. log.debug("App.final_save() --> App UI state saved.")
  3973. QtWidgets.qApp.quit()
  3974. def on_portable_checked(self, state):
  3975. """
  3976. Callback called when the checkbox in Preferences GUI is checked.
  3977. It will set the application as portable by creating the preferences and recent files in the
  3978. 'config' folder found in the FlatCAM installation folder.
  3979. :param state: boolean, the state of the checkbox when clicked/checked
  3980. :return:
  3981. """
  3982. line_no = 0
  3983. data = None
  3984. if sys.platform != 'win32':
  3985. # this won't work in Linux or MacOS
  3986. return
  3987. # test if the app was frozen and choose the path for the configuration file
  3988. if getattr(sys, "frozen", False) is True:
  3989. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  3990. else:
  3991. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  3992. config_file = current_data_path + '\\configuration.txt'
  3993. try:
  3994. with open(config_file, 'r') as f:
  3995. try:
  3996. data = f.readlines()
  3997. except Exception as e:
  3998. log.debug('App.__init__() -->%s' % str(e))
  3999. return
  4000. except FileNotFoundError:
  4001. pass
  4002. for line in data:
  4003. line = line.strip('\n')
  4004. param = str(line).rpartition('=')
  4005. if param[0] == 'portable':
  4006. break
  4007. line_no += 1
  4008. if state:
  4009. data[line_no] = 'portable=True\n'
  4010. # create the new defauults files
  4011. # create current_defaults.FlatConfig file if there is none
  4012. try:
  4013. f = open(current_data_path + '/current_defaults.FlatConfig')
  4014. f.close()
  4015. except IOError:
  4016. App.log.debug('Creating empty current_defaults.FlatConfig')
  4017. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  4018. json.dump({}, f)
  4019. f.close()
  4020. # create factory_defaults.FlatConfig file if there is none
  4021. try:
  4022. f = open(current_data_path + '/factory_defaults.FlatConfig')
  4023. f.close()
  4024. except IOError:
  4025. App.log.debug('Creating empty factory_defaults.FlatConfig')
  4026. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  4027. json.dump({}, f)
  4028. f.close()
  4029. try:
  4030. f = open(current_data_path + '/recent.json')
  4031. f.close()
  4032. except IOError:
  4033. App.log.debug('Creating empty recent.json')
  4034. f = open(current_data_path + '/recent.json', 'w')
  4035. json.dump([], f)
  4036. f.close()
  4037. try:
  4038. fp = open(current_data_path + '/recent_projects.json')
  4039. fp.close()
  4040. except IOError:
  4041. App.log.debug('Creating empty recent_projects.json')
  4042. fp = open(current_data_path + '/recent_projects.json', 'w')
  4043. json.dump([], fp)
  4044. fp.close()
  4045. # save the current defaults to the new defaults file
  4046. self.save_defaults(silent=True, data_path=current_data_path)
  4047. self.save_factory_defaults(silent=True, data_path=current_data_path)
  4048. else:
  4049. data[line_no] = 'portable=False\n'
  4050. with open(config_file, 'w') as f:
  4051. f.writelines(data)
  4052. def on_toggle_shell(self):
  4053. """
  4054. Toggle shell: if is visible close it, if it is closed then open it
  4055. :return:
  4056. """
  4057. self.report_usage("on_toggle_shell()")
  4058. if self.ui.shell_dock.isVisible():
  4059. self.ui.shell_dock.hide()
  4060. else:
  4061. self.ui.shell_dock.show()
  4062. def on_register_files(self, obj_type=None):
  4063. """
  4064. Called whenever there is a need to register file extensions with FlatCAM.
  4065. Works only in Windows and should be called only when FlatCAM is run in Windows.
  4066. :param obj_type: the type of object to be register for.
  4067. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  4068. :return: None
  4069. """
  4070. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  4071. new_reg_path = 'Software\\Classes\\'
  4072. # find if the current user is admin
  4073. try:
  4074. is_admin = os.getuid() == 0
  4075. except AttributeError:
  4076. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  4077. if is_admin is True:
  4078. root_path = winreg.HKEY_LOCAL_MACHINE
  4079. else:
  4080. root_path = winreg.HKEY_CURRENT_USER
  4081. # create the keys
  4082. def set_reg(name, root_path, new_reg_path, value):
  4083. try:
  4084. winreg.CreateKey(root_path, new_reg_path)
  4085. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  4086. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  4087. return True
  4088. except WindowsError:
  4089. return False
  4090. # delete key in registry
  4091. def delete_reg(root_path, reg_path, key_to_del):
  4092. key_to_del_path = reg_path + key_to_del
  4093. try:
  4094. winreg.DeleteKey(root_path, key_to_del_path)
  4095. return True
  4096. except WindowsError:
  4097. return False
  4098. if obj_type is None or obj_type == 'excellon':
  4099. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4100. exc_list = [x for x in exc_list if x != '']
  4101. # register all keys in the Preferences window
  4102. for ext in exc_list:
  4103. new_k = new_reg_path + '.%s' % ext
  4104. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4105. # and unregister those that are no longer in the Preferences windows but are in the file
  4106. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  4107. if ext not in exc_list:
  4108. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4109. # now write the updated extensions to the self.defaults
  4110. # new_ext = ''
  4111. # for ext in exc_list:
  4112. # new_ext = new_ext + ext + ', '
  4113. # self.defaults["fa_excellon"] = new_ext
  4114. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  4115. if obj_type is None or obj_type == 'gcode':
  4116. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4117. gco_list = [x for x in gco_list if x != '']
  4118. # register all keys in the Preferences window
  4119. for ext in gco_list:
  4120. new_k = new_reg_path + '.%s' % ext
  4121. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4122. # and unregister those that are no longer in the Preferences windows but are in the file
  4123. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  4124. if ext not in gco_list:
  4125. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4126. # now write the updated extensions to the self.defaults
  4127. # new_ext = ''
  4128. # for ext in gco_list:
  4129. # new_ext = new_ext + ext + ', '
  4130. # self.defaults["fa_gcode"] = new_ext
  4131. self.inform.emit('[success] %s' %
  4132. _("Selected GCode file extensions registered with FlatCAM."))
  4133. if obj_type is None or obj_type == 'gerber':
  4134. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4135. grb_list = [x for x in grb_list if x != '']
  4136. # register all keys in the Preferences window
  4137. for ext in grb_list:
  4138. new_k = new_reg_path + '.%s' % ext
  4139. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4140. # and unregister those that are no longer in the Preferences windows but are in the file
  4141. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  4142. if ext not in grb_list:
  4143. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4144. # now write the updated extensions to the self.defaults
  4145. # new_ext = ''
  4146. # for ext in grb_list:
  4147. # new_ext = new_ext + ext + ', '
  4148. # self.defaults["fa_gerber"] = new_ext
  4149. self.inform.emit('[success] %s' %
  4150. _("Selected Gerber file extensions registered with FlatCAM."))
  4151. def add_extension(self, ext_type):
  4152. if ext_type == 'excellon':
  4153. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4154. if new_ext == '':
  4155. return
  4156. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4157. if new_ext in old_val:
  4158. return
  4159. old_val.append(new_ext)
  4160. old_val.sort()
  4161. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4162. if ext_type == 'gcode':
  4163. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4164. if new_ext == '':
  4165. return
  4166. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4167. if new_ext in old_val:
  4168. return
  4169. old_val.append(new_ext)
  4170. old_val.sort()
  4171. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4172. if ext_type == 'gerber':
  4173. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4174. if new_ext == '':
  4175. return
  4176. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4177. if new_ext in old_val:
  4178. return
  4179. old_val.append(new_ext)
  4180. old_val.sort()
  4181. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4182. if ext_type == 'keyword':
  4183. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4184. if new_kw == '':
  4185. return
  4186. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4187. if new_kw in old_val:
  4188. return
  4189. old_val.append(new_kw)
  4190. old_val.sort()
  4191. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4192. # update the self.myKeywords so the model is updated
  4193. self.autocomplete_kw_list = \
  4194. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4195. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4196. self.shell._edit.set_model_data(self.myKeywords)
  4197. self.ui.code_editor.set_model_data(self.myKeywords)
  4198. def del_extension(self, ext_type):
  4199. if ext_type == 'excellon':
  4200. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4201. if new_ext == '':
  4202. return
  4203. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4204. if new_ext not in old_val:
  4205. return
  4206. old_val.remove(new_ext)
  4207. old_val.sort()
  4208. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4209. if ext_type == 'gcode':
  4210. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4211. if new_ext == '':
  4212. return
  4213. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4214. if new_ext not in old_val:
  4215. return
  4216. old_val.remove(new_ext)
  4217. old_val.sort()
  4218. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4219. if ext_type == 'gerber':
  4220. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4221. if new_ext == '':
  4222. return
  4223. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4224. if new_ext not in old_val:
  4225. return
  4226. old_val.remove(new_ext)
  4227. old_val.sort()
  4228. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4229. if ext_type == 'keyword':
  4230. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4231. if new_kw == '':
  4232. return
  4233. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4234. if new_kw not in old_val:
  4235. return
  4236. old_val.remove(new_kw)
  4237. old_val.sort()
  4238. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4239. # update the self.myKeywords so the model is updated
  4240. self.autocomplete_kw_list = \
  4241. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4242. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4243. self.shell._edit.set_model_data(self.myKeywords)
  4244. self.ui.code_editor.set_model_data(self.myKeywords)
  4245. def restore_extensions(self, ext_type):
  4246. if ext_type == 'excellon':
  4247. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  4248. # for the ability to open Excellon files with .txt extension
  4249. new_exc_list = deepcopy(self.exc_list)
  4250. try:
  4251. new_exc_list.remove('txt')
  4252. except ValueError:
  4253. pass
  4254. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  4255. if ext_type == 'gcode':
  4256. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  4257. if ext_type == 'gerber':
  4258. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  4259. if ext_type == 'keyword':
  4260. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  4261. # update the self.myKeywords so the model is updated
  4262. self.autocomplete_kw_list = self.default_keywords
  4263. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4264. self.shell._edit.set_model_data(self.myKeywords)
  4265. self.ui.code_editor.set_model_data(self.myKeywords)
  4266. def delete_all_extensions(self, ext_type):
  4267. if ext_type == 'excellon':
  4268. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4269. if ext_type == 'gcode':
  4270. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4271. if ext_type == 'gerber':
  4272. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4273. if ext_type == 'keyword':
  4274. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4275. # update the self.myKeywords so the model is updated
  4276. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4277. self.shell._edit.set_model_data(self.myKeywords)
  4278. self.ui.code_editor.set_model_data(self.myKeywords)
  4279. def on_edit_join(self, name=None):
  4280. """
  4281. Callback for Edit->Join. Joins the selected geometry objects into
  4282. a new one.
  4283. :return: None
  4284. """
  4285. self.report_usage("on_edit_join()")
  4286. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4287. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4288. tooldias = []
  4289. geo_type_list = set()
  4290. objs = self.collection.get_selected()
  4291. if len(objs) < 2:
  4292. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4293. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4294. return 'fail'
  4295. for obj in objs:
  4296. geo_type_list.add(obj.multigeo)
  4297. # if len(geo_type_list) == 1 means that all list elements are the same
  4298. if len(geo_type_list) != 1:
  4299. self.inform.emit('[ERROR] %s' %
  4300. _("Failed join. The Geometry objects are of different types.\n"
  4301. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4302. "convert from one to another and retry joining \n"
  4303. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4304. "the result may not be what was expected. \n"
  4305. "Check the generated GCODE."))
  4306. return
  4307. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4308. if True in geo_type_list:
  4309. def initialize(obj, app):
  4310. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=True)
  4311. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4312. for v in obj.tools.values():
  4313. v['data']['name'] = obj_name_multi
  4314. self.new_object("geometry", obj_name_multi, initialize)
  4315. else:
  4316. def initialize(obj, app):
  4317. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=False)
  4318. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4319. for v in obj.tools.values():
  4320. v['data']['name'] = obj_name_single
  4321. self.new_object("geometry", obj_name_single, initialize)
  4322. self.should_we_save = True
  4323. def on_edit_join_exc(self):
  4324. """
  4325. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4326. a new Excellon.
  4327. :return: None
  4328. """
  4329. self.report_usage("on_edit_join_exc()")
  4330. objs = self.collection.get_selected()
  4331. for obj in objs:
  4332. if not isinstance(obj, FlatCAMExcellon):
  4333. self.inform.emit('[ERROR_NOTCL] %s' %
  4334. _("Failed. Excellon joining works only on Excellon objects."))
  4335. return
  4336. if len(objs) < 2:
  4337. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4338. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4339. return 'fail'
  4340. def initialize(obj, app):
  4341. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=obj)
  4342. self.new_object("excellon", 'Combo_Excellon', initialize)
  4343. self.should_we_save = True
  4344. def on_edit_join_grb(self):
  4345. """
  4346. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4347. a new Gerber object.
  4348. :return: None
  4349. """
  4350. self.report_usage("on_edit_join_grb()")
  4351. objs = self.collection.get_selected()
  4352. for obj in objs:
  4353. if not isinstance(obj, FlatCAMGerber):
  4354. self.inform.emit('[ERROR_NOTCL] %s' %
  4355. _("Failed. Gerber joining works only on Gerber objects."))
  4356. return
  4357. if len(objs) < 2:
  4358. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4359. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4360. return 'fail'
  4361. def initialize(obj, app):
  4362. FlatCAMGerber.merge(self, grb_list=objs, grb_final=obj)
  4363. self.new_object("gerber", 'Combo_Gerber', initialize)
  4364. self.should_we_save = True
  4365. def on_convert_singlegeo_to_multigeo(self):
  4366. """
  4367. Called for converting a Geometry object from single-geo to multi-geo.
  4368. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4369. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4370. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4371. the solid-geometry of that tool.
  4372. :return: None
  4373. """
  4374. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4375. obj = self.collection.get_active()
  4376. if obj is None:
  4377. self.inform.emit('[ERROR_NOTCL] %s' %
  4378. _("Failed. Select a Geometry Object and try again."))
  4379. return
  4380. if not isinstance(obj, FlatCAMGeometry):
  4381. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4382. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4383. return
  4384. obj.multigeo = True
  4385. for tooluid, dict_value in obj.tools.items():
  4386. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4387. if not isinstance(obj.solid_geometry, list):
  4388. obj.solid_geometry = [obj.solid_geometry]
  4389. obj.solid_geometry[:] = []
  4390. obj.plot()
  4391. self.should_we_save = True
  4392. self.inform.emit('[success] %s' %
  4393. _("A Geometry object was converted to MultiGeo type."))
  4394. def on_convert_multigeo_to_singlegeo(self):
  4395. """
  4396. Called for converting a Geometry object from multi-geo to single-geo.
  4397. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4398. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4399. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4400. the solid-geometry of that tool.
  4401. :return: None
  4402. """
  4403. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4404. obj = self.collection.get_active()
  4405. if obj is None:
  4406. self.inform.emit('[ERROR_NOTCL] %s' %
  4407. _("Failed. Select a Geometry Object and try again."))
  4408. return
  4409. if not isinstance(obj, FlatCAMGeometry):
  4410. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4411. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4412. return
  4413. obj.multigeo = False
  4414. total_solid_geometry = []
  4415. for tooluid, dict_value in obj.tools.items():
  4416. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4417. # clear the original geometry
  4418. dict_value['solid_geometry'][:] = []
  4419. obj.solid_geometry = deepcopy(total_solid_geometry)
  4420. obj.plot()
  4421. self.should_we_save = True
  4422. self.inform.emit('[success] %s' %
  4423. _("A Geometry object was converted to SingleGeo type."))
  4424. def on_options_dict_change(self, field):
  4425. """
  4426. Called whenever a key changed in the self.options dictionary. This dict was used to store the preferences of the
  4427. current project. This feature is no longer used.
  4428. :param field:
  4429. :return:
  4430. """
  4431. self.options_write_form_field(field)
  4432. if field == "units":
  4433. self.set_screen_units(self.options['units'])
  4434. def on_defaults_dict_change(self, field):
  4435. """
  4436. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4437. Edit -> Preferences tab window.
  4438. :param field: the key of the self.defaults dictionary that was changed.
  4439. :return: None
  4440. """
  4441. self.defaults_write_form_field(field)
  4442. if field == "units":
  4443. self.set_screen_units(self.defaults['units'])
  4444. def set_screen_units(self, units):
  4445. """
  4446. Set the FlatCAM units on the status bar.
  4447. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4448. :return: None
  4449. """
  4450. self.ui.units_label.setText("[" + units.lower() + "]")
  4451. def on_toggle_units(self, no_pref=False):
  4452. """
  4453. Callback for the Units radio-button change in the Preferences tab.
  4454. Changes the application's default units adn for the project too.
  4455. If changing the project's units, the change propagates to all of
  4456. the objects in the project.
  4457. :return: None
  4458. """
  4459. self.report_usage("on_toggle_units")
  4460. if self.toggle_units_ignore:
  4461. return
  4462. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4463. # If option is the same, then ignore
  4464. if new_units == self.defaults["units"].upper():
  4465. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4466. return
  4467. # Options to scale
  4468. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin', "gerber_isooverlap",
  4469. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f"
  4470. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  4471. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4472. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  4473. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  4474. "excellon_editor_slot_lin_pitch",
  4475. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4476. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4477. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  4478. "geometry_feedrate_probe", "geometry_startz",
  4479. 'cncjob_tooldia',
  4480. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4481. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia"
  4482. "tools_2sided_drilldia", "tools_film_boundary",
  4483. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4484. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4485. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4486. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4487. "tools_transform_offset_y",
  4488. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4489. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4490. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4491. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4492. 'global_gridx', 'global_gridy', 'global_snap_max']
  4493. def scale_options(sfactor):
  4494. for dim in dimensions:
  4495. if dim == 'excellon_toolchangexy':
  4496. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4497. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4498. coords_xy[0] *= sfactor
  4499. coords_xy[1] *= sfactor
  4500. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4501. elif dim == 'geometry_toolchangexy':
  4502. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4503. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4504. coords_xy[0] *= sfactor
  4505. coords_xy[1] *= sfactor
  4506. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4507. elif dim == 'geometry_cnctooldia':
  4508. tools_diameters = []
  4509. try:
  4510. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4511. tools_diameters = [eval(a) for a in tools_string if a != '']
  4512. except Exception as e:
  4513. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4514. self.options['geometry_cnctooldia'] = ''
  4515. for t in range(len(tools_diameters)):
  4516. tools_diameters[t] *= sfactor
  4517. self.options['geometry_cnctooldia'] += "%f," % tools_diameters[t]
  4518. elif dim == 'tools_ncctools':
  4519. ncctools = []
  4520. try:
  4521. tools_string = self.defaults["tools_ncctools"].split(",")
  4522. ncctools = [eval(a) for a in tools_string if a != '']
  4523. except Exception as e:
  4524. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4525. self.options['tools_ncctools'] = ''
  4526. for t in range(len(ncctools)):
  4527. ncctools[t] *= sfactor
  4528. self.options['tools_ncctools'] += "%f," % ncctools[t]
  4529. elif dim == 'tools_solderpaste_tools':
  4530. sptools = []
  4531. try:
  4532. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4533. sptools = [eval(a) for a in tools_string if a != '']
  4534. except Exception as e:
  4535. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4536. self.options['tools_solderpaste_tools'] = ""
  4537. for t in range(len(sptools)):
  4538. sptools[t] *= sfactor
  4539. self.options['tools_solderpaste_tools'] += "%f," % sptools[t]
  4540. elif dim == 'tools_solderpaste_xy_toolchange':
  4541. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4542. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4543. sp_coords[0] *= sfactor
  4544. sp_coords[1] *= sfactor
  4545. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  4546. elif dim == 'global_gridx' or dim == 'global_gridy':
  4547. if new_units == 'IN':
  4548. val = 0.1
  4549. try:
  4550. val = float(self.defaults[dim]) * sfactor
  4551. except Exception as e:
  4552. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4553. self.options[dim] = float('%.6f' % val)
  4554. else:
  4555. val = 0.1
  4556. try:
  4557. val = float(self.defaults[dim]) * sfactor
  4558. except Exception as e:
  4559. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4560. self.options[dim] = float('%.4f' % val)
  4561. else:
  4562. val = 0.1
  4563. try:
  4564. val = float(self.options[dim]) * sfactor
  4565. except Exception as e:
  4566. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  4567. self.options[dim] = val
  4568. def scale_defaults(sfactor):
  4569. for dim in dimensions:
  4570. if dim == 'excellon_toolchangexy':
  4571. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4572. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4573. coords_xy[0] *= sfactor
  4574. coords_xy[1] *= sfactor
  4575. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4576. elif dim == 'geometry_toolchangexy':
  4577. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4578. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4579. coords_xy[0] *= sfactor
  4580. coords_xy[1] *= sfactor
  4581. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4582. elif dim == 'geometry_cnctooldia':
  4583. tools_diameters = []
  4584. try:
  4585. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4586. tools_diameters = [eval(a) for a in tools_string if a != '']
  4587. except Exception as e:
  4588. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4589. self.defaults['geometry_cnctooldia'] = ''
  4590. for t in range(len(tools_diameters)):
  4591. tools_diameters[t] *= sfactor
  4592. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  4593. elif dim == 'tools_ncctools':
  4594. ncctools = []
  4595. try:
  4596. tools_string = self.defaults["tools_ncctools"].split(",")
  4597. ncctools = [eval(a) for a in tools_string if a != '']
  4598. except Exception as e:
  4599. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4600. self.defaults['tools_ncctools'] = ''
  4601. for t in range(len(ncctools)):
  4602. ncctools[t] *= sfactor
  4603. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  4604. elif dim == 'tools_solderpaste_tools':
  4605. sptools = []
  4606. try:
  4607. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4608. sptools = [eval(a) for a in tools_string if a != '']
  4609. except Exception as e:
  4610. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4611. self.defaults['tools_solderpaste_tools'] = ""
  4612. for t in range(len(sptools)):
  4613. sptools[t] *= sfactor
  4614. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  4615. elif dim == 'tools_solderpaste_xy_toolchange':
  4616. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4617. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4618. sp_coords[0] *= sfactor
  4619. sp_coords[1] *= sfactor
  4620. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  4621. elif dim == 'global_gridx' or dim == 'global_gridy':
  4622. if new_units == 'IN':
  4623. val = 0.1
  4624. try:
  4625. val = float(self.defaults[dim]) * sfactor
  4626. except Exception as e:
  4627. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4628. self.defaults[dim] = float('%.6f' % val)
  4629. else:
  4630. val = 0.1
  4631. try:
  4632. val = float(self.defaults[dim]) * sfactor
  4633. except Exception as e:
  4634. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4635. self.defaults[dim] = float('%.4f' % val)
  4636. else:
  4637. val = 0.1
  4638. try:
  4639. val = float(self.defaults[dim]) * sfactor
  4640. except Exception as e:
  4641. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4642. self.defaults[dim] = val
  4643. # The scaling factor depending on choice of units.
  4644. factor = 1/25.4
  4645. if new_units == 'MM':
  4646. factor = 25.4
  4647. # Changing project units. Warn user.
  4648. msgbox = QtWidgets.QMessageBox()
  4649. msgbox.setWindowTitle(_("Toggle Units"))
  4650. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  4651. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4652. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  4653. "properties of all objects to be scaled accordingly.\nContinue?"))
  4654. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4655. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4656. msgbox.setDefaultButton(bt_ok)
  4657. msgbox.exec_()
  4658. response = msgbox.clickedButton()
  4659. if response == bt_ok:
  4660. if no_pref is False:
  4661. self.options_read_form()
  4662. scale_options(factor)
  4663. self.options_write_form()
  4664. self.defaults_read_form()
  4665. scale_defaults(factor)
  4666. self.defaults_write_form(fl_units=new_units)
  4667. # save the defaults to file, some may assume that the conversion is enough and it's not
  4668. self.on_save_button()
  4669. self.should_we_save = True
  4670. # change this only if the workspace is active
  4671. if self.defaults['global_workspace'] is True:
  4672. self.plotcanvas.draw_workspace()
  4673. # adjust the grid values on the main toolbar
  4674. dec = 6 if new_units == 'IN'else 4
  4675. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  4676. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  4677. if not self.ui.grid_gap_link_cb.isChecked():
  4678. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  4679. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  4680. for obj in self.collection.get_list():
  4681. obj.convert_units(new_units)
  4682. # make that the properties stored in the object are also updated
  4683. self.object_changed.emit(obj)
  4684. obj.build_ui()
  4685. current = self.collection.get_active()
  4686. if current is not None:
  4687. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4688. if not isinstance(current, FlatCAMGeometry):
  4689. current.to_form()
  4690. self.plot_all()
  4691. self.inform.emit('[success] %s: %s' %
  4692. (_("Converted units to"), new_units))
  4693. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4694. self.set_screen_units(new_units)
  4695. else:
  4696. # Undo toggling
  4697. self.toggle_units_ignore = True
  4698. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4699. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4700. else:
  4701. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4702. self.toggle_units_ignore = False
  4703. self.inform.emit('[WARNING_NOTCL]%s' %
  4704. _(" Units conversion cancelled."))
  4705. self.options_read_form()
  4706. self.defaults_read_form()
  4707. def on_toggle_units_click(self):
  4708. try:
  4709. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4710. except (TypeError, AttributeError):
  4711. pass
  4712. if self.defaults["units"] == 'MM':
  4713. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4714. else:
  4715. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4716. self.on_toggle_units(no_pref=True)
  4717. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4718. lambda: self.on_toggle_units(no_pref=False))
  4719. def on_fullscreen(self):
  4720. self.report_usage("on_fullscreen()")
  4721. if self.toggle_fscreen is False:
  4722. # self.ui.showFullScreen()
  4723. self.ui.setWindowFlags(self.ui.windowFlags() | Qt.FramelessWindowHint)
  4724. a = self.ui.geometry()
  4725. self.x_pos = a.x()
  4726. self.y_pos = a.y()
  4727. self.width = a.width()
  4728. self.height = a.height()
  4729. # set new geometry to full desktop rect
  4730. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  4731. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  4732. # everything else will not work without this hack. This happen in Windows.
  4733. # https://bugreports.qt.io/browse/QTBUG-41309
  4734. desktop = QtWidgets.QApplication.desktop()
  4735. screen = desktop.screenNumber(QtGui.QCursor.pos())
  4736. rec = desktop.screenGeometry(screen)
  4737. x = rec.x() - 1
  4738. y = rec.y() - 1
  4739. h = rec.height() + 2
  4740. w = rec.width() + 2
  4741. self.ui.setGeometry(x, y, w, h)
  4742. self.ui.show()
  4743. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4744. tb.setVisible(False)
  4745. self.ui.splitter_left.setVisible(False)
  4746. self.toggle_fscreen = True
  4747. else:
  4748. self.ui.setWindowFlags(self.ui.windowFlags() & ~Qt.FramelessWindowHint)
  4749. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  4750. self.ui.showNormal()
  4751. self.restore_toolbar_view()
  4752. self.ui.splitter_left.setVisible(True)
  4753. self.toggle_fscreen = False
  4754. def on_toggle_plotarea(self):
  4755. self.report_usage("on_toggle_plotarea()")
  4756. try:
  4757. name = self.ui.plot_tab_area.widget(0).objectName()
  4758. except AttributeError:
  4759. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4760. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4761. self.ui.plot_tab_area.protectTab(0)
  4762. return
  4763. if name != 'plotarea':
  4764. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4765. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4766. self.ui.plot_tab_area.protectTab(0)
  4767. else:
  4768. self.ui.plot_tab_area.closeTab(0)
  4769. def on_toggle_notebook(self):
  4770. if self.ui.splitter.sizes()[0] == 0:
  4771. self.ui.splitter.setSizes([1, 1])
  4772. else:
  4773. self.ui.splitter.setSizes([0, 1])
  4774. def on_toggle_axis(self):
  4775. self.report_usage("on_toggle_axis()")
  4776. if self.toggle_axis is False:
  4777. if self.is_legacy is False:
  4778. # self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4779. # self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4780. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  4781. parent=self.plotcanvas.view.scene)
  4782. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  4783. parent=self.plotcanvas.view.scene)
  4784. # self.plotcanvas.redraw()
  4785. else:
  4786. self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  4787. self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  4788. self.plotcanvas.canvas.draw()
  4789. pass
  4790. self.toggle_axis = True
  4791. else:
  4792. if self.is_legacy is False:
  4793. # self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4794. # self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4795. # self.plotcanvas.redraw()
  4796. self.plotcanvas.v_line.parent = None
  4797. self.plotcanvas.h_line.parent = None
  4798. else:
  4799. self.plotcanvas.axes.lines[:] = []
  4800. self.plotcanvas.canvas.draw()
  4801. self.toggle_axis = False
  4802. def on_toggle_grid(self):
  4803. self.report_usage("on_toggle_grid()")
  4804. self.ui.grid_snap_btn.trigger()
  4805. def on_options_combo_change(self, sel):
  4806. """
  4807. Called when the combo box to choose between application defaults and
  4808. project option changes value. The corresponding variables are
  4809. copied to the UI.
  4810. :param sel: The option index that was chosen.
  4811. :return: None
  4812. """
  4813. # combo_sel = self.ui.notebook.combo_options.get_active()
  4814. App.log.debug("Options --> %s" % sel)
  4815. # form = [self.defaults_form, self.options_form][sel]
  4816. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  4817. if sel == 0:
  4818. self.gen_form = self.ui.general_defaults_form
  4819. self.ger_form = self.ui.gerber_defaults_form
  4820. self.exc_form = self.ui.excellon_defaults_form
  4821. self.geo_form = self.ui.geometry_defaults_form
  4822. self.cnc_form = self.ui.cncjob_defaults_form
  4823. self.tools_form = self.ui.tools_defaults_form
  4824. self.fa_form = self.ui.util_defaults_form
  4825. elif sel == 1:
  4826. self.gen_form = self.ui.general_options_form
  4827. self.ger_form = self.ui.gerber_options_form
  4828. self.exc_form = self.ui.excellon_options_form
  4829. self.geo_form = self.ui.geometry_options_form
  4830. self.cnc_form = self.ui.cncjob_options_form
  4831. self.tools_form = self.ui.tools_options_form
  4832. self.fa_form = self.ui.util_options_form
  4833. else:
  4834. return
  4835. try:
  4836. self.ui.general_scroll_area.takeWidget()
  4837. except:
  4838. self.log.debug("Nothing to remove")
  4839. self.ui.general_scroll_area.setWidget(self.gen_form)
  4840. self.gen_form.show()
  4841. try:
  4842. self.ui.gerber_scroll_area.takeWidget()
  4843. except:
  4844. self.log.debug("Nothing to remove")
  4845. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  4846. self.ger_form.show()
  4847. try:
  4848. self.ui.excellon_scroll_area.takeWidget()
  4849. except:
  4850. self.log.debug("Nothing to remove")
  4851. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  4852. self.exc_form.show()
  4853. try:
  4854. self.ui.geometry_scroll_area.takeWidget()
  4855. except:
  4856. self.log.debug("Nothing to remove")
  4857. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  4858. self.geo_form.show()
  4859. try:
  4860. self.ui.cncjob_scroll_area.takeWidget()
  4861. except:
  4862. self.log.debug("Nothing to remove")
  4863. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  4864. self.cnc_form.show()
  4865. try:
  4866. self.ui.tools_scroll_area.takeWidget()
  4867. except:
  4868. self.log.debug("Nothing to remove")
  4869. self.ui.tools_scroll_area.setWidget(self.tools_form)
  4870. self.tools_form.show()
  4871. try:
  4872. self.ui.fa_scroll_area.takeWidget()
  4873. except:
  4874. self.log.debug("Nothing to remove")
  4875. self.ui.fa_scroll_area.setWidget(self.fa_form)
  4876. self.fa_form.show()
  4877. self.log.debug("Finished GUI form initialization.")
  4878. # self.options2form()
  4879. def on_excellon_defaults_button(self):
  4880. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  4881. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  4882. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  4883. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  4884. self.defaults_form_fields["excellon_zeros"].set_value('L')
  4885. self.defaults_form_fields["excellon_units"].set_value('INCH')
  4886. log.debug("Excellon app defaults loaded ...")
  4887. def on_excellon_options_button(self):
  4888. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  4889. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  4890. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  4891. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  4892. self.options_form_fields["excellon_zeros"].set_value('L')
  4893. self.options_form_fields["excellon_units"].set_value('INCH')
  4894. log.debug("Excellon options defaults loaded ...")
  4895. def on_update_exc_export(self, state):
  4896. """
  4897. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  4898. if the update_excellon_cb checkbox is checked
  4899. :param state: state of the checkbox whose signals is tied to his slot
  4900. :return:
  4901. """
  4902. if state:
  4903. # first try to disconnect
  4904. try:
  4905. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.\
  4906. disconnect(self.on_excellon_format_changed)
  4907. except TypeError:
  4908. pass
  4909. try:
  4910. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged.\
  4911. disconnect(self.on_excellon_format_changed)
  4912. except TypeError:
  4913. pass
  4914. try:
  4915. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged.\
  4916. disconnect(self.on_excellon_format_changed)
  4917. except TypeError:
  4918. pass
  4919. try:
  4920. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged.\
  4921. disconnect(self.on_excellon_format_changed)
  4922. except TypeError:
  4923. pass
  4924. try:
  4925. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  4926. disconnect(self.on_excellon_zeros_changed)
  4927. except TypeError:
  4928. pass
  4929. try:
  4930. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  4931. disconnect(self.on_excellon_zeros_changed)
  4932. except TypeError:
  4933. pass
  4934. # the connect them
  4935. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.connect(
  4936. self.on_excellon_format_changed)
  4937. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged.connect(
  4938. self.on_excellon_format_changed)
  4939. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged.connect(
  4940. self.on_excellon_format_changed)
  4941. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged.connect(
  4942. self.on_excellon_format_changed)
  4943. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  4944. self.on_excellon_zeros_changed)
  4945. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  4946. self.on_excellon_units_changed)
  4947. else:
  4948. # disconnect the signals
  4949. try:
  4950. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged. \
  4951. disconnect(self.on_excellon_format_changed)
  4952. except TypeError:
  4953. pass
  4954. try:
  4955. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged. \
  4956. disconnect(self.on_excellon_format_changed)
  4957. except TypeError:
  4958. pass
  4959. try:
  4960. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged. \
  4961. disconnect(self.on_excellon_format_changed)
  4962. except TypeError:
  4963. pass
  4964. try:
  4965. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged. \
  4966. disconnect(self.on_excellon_format_changed)
  4967. except TypeError:
  4968. pass
  4969. try:
  4970. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  4971. disconnect(self.on_excellon_zeros_changed)
  4972. except TypeError:
  4973. pass
  4974. try:
  4975. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  4976. disconnect(self.on_excellon_zeros_changed)
  4977. except TypeError:
  4978. pass
  4979. def on_excellon_format_changed(self):
  4980. """
  4981. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  4982. :return: None
  4983. """
  4984. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  4985. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4986. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  4987. )
  4988. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4989. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  4990. )
  4991. else:
  4992. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4993. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  4994. )
  4995. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4996. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  4997. )
  4998. def on_excellon_zeros_changed(self):
  4999. """
  5000. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  5001. :return: None
  5002. """
  5003. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  5004. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  5005. )
  5006. def on_excellon_units_changed(self):
  5007. """
  5008. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  5009. :return: None
  5010. """
  5011. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  5012. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  5013. )
  5014. self.on_excellon_format_changed()
  5015. # Setting plot colors handlers
  5016. def on_pf_color_entry(self):
  5017. self.defaults['global_plot_fill'] = \
  5018. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  5019. self.defaults['global_plot_fill'][7:9]
  5020. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5021. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  5022. def on_pf_color_button(self):
  5023. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  5024. c_dialog = QtWidgets.QColorDialog()
  5025. plot_fill_color = c_dialog.getColor(initial=current_color)
  5026. if plot_fill_color.isValid() is False:
  5027. return
  5028. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5029. "background-color:%s" % str(plot_fill_color.name()))
  5030. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  5031. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  5032. self.defaults['global_plot_fill'] = new_val
  5033. def on_pf_color_spinner(self):
  5034. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  5035. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  5036. self.defaults['global_plot_fill'] = \
  5037. self.defaults['global_plot_fill'][:7] + \
  5038. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5039. self.defaults['global_plot_line'] = \
  5040. self.defaults['global_plot_line'][:7] + \
  5041. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5042. def on_pf_color_slider(self):
  5043. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  5044. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  5045. def on_pl_color_entry(self):
  5046. self.defaults['global_plot_line'] = \
  5047. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  5048. self.defaults['global_plot_line'][7:9]
  5049. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5050. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  5051. def on_pl_color_button(self):
  5052. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  5053. # print(current_color)
  5054. c_dialog = QtWidgets.QColorDialog()
  5055. plot_line_color = c_dialog.getColor(initial=current_color)
  5056. if plot_line_color.isValid() is False:
  5057. return
  5058. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5059. "background-color:%s" % str(plot_line_color.name()))
  5060. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  5061. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  5062. self.defaults['global_plot_line'] = new_val_line
  5063. # Setting selection colors (left - right) handlers
  5064. def on_sf_color_entry(self):
  5065. self.defaults['global_sel_fill'] = \
  5066. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  5067. self.defaults['global_sel_fill'][7:9]
  5068. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5069. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  5070. def on_sf_color_button(self):
  5071. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  5072. c_dialog = QtWidgets.QColorDialog()
  5073. plot_fill_color = c_dialog.getColor(initial=current_color)
  5074. if plot_fill_color.isValid() is False:
  5075. return
  5076. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5077. "background-color:%s" % str(plot_fill_color.name()))
  5078. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  5079. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  5080. self.defaults['global_sel_fill'] = new_val
  5081. def on_sf_color_spinner(self):
  5082. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  5083. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  5084. self.defaults['global_sel_fill'] = \
  5085. self.defaults['global_sel_fill'][:7] + \
  5086. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5087. self.defaults['global_sel_line'] = \
  5088. self.defaults['global_sel_line'][:7] + \
  5089. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5090. def on_sf_color_slider(self):
  5091. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  5092. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  5093. def on_sl_color_entry(self):
  5094. self.defaults['global_sel_line'] = \
  5095. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  5096. self.defaults['global_sel_line'][7:9]
  5097. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5098. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  5099. def on_sl_color_button(self):
  5100. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  5101. c_dialog = QtWidgets.QColorDialog()
  5102. plot_line_color = c_dialog.getColor(initial=current_color)
  5103. if plot_line_color.isValid() is False:
  5104. return
  5105. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5106. "background-color:%s" % str(plot_line_color.name()))
  5107. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  5108. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  5109. self.defaults['global_sel_line'] = new_val_line
  5110. # Setting selection colors (right - left) handlers
  5111. def on_alt_sf_color_entry(self):
  5112. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  5113. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  5114. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5115. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  5116. def on_alt_sf_color_button(self):
  5117. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  5118. c_dialog = QtWidgets.QColorDialog()
  5119. plot_fill_color = c_dialog.getColor(initial=current_color)
  5120. if plot_fill_color.isValid() is False:
  5121. return
  5122. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5123. "background-color:%s" % str(plot_fill_color.name()))
  5124. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  5125. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  5126. self.defaults['global_alt_sel_fill'] = new_val
  5127. def on_alt_sf_color_spinner(self):
  5128. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  5129. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  5130. self.defaults['global_alt_sel_fill'] = \
  5131. self.defaults['global_alt_sel_fill'][:7] + \
  5132. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5133. self.defaults['global_alt_sel_line'] = \
  5134. self.defaults['global_alt_sel_line'][:7] + \
  5135. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5136. def on_alt_sf_color_slider(self):
  5137. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  5138. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  5139. def on_alt_sl_color_entry(self):
  5140. self.defaults['global_alt_sel_line'] = \
  5141. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  5142. self.defaults['global_alt_sel_line'][7:9]
  5143. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5144. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  5145. def on_alt_sl_color_button(self):
  5146. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  5147. c_dialog = QtWidgets.QColorDialog()
  5148. plot_line_color = c_dialog.getColor(initial=current_color)
  5149. if plot_line_color.isValid() is False:
  5150. return
  5151. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5152. "background-color:%s" % str(plot_line_color.name()))
  5153. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  5154. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  5155. self.defaults['global_alt_sel_line'] = new_val_line
  5156. # Setting Editor colors
  5157. def on_draw_color_entry(self):
  5158. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5159. .draw_color_entry.get_value()
  5160. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5161. "background-color:%s" % str(self.defaults['global_draw_color']))
  5162. def on_draw_color_button(self):
  5163. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  5164. c_dialog = QtWidgets.QColorDialog()
  5165. draw_color = c_dialog.getColor(initial=current_color)
  5166. if draw_color.isValid() is False:
  5167. return
  5168. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5169. "background-color:%s" % str(draw_color.name()))
  5170. new_val = str(draw_color.name())
  5171. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  5172. self.defaults['global_draw_color'] = new_val
  5173. def on_sel_draw_color_entry(self):
  5174. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5175. .sel_draw_color_entry.get_value()
  5176. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5177. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  5178. def on_sel_draw_color_button(self):
  5179. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  5180. c_dialog = QtWidgets.QColorDialog()
  5181. sel_draw_color = c_dialog.getColor(initial=current_color)
  5182. if sel_draw_color.isValid() is False:
  5183. return
  5184. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5185. "background-color:%s" % str(sel_draw_color.name()))
  5186. new_val_sel = str(sel_draw_color.name())
  5187. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  5188. self.defaults['global_sel_draw_color'] = new_val_sel
  5189. def on_proj_color_entry(self):
  5190. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  5191. .proj_color_entry.get_value()
  5192. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5193. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  5194. def on_proj_color_button(self):
  5195. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  5196. c_dialog = QtWidgets.QColorDialog()
  5197. proj_color = c_dialog.getColor(initial=current_color)
  5198. if proj_color.isValid() is False:
  5199. return
  5200. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5201. "background-color:%s" % str(proj_color.name()))
  5202. new_val_sel = str(proj_color.name())
  5203. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  5204. self.defaults['global_proj_item_color'] = new_val_sel
  5205. def on_proj_color_dis_entry(self):
  5206. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  5207. .proj_color_dis_entry.get_value()
  5208. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5209. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  5210. def on_proj_color_dis_button(self):
  5211. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  5212. c_dialog = QtWidgets.QColorDialog()
  5213. proj_color = c_dialog.getColor(initial=current_color)
  5214. if proj_color.isValid() is False:
  5215. return
  5216. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5217. "background-color:%s" % str(proj_color.name()))
  5218. new_val_sel = str(proj_color.name())
  5219. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  5220. self.defaults['global_proj_item_dis_color'] = new_val_sel
  5221. def on_annotation_fontcolor_entry(self):
  5222. self.defaults['cncjob_annotation_fontcolor'] = \
  5223. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.get_value()
  5224. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5225. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  5226. def on_annotation_fontcolor_button(self):
  5227. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  5228. c_dialog = QtWidgets.QColorDialog()
  5229. annotation_color = c_dialog.getColor(initial=current_color)
  5230. if annotation_color.isValid() is False:
  5231. return
  5232. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5233. "background-color:%s" % str(annotation_color.name()))
  5234. new_val_sel = str(annotation_color.name())
  5235. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(new_val_sel)
  5236. self.defaults['cncjob_annotation_fontcolor'] = new_val_sel
  5237. def on_film_color_entry(self):
  5238. self.defaults['tools_film_color'] = \
  5239. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  5240. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5241. "background-color:%s" % str(self.defaults['tools_film_color']))
  5242. def on_film_color_button(self):
  5243. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  5244. c_dialog = QtWidgets.QColorDialog()
  5245. film_color = c_dialog.getColor(initial=current_color)
  5246. if film_color.isValid() is False:
  5247. return
  5248. # if new color is different then mark that the Preferences are changed
  5249. if film_color != current_color:
  5250. self.on_preferences_edited()
  5251. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5252. "background-color:%s" % str(film_color.name()))
  5253. new_val_sel = str(film_color.name())
  5254. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  5255. self.defaults['tools_film_color'] = new_val_sel
  5256. def on_splash_changed(self, state):
  5257. settings = QSettings("Open Source", "FlatCAM")
  5258. settings.setValue('splash_screen', 1) if state else settings.setValue('splash_screen', 0)
  5259. # This will write the setting to the platform specific storage.
  5260. del settings
  5261. def on_notebook_tab_rmb_click(self, checked):
  5262. self.ui.notebook.set_detachable(val=checked)
  5263. self.defaults["global_tabs_detachable"] = checked
  5264. self.ui.plot_tab_area.set_detachable(val=checked)
  5265. self.defaults["global_tabs_detachable"] = checked
  5266. def on_deselect_all(self):
  5267. self.collection.set_all_inactive()
  5268. self.delete_selection_shape()
  5269. def on_workspace_modified(self):
  5270. self.save_defaults(silent=True)
  5271. self.plotcanvas.draw_workspace()
  5272. def on_workspace(self):
  5273. self.report_usage("on_workspace()")
  5274. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5275. self.plotcanvas.restore_workspace()
  5276. else:
  5277. self.plotcanvas.delete_workspace()
  5278. self.save_defaults(silent=True)
  5279. def on_workspace_menu(self):
  5280. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5281. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  5282. else:
  5283. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  5284. self.on_workspace()
  5285. def on_layout(self, index=None, lay=None):
  5286. """
  5287. Set the toolbars layout (location)
  5288. :param index:
  5289. :param lay: type of layout to be set on the toolbard
  5290. :return: None
  5291. """
  5292. self.report_usage("on_layout()")
  5293. if lay:
  5294. current_layout = lay
  5295. else:
  5296. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  5297. settings = QSettings("Open Source", "FlatCAM")
  5298. settings.setValue('layout', current_layout)
  5299. # This will write the setting to the platform specific storage.
  5300. del settings
  5301. # first remove the toolbars:
  5302. try:
  5303. self.ui.removeToolBar(self.ui.toolbarfile)
  5304. self.ui.removeToolBar(self.ui.toolbargeo)
  5305. self.ui.removeToolBar(self.ui.toolbarview)
  5306. self.ui.removeToolBar(self.ui.toolbarshell)
  5307. self.ui.removeToolBar(self.ui.toolbartools)
  5308. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  5309. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  5310. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  5311. self.ui.removeToolBar(self.ui.snap_toolbar)
  5312. self.ui.removeToolBar(self.ui.toolbarshell)
  5313. except Exception as e:
  5314. pass
  5315. if current_layout == 'standard':
  5316. # ## TOOLBAR INSTALLATION # ##
  5317. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5318. self.ui.toolbarfile.setObjectName('File_TB')
  5319. self.ui.addToolBar(self.ui.toolbarfile)
  5320. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5321. self.ui.toolbargeo.setObjectName('Edit_TB')
  5322. self.ui.addToolBar(self.ui.toolbargeo)
  5323. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5324. self.ui.toolbarview.setObjectName('View_TB')
  5325. self.ui.addToolBar(self.ui.toolbarview)
  5326. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5327. self.ui.toolbarshell.setObjectName('Shell_TB')
  5328. self.ui.addToolBar(self.ui.toolbarshell)
  5329. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5330. self.ui.toolbartools.setObjectName('Tools_TB')
  5331. self.ui.addToolBar(self.ui.toolbartools)
  5332. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5333. # self.ui.exc_edit_toolbar.setVisible(False)
  5334. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5335. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  5336. self.ui.addToolBarBreak()
  5337. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5338. # self.ui.geo_edit_toolbar.setVisible(False)
  5339. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5340. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  5341. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5342. # self.ui.grb_edit_toolbar.setVisible(False)
  5343. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5344. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  5345. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5346. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5347. # self.ui.snap_toolbar.setMaximumHeight(30)
  5348. self.ui.addToolBar(self.ui.snap_toolbar)
  5349. self.ui.corner_snap_btn.setVisible(False)
  5350. self.ui.snap_magnet.setVisible(False)
  5351. elif current_layout == 'compact':
  5352. # ## TOOLBAR INSTALLATION # ##
  5353. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5354. self.ui.toolbarfile.setObjectName('File_TB')
  5355. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  5356. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5357. self.ui.toolbargeo.setObjectName('Edit_TB')
  5358. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  5359. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5360. self.ui.toolbarshell.setObjectName('Shell_TB')
  5361. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  5362. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5363. self.ui.toolbartools.setObjectName('Tools_TB')
  5364. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  5365. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5366. # self.ui.geo_edit_toolbar.setVisible(False)
  5367. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5368. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  5369. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5370. self.ui.toolbarview.setObjectName('View_TB')
  5371. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  5372. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  5373. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5374. # self.ui.grb_edit_toolbar.setVisible(False)
  5375. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5376. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  5377. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5378. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5379. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  5380. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5381. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5382. self.ui.snap_toolbar.setMaximumHeight(30)
  5383. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  5384. self.ui.corner_snap_btn.setVisible(True)
  5385. self.ui.snap_magnet.setVisible(True)
  5386. # add all the actions to the toolbars
  5387. self.ui.populate_toolbars()
  5388. # reconnect all the signals to the toolbar actions
  5389. self.connect_toolbar_signals()
  5390. self.ui.grid_snap_btn.setChecked(True)
  5391. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  5392. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  5393. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  5394. self.ui.grid_gap_link_cb.setChecked(True)
  5395. def on_cursor_type(self, val):
  5396. """
  5397. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  5398. :return: None
  5399. """
  5400. self.app_cursor.enabled = False
  5401. if val == 'small':
  5402. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(False)
  5403. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(False)
  5404. self.app_cursor = self.plotcanvas.new_cursor()
  5405. else:
  5406. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(True)
  5407. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(True)
  5408. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  5409. if self.ui.grid_snap_btn.isChecked():
  5410. self.app_cursor.enabled = True
  5411. else:
  5412. self.app_cursor.enabled = False
  5413. def on_cnc_custom_parameters(self, signal_text):
  5414. if signal_text == 'Parameters':
  5415. return
  5416. else:
  5417. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  5418. def on_save_button(self):
  5419. log.debug("App.on_save_button() --> Saving preferences to file.")
  5420. self.preferences_changed_flag = False
  5421. self.save_defaults(silent=False)
  5422. # load the defaults so they are updated into the app
  5423. self.load_defaults(filename='current_defaults')
  5424. # Re-fresh project options
  5425. self.on_options_app2project()
  5426. settings = QSettings("Open Source", "FlatCAM")
  5427. # save the notebook font size
  5428. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  5429. settings.setValue('notebook_font_size', fsize)
  5430. # save the axis font size
  5431. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  5432. settings.setValue('axis_font_size', g_fsize)
  5433. # save the textbox font size
  5434. tb_fsize = self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  5435. settings.setValue('textbox_font_size', tb_fsize)
  5436. # This will write the setting to the platform specific storage.
  5437. del settings
  5438. def handlePrint(self):
  5439. self.report_usage("handlePrint()")
  5440. dialog = QtPrintSupport.QPrintDialog()
  5441. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  5442. self.ui.code_editor.document().print_(dialog.printer())
  5443. def handlePreview(self):
  5444. self.report_usage("handlePreview()")
  5445. dialog = QtPrintSupport.QPrintPreviewDialog()
  5446. dialog.paintRequested.connect(self.ui.code_editor.print_)
  5447. dialog.exec_()
  5448. def handleTextChanged(self):
  5449. # enable = not self.ui.code_editor.document().isEmpty()
  5450. # self.ui.buttonPrint.setEnabled(enable)
  5451. # self.ui.buttonPreview.setEnabled(enable)
  5452. pass
  5453. def handleOpen(self, filt=None):
  5454. self.report_usage("handleOpen()")
  5455. if filt:
  5456. _filter_ = filt
  5457. else:
  5458. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  5459. "All Files (*.*)"
  5460. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  5461. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  5462. if path:
  5463. file = QtCore.QFile(path)
  5464. if file.open(QtCore.QIODevice.ReadOnly):
  5465. stream = QtCore.QTextStream(file)
  5466. self.gcode_edited = stream.readAll()
  5467. self.ui.code_editor.setPlainText(self.gcode_edited)
  5468. file.close()
  5469. def handleSaveGCode(self, name=None, filt=None):
  5470. self.report_usage("handleSaveGCode()")
  5471. if filt:
  5472. _filter_ = filt
  5473. else:
  5474. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  5475. "All Files (*.*)"
  5476. if name:
  5477. obj_name = name
  5478. else:
  5479. try:
  5480. obj_name = self.collection.get_active().options['name']
  5481. except AttributeError:
  5482. obj_name = 'file'
  5483. if filt is None:
  5484. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  5485. try:
  5486. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  5487. caption=_("Export G-Code ..."),
  5488. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  5489. filter=_filter_
  5490. )[0])
  5491. except TypeError:
  5492. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  5493. if filename == "":
  5494. self.inform.emit('[WARNING_NOTCL] %s' %
  5495. _("Export Code cancelled."))
  5496. return
  5497. else:
  5498. try:
  5499. my_gcode = self.ui.code_editor.toPlainText()
  5500. with open(filename, 'w') as f:
  5501. for line in my_gcode:
  5502. f.write(line)
  5503. except FileNotFoundError:
  5504. self.inform.emit('[WARNING] %s' %
  5505. _("No such file or directory"))
  5506. return
  5507. except PermissionError:
  5508. self.inform.emit('[WARNING] %s' %
  5509. _("Permission denied, saving not possible.\n"
  5510. "Most likely another app is holding the file open and not accessible."))
  5511. return
  5512. # Just for adding it to the recent files list.
  5513. if self.defaults["global_open_style"] is False:
  5514. self.file_opened.emit("cncjob", filename)
  5515. self.file_saved.emit("cncjob", filename)
  5516. self.inform.emit('%s: %s' % (_("Saved to"), str(filename)))
  5517. def handleFindGCode(self):
  5518. self.report_usage("handleFindGCode()")
  5519. flags = QtGui.QTextDocument.FindCaseSensitively
  5520. text_to_be_found = self.ui.entryFind.get_value()
  5521. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  5522. if r is False:
  5523. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5524. def handleReplaceGCode(self):
  5525. self.report_usage("handleReplaceGCode()")
  5526. old = self.ui.entryFind.get_value()
  5527. new = self.ui.entryReplace.get_value()
  5528. if self.ui.sel_all_cb.isChecked():
  5529. while True:
  5530. cursor = self.ui.code_editor.textCursor()
  5531. cursor.beginEditBlock()
  5532. flags = QtGui.QTextDocument.FindCaseSensitively
  5533. # self.ui.editor is the QPlainTextEdit
  5534. r = self.ui.code_editor.find(str(old), flags)
  5535. if r:
  5536. qc = self.ui.code_editor.textCursor()
  5537. if qc.hasSelection():
  5538. qc.insertText(new)
  5539. else:
  5540. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5541. break
  5542. # Mark end of undo block
  5543. cursor.endEditBlock()
  5544. else:
  5545. cursor = self.ui.code_editor.textCursor()
  5546. cursor.beginEditBlock()
  5547. qc = self.ui.code_editor.textCursor()
  5548. if qc.hasSelection():
  5549. qc.insertText(new)
  5550. # Mark end of undo block
  5551. cursor.endEditBlock()
  5552. def handleCopyAll(self):
  5553. text = self.ui.code_editor.toPlainText()
  5554. self.clipboard.setText(text)
  5555. self.inform.emit(_("Code Editor content copied to clipboard ..."))
  5556. def handleRunCode(self):
  5557. # trying to run a Tcl command without having the Shell open will create some warnings because the Tcl Shell
  5558. # tries to print on a hidden widget, therefore show the dock if hidden
  5559. if self.ui.shell_dock.isHidden():
  5560. self.ui.shell_dock.show()
  5561. self.script_code = deepcopy(self.ui.code_editor.toPlainText())
  5562. # self.shell._sysShell.exec_command(script_code)
  5563. old_line = ''
  5564. for tcl_command_line in self.script_code.splitlines():
  5565. # do not process lines starting with '#' = comment and empty lines
  5566. if not tcl_command_line.startswith('#') and tcl_command_line != '':
  5567. # id FlatCAM is run in Windows then replace all the slashes with
  5568. # the UNIX style slash that TCL understands
  5569. if sys.platform == 'win32':
  5570. if "open" in tcl_command_line:
  5571. tcl_command_line = tcl_command_line.replace('\\', '/')
  5572. if old_line != '':
  5573. new_command = old_line + tcl_command_line + '\n'
  5574. else:
  5575. new_command = tcl_command_line
  5576. # execute the actual Tcl command
  5577. try:
  5578. self.shell.open_proccessing() # Disables input box.
  5579. result = self.tcl.eval(str(new_command))
  5580. if result != 'None':
  5581. self.shell.append_output(result + '\n')
  5582. old_line = ''
  5583. except tk.TclError:
  5584. old_line = old_line + tcl_command_line + '\n'
  5585. except Exception as e:
  5586. log.debug("App.handleRunCode() --> %s" % str(e))
  5587. if old_line != '':
  5588. # it means that the script finished with an error
  5589. result = self.tcl.eval("set errorInfo")
  5590. self.log.error("Exec command Exception: %s" % (result + '\n'))
  5591. self.shell.append_error('ERROR: ' + result + '\n')
  5592. self.shell.close_proccessing()
  5593. def on_tool_add_keypress(self):
  5594. # ## Current application units in Upper Case
  5595. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5596. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5597. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5598. if notebook_widget_name == 'selected_tab':
  5599. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5600. # Tool add works for Geometry only if Advanced is True in Preferences
  5601. if self.defaults["global_app_level"] == 'a':
  5602. tool_add_popup = FCInputDialog(title="New Tool ...",
  5603. text='Enter a Tool Diameter:',
  5604. min=0.0000, max=99.9999, decimals=4)
  5605. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5606. val, ok = tool_add_popup.get_value()
  5607. if ok:
  5608. if float(val) == 0:
  5609. self.inform.emit('[WARNING_NOTCL] %s' %
  5610. _("Please enter a tool diameter with non-zero value, in Float format."))
  5611. return
  5612. self.collection.get_active().on_tool_add(dia=float(val))
  5613. else:
  5614. self.inform.emit('[WARNING_NOTCL] %s...' %
  5615. _("Adding Tool cancelled"))
  5616. else:
  5617. msgbox = QtWidgets.QMessageBox()
  5618. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5619. "Go to Preferences -> General - Show Advanced Options."))
  5620. msgbox.setWindowTitle("Tool adding ...")
  5621. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  5622. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5623. msgbox.setDefaultButton(bt_ok)
  5624. msgbox.exec_()
  5625. # work only if the notebook tab on focus is the Tools_Tab
  5626. if notebook_widget_name == 'tool_tab':
  5627. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5628. tool_add_popup = FCInputDialog(title="New Tool ...",
  5629. text='Enter a Tool Diameter:',
  5630. min=0.0000, max=99.9999, decimals=4)
  5631. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5632. val, ok = tool_add_popup.get_value()
  5633. # and only if the tool is NCC Tool
  5634. if tool_widget == self.ncclear_tool.toolName:
  5635. if ok:
  5636. if float(val) == 0:
  5637. self.inform.emit('[WARNING_NOTCL] %s' %
  5638. _("Please enter a tool diameter with non-zero value, in Float format."))
  5639. return
  5640. self.ncclear_tool.on_tool_add(dia=float(val))
  5641. else:
  5642. self.inform.emit('[WARNING_NOTCL] %s...' %
  5643. _("Adding Tool cancelled"))
  5644. # and only if the tool is Paint Area Tool
  5645. elif tool_widget == self.paint_tool.toolName:
  5646. if ok:
  5647. if float(val) == 0:
  5648. self.inform.emit('[WARNING_NOTCL] %s' %
  5649. _("Please enter a tool diameter with non-zero value, in Float format."))
  5650. return
  5651. self.paint_tool.on_tool_add(dia=float(val))
  5652. else:
  5653. self.inform.emit('[WARNING_NOTCL] %s...' %
  5654. _("Adding Tool cancelled"))
  5655. # and only if the tool is Solder Paste Dispensing Tool
  5656. elif tool_widget == self.paste_tool.toolName:
  5657. if ok:
  5658. if float(val) == 0:
  5659. self.inform.emit('[WARNING_NOTCL] %s' %
  5660. _("Please enter a tool diameter with non-zero value, in Float format."))
  5661. return
  5662. self.paste_tool.on_tool_add(dia=float(val))
  5663. else:
  5664. self.inform.emit('[WARNING_NOTCL] %s...' %
  5665. _("Adding Tool cancelled"))
  5666. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5667. # See description bellow.
  5668. def on_delete_keypress(self):
  5669. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5670. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5671. if notebook_widget_name == 'selected_tab':
  5672. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5673. self.collection.get_active().on_tool_delete()
  5674. # work only if the notebook tab on focus is the Tools_Tab
  5675. elif notebook_widget_name == 'tool_tab':
  5676. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5677. # and only if the tool is NCC Tool
  5678. if tool_widget == self.ncclear_tool.toolName:
  5679. self.ncclear_tool.on_tool_delete()
  5680. # and only if the tool is Paint Tool
  5681. elif tool_widget == self.paint_tool.toolName:
  5682. self.paint_tool.on_tool_delete()
  5683. # and only if the tool is Solder Paste Dispensing Tool
  5684. elif tool_widget == self.paste_tool.toolName:
  5685. self.paste_tool.on_tool_delete()
  5686. else:
  5687. self.on_delete()
  5688. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5689. # some screens you have to be careful where you hover with your mouse.
  5690. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5691. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5692. # Complicated, I know :)
  5693. def on_delete(self):
  5694. """
  5695. Delete the currently selected FlatCAMObjs.
  5696. :return: None
  5697. """
  5698. self.report_usage("on_delete()")
  5699. response = None
  5700. bt_ok = None
  5701. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5702. # a geometry object before we update it.
  5703. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5704. and self.grb_editor.editor_active is False:
  5705. if self.defaults["global_delete_confirmation"] is True:
  5706. msgbox = QtWidgets.QMessageBox()
  5707. msgbox.setWindowTitle(_("Delete objects"))
  5708. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  5709. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5710. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5711. "the selected objects?"))
  5712. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5713. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5714. msgbox.setDefaultButton(bt_ok)
  5715. msgbox.exec_()
  5716. response = msgbox.clickedButton()
  5717. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  5718. if self.collection.get_active():
  5719. self.log.debug("App.on_delete()")
  5720. while self.collection.get_active():
  5721. obj_active = self.collection.get_active()
  5722. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  5723. if isinstance(obj_active, FlatCAMGerber):
  5724. for el in obj_active.mark_shapes:
  5725. obj_active.mark_shapes[el].clear(update=True)
  5726. obj_active.mark_shapes[el].enabled = False
  5727. # obj_active.mark_shapes[el] = None
  5728. del el
  5729. elif isinstance(obj_active, FlatCAMCNCjob):
  5730. try:
  5731. obj_active.annotation.clear(update=True)
  5732. obj_active.annotation.enabled = False
  5733. except AttributeError:
  5734. pass
  5735. self.delete_first_selected()
  5736. self.inform.emit('%s...' %
  5737. _("Object(s) deleted"))
  5738. # make sure that the selection shape is deleted, too
  5739. self.delete_selection_shape()
  5740. else:
  5741. self.inform.emit(_("Failed. No object(s) selected..."))
  5742. else:
  5743. self.inform.emit(_("Save the work in Editor and try again ..."))
  5744. def delete_first_selected(self):
  5745. # Keep this for later
  5746. try:
  5747. sel_obj = self.collection.get_active()
  5748. name = sel_obj.options["name"]
  5749. isPlotted = sel_obj.options["plot"]
  5750. except AttributeError:
  5751. self.log.debug("Nothing selected for deletion")
  5752. return
  5753. if self.is_legacy is True:
  5754. # Remove plot only if the object was plotted otherwise delaxes will fail
  5755. if isPlotted:
  5756. try:
  5757. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  5758. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  5759. except Exception as e:
  5760. log.debug("App.delete_first_selected() --> %s" % str(e))
  5761. self.plotcanvas.auto_adjust_axes()
  5762. # Remove from dictionary
  5763. self.collection.delete_active()
  5764. # Clear form
  5765. self.setup_component_editor()
  5766. self.inform.emit('%s: %s' %
  5767. (_("Object deleted"), name))
  5768. def on_set_origin(self):
  5769. """
  5770. Set the origin to the left mouse click position
  5771. :return: None
  5772. """
  5773. # display the message for the user
  5774. # and ask him to click on the desired position
  5775. self.report_usage("on_set_origin()")
  5776. def origin_replot():
  5777. def worker_task():
  5778. with self.proc_container.new('%s...' % _("Plotting")):
  5779. for obj in self.collection.get_list():
  5780. obj.plot()
  5781. self.plotcanvas.fit_view()
  5782. if self.is_legacy:
  5783. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  5784. else:
  5785. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  5786. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5787. self.inform.emit(_('Click to set the origin ...'))
  5788. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  5789. # first disconnect it as it may have been used by something else
  5790. try:
  5791. self.replot_signal.disconnect()
  5792. except TypeError:
  5793. pass
  5794. self.replot_signal[list].connect(origin_replot)
  5795. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  5796. """
  5797. :param event:
  5798. :param location:
  5799. :param noplot:
  5800. :param use_thread:
  5801. :return:
  5802. """
  5803. noplot_sig = noplot
  5804. def worker_task():
  5805. with self.proc_container.new(_("Setting Origin...")):
  5806. for obj in self.collection.get_list():
  5807. obj.offset((x, y))
  5808. self.object_changed.emit(obj)
  5809. # Update the object bounding box options
  5810. a, b, c, d = obj.bounds()
  5811. obj.options['xmin'] = a
  5812. obj.options['ymin'] = b
  5813. obj.options['xmax'] = c
  5814. obj.options['ymax'] = d
  5815. self.inform.emit('[success] %s...' %
  5816. _('Origin set'))
  5817. if noplot_sig is False:
  5818. self.replot_signal.emit([])
  5819. if location is not None:
  5820. if len(location) != 2:
  5821. self.inform.emit('[ERROR_NOTCL] %s...' %
  5822. _("Origin coordinates specified but incomplete."))
  5823. return 'fail'
  5824. x, y = location
  5825. if use_thread is True:
  5826. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5827. else:
  5828. worker_task()
  5829. self.should_we_save = True
  5830. return
  5831. if event.button == 1:
  5832. if self.is_legacy is False:
  5833. event_pos = event.pos
  5834. else:
  5835. event_pos = (event.xdata, event.ydata)
  5836. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5837. if self.grid_status() == True:
  5838. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5839. else:
  5840. pos = pos_canvas
  5841. x = 0 - pos[0]
  5842. y = 0 - pos[1]
  5843. if use_thread is True:
  5844. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5845. else:
  5846. worker_task()
  5847. self.should_we_save = True
  5848. def on_jump_to(self, custom_location=None, fit_center=True):
  5849. """
  5850. Jump to a location by setting the mouse cursor location
  5851. :return:
  5852. """
  5853. self.report_usage("on_jump_to()")
  5854. # if self.is_legacy is True:
  5855. # self.inform.emit(_("Not available with the current Graphic Engine Legacy(2D)."))
  5856. # return
  5857. if not custom_location:
  5858. dia_box_location = None
  5859. try:
  5860. dia_box_location = eval(self.clipboard.text())
  5861. except Exception as e:
  5862. pass
  5863. if type(dia_box_location) == tuple:
  5864. dia_box_location = str(dia_box_location)
  5865. else:
  5866. dia_box_location = None
  5867. dia_box = Dialog_box(title=_("Jump to ..."),
  5868. label=_("Enter the coordinates in format X,Y:"),
  5869. icon=QtGui.QIcon('share/jump_to16.png'),
  5870. initial_text=dia_box_location)
  5871. if dia_box.ok is True:
  5872. try:
  5873. location = eval(dia_box.location)
  5874. if not isinstance(location, tuple):
  5875. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  5876. return
  5877. except:
  5878. return
  5879. else:
  5880. return
  5881. else:
  5882. location = custom_location
  5883. if fit_center:
  5884. self.plotcanvas.fit_center(loc=location)
  5885. cursor = QtGui.QCursor()
  5886. if self.is_legacy is False:
  5887. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5888. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  5889. j_pos = (canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  5890. cursor.setPos(j_pos[0], j_pos[1])
  5891. else:
  5892. # find the canvas origin which is in the top left corner
  5893. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5894. # determine the coordinates for the lowest left point of the canvas
  5895. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  5896. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  5897. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  5898. # canvas) and the point (width, height) is in the top-right location
  5899. loc = self.plotcanvas.axes.transData.transform_point(location)
  5900. j_pos = (x0 + loc[0], y0 - loc[1])
  5901. cursor.setPos(j_pos[0], j_pos[1])
  5902. if self.grid_status() == True:
  5903. # Update cursor
  5904. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  5905. symbol='++', edge_color='black', size=self.defaults["global_cursor_size"])
  5906. # Set the position label
  5907. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5908. "<b>Y</b>: %.4f" % (location[0], location[1]))
  5909. # Set the relative position label
  5910. dx = location[0] - float(self.rel_point1[0])
  5911. dy = location[1] - float(self.rel_point1[1])
  5912. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5913. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  5914. self.inform.emit('[success] %s' %
  5915. _("Done."))
  5916. return location
  5917. def on_copy_object(self):
  5918. self.report_usage("on_copy_object()")
  5919. def initialize(obj_init, app):
  5920. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5921. try:
  5922. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5923. except AttributeError:
  5924. pass
  5925. try:
  5926. obj_init.apertures = deepcopy(obj.apertures)
  5927. except AttributeError:
  5928. pass
  5929. try:
  5930. if obj.tools:
  5931. obj_init.tools = deepcopy(obj.tools)
  5932. except Exception as e:
  5933. log.debug("App.on_copy_object() --> %s" % str(e))
  5934. def initialize_excellon(obj_init, app):
  5935. obj_init.tools = deepcopy(obj.tools)
  5936. # drills are offset, so they need to be deep copied
  5937. obj_init.drills = deepcopy(obj.drills)
  5938. # slots are offset, so they need to be deep copied
  5939. obj_init.slots = deepcopy(obj.slots)
  5940. obj_init.create_geometry()
  5941. for obj in self.collection.get_selected():
  5942. obj_name = obj.options["name"]
  5943. try:
  5944. if isinstance(obj, FlatCAMExcellon):
  5945. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  5946. elif isinstance(obj, FlatCAMGerber):
  5947. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  5948. elif isinstance(obj, FlatCAMGeometry):
  5949. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  5950. except Exception as e:
  5951. return "Operation failed: %s" % str(e)
  5952. def on_copy_object2(self, custom_name):
  5953. def initialize_geometry(obj_init, app):
  5954. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5955. try:
  5956. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5957. except AttributeError:
  5958. pass
  5959. try:
  5960. obj_init.apertures = deepcopy(obj.apertures)
  5961. except AttributeError:
  5962. pass
  5963. try:
  5964. if obj.tools:
  5965. obj_init.tools = deepcopy(obj.tools)
  5966. except Exception as e:
  5967. log.debug("on_copy_object2() --> %s" % str(e))
  5968. def initialize_gerber(obj_init, app):
  5969. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5970. obj_init.apertures = deepcopy(obj.apertures)
  5971. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  5972. def initialize_excellon(obj_init, app):
  5973. obj_init.tools = deepcopy(obj.tools)
  5974. # drills are offset, so they need to be deep copied
  5975. obj_init.drills = deepcopy(obj.drills)
  5976. # slots are offset, so they need to be deep copied
  5977. obj_init.slots = deepcopy(obj.slots)
  5978. obj_init.create_geometry()
  5979. for obj in self.collection.get_selected():
  5980. obj_name = obj.options["name"]
  5981. try:
  5982. if isinstance(obj, FlatCAMExcellon):
  5983. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  5984. elif isinstance(obj, FlatCAMGerber):
  5985. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  5986. elif isinstance(obj, FlatCAMGeometry):
  5987. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  5988. except Exception as e:
  5989. return "Operation failed: %s" % str(e)
  5990. def on_rename_object(self, text):
  5991. self.report_usage("on_rename_object()")
  5992. named_obj = self.collection.get_active()
  5993. for obj in named_obj:
  5994. if obj is list:
  5995. self.on_rename_object(text)
  5996. else:
  5997. try:
  5998. obj.options['name'] = text
  5999. except Exception as e:
  6000. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  6001. def convert_any2geo(self):
  6002. self.report_usage("convert_any2geo()")
  6003. def initialize(obj_init, app):
  6004. obj_init.solid_geometry = obj.solid_geometry
  6005. try:
  6006. obj_init.follow_geometry = obj.follow_geometry
  6007. except AttributeError:
  6008. pass
  6009. try:
  6010. obj_init.apertures = obj.apertures
  6011. except AttributeError:
  6012. pass
  6013. try:
  6014. if obj.tools:
  6015. obj_init.tools = obj.tools
  6016. except AttributeError:
  6017. pass
  6018. def initialize_excellon(obj_init, app):
  6019. # objs = self.collection.get_selected()
  6020. # FlatCAMGeometry.merge(objs, obj)
  6021. solid_geo = []
  6022. for tool in obj.tools:
  6023. for geo in obj.tools[tool]['solid_geometry']:
  6024. solid_geo.append(geo)
  6025. obj_init.solid_geometry = deepcopy(solid_geo)
  6026. if not self.collection.get_selected():
  6027. log.warning("App.convert_any2geo --> No object selected")
  6028. self.inform.emit('[WARNING_NOTCL] %s' %
  6029. _("No object is selected. Select an object and try again."))
  6030. return
  6031. for obj in self.collection.get_selected():
  6032. obj_name = obj.options["name"]
  6033. try:
  6034. if isinstance(obj, FlatCAMExcellon):
  6035. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  6036. else:
  6037. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  6038. except Exception as e:
  6039. return "Operation failed: %s" % str(e)
  6040. def convert_any2gerber(self):
  6041. self.report_usage("convert_any2gerber()")
  6042. def initialize_geometry(obj_init, app):
  6043. apertures = {}
  6044. apid = 0
  6045. apertures[str(apid)] = {}
  6046. apertures[str(apid)]['geometry'] = []
  6047. for obj_orig in obj.solid_geometry:
  6048. new_elem = dict()
  6049. new_elem['solid'] = obj_orig
  6050. new_elem['follow'] = obj_orig.exterior
  6051. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  6052. apertures[str(apid)]['size'] = 0.0
  6053. apertures[str(apid)]['type'] = 'C'
  6054. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6055. obj_init.apertures = deepcopy(apertures)
  6056. def initialize_excellon(obj_init, app):
  6057. apertures = {}
  6058. apid = 10
  6059. for tool in obj.tools:
  6060. apertures[str(apid)] = {}
  6061. apertures[str(apid)]['geometry'] = []
  6062. for geo in obj.tools[tool]['solid_geometry']:
  6063. new_el = dict()
  6064. new_el['solid'] = geo
  6065. new_el['follow'] = geo.exterior
  6066. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  6067. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  6068. apertures[str(apid)]['type'] = 'C'
  6069. apid += 1
  6070. # create solid_geometry
  6071. solid_geometry = []
  6072. for apid in apertures:
  6073. for geo_el in apertures[apid]['geometry']:
  6074. solid_geometry.append(geo_el['solid'])
  6075. solid_geometry = MultiPolygon(solid_geometry)
  6076. solid_geometry = solid_geometry.buffer(0.0000001)
  6077. obj_init.solid_geometry = deepcopy(solid_geometry)
  6078. obj_init.apertures = deepcopy(apertures)
  6079. # clear the working objects (perhaps not necessary due of Python GC)
  6080. apertures.clear()
  6081. if not self.collection.get_selected():
  6082. log.warning("App.convert_any2gerber --> No object selected")
  6083. self.inform.emit('[WARNING_NOTCL] %s' %
  6084. _("No object is selected. Select an object and try again."))
  6085. return
  6086. for obj in self.collection.get_selected():
  6087. obj_name = obj.options["name"]
  6088. try:
  6089. if isinstance(obj, FlatCAMExcellon):
  6090. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  6091. elif isinstance(obj, FlatCAMGeometry):
  6092. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  6093. else:
  6094. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  6095. except Exception as e:
  6096. return "Operation failed: %s" % str(e)
  6097. def abort_all_tasks(self):
  6098. if self.abort_flag is False:
  6099. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  6100. self.abort_flag = True
  6101. def app_is_idle(self):
  6102. if self.abort_flag:
  6103. self.inform.emit('[WARNING_NOTCL] %s' %
  6104. _("The current task was gracefully closed on user request..."))
  6105. self.abort_flag = False
  6106. def on_selectall(self):
  6107. self.report_usage("on_selectall()")
  6108. # delete the possible selection box around a possible selected object
  6109. self.delete_selection_shape()
  6110. for name in self.collection.get_names():
  6111. self.collection.set_active(name)
  6112. curr_sel_obj = self.collection.get_by_name(name)
  6113. # create the selection box around the selected object
  6114. if self.defaults['global_selection_shape'] is True:
  6115. self.draw_selection_shape(curr_sel_obj)
  6116. def on_preferences(self):
  6117. # add the tab if it was closed
  6118. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  6119. # delete the absolute and relative position and messages in the infobar
  6120. self.ui.position_label.setText("")
  6121. self.ui.rel_position_label.setText("")
  6122. # Switch plot_area to preferences page
  6123. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  6124. # self.ui.show()
  6125. # this disconnect() is done so the slot will be connected only once
  6126. try:
  6127. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_preferences_closed)
  6128. except (TypeError, AttributeError):
  6129. pass
  6130. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_preferences_closed)
  6131. # detect changes in the preferences
  6132. for idx in range(self.ui.pref_tab_area.count()):
  6133. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6134. try:
  6135. try:
  6136. tb.textEdited.disconnect(self.on_preferences_edited)
  6137. except (TypeError, AttributeError):
  6138. pass
  6139. tb.textEdited.connect(self.on_preferences_edited)
  6140. except AttributeError:
  6141. pass
  6142. try:
  6143. try:
  6144. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6145. except (TypeError, AttributeError):
  6146. pass
  6147. tb.modificationChanged.connect(self.on_preferences_edited)
  6148. except AttributeError:
  6149. pass
  6150. try:
  6151. try:
  6152. tb.toggled.disconnect(self.on_preferences_edited)
  6153. except (TypeError, AttributeError):
  6154. pass
  6155. tb.toggled.connect(self.on_preferences_edited)
  6156. except AttributeError:
  6157. pass
  6158. try:
  6159. try:
  6160. tb.valueChanged.disconnect(self.on_preferences_edited)
  6161. except (TypeError, AttributeError):
  6162. pass
  6163. tb.valueChanged.connect(self.on_preferences_edited)
  6164. except AttributeError:
  6165. pass
  6166. try:
  6167. try:
  6168. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6169. except (TypeError, AttributeError):
  6170. pass
  6171. tb.currentIndexChanged.connect(self.on_preferences_edited)
  6172. except AttributeError:
  6173. pass
  6174. def on_preferences_edited(self):
  6175. self.inform.emit('[WARNING_NOTCL] %s' %
  6176. _("Preferences edited but not saved."))
  6177. self.preferences_changed_flag = True
  6178. def on_preferences_closed(self):
  6179. # disconnect
  6180. for idx in range(self.ui.pref_tab_area.count()):
  6181. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6182. try:
  6183. tb.textEdited.disconnect(self.on_preferences_edited)
  6184. except (TypeError, AttributeError):
  6185. pass
  6186. try:
  6187. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6188. except (TypeError, AttributeError):
  6189. pass
  6190. try:
  6191. tb.toggled.disconnect(self.on_preferences_edited)
  6192. except (TypeError, AttributeError):
  6193. pass
  6194. try:
  6195. tb.valueChanged.disconnect(self.on_preferences_edited)
  6196. except (TypeError, AttributeError):
  6197. pass
  6198. try:
  6199. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6200. except (TypeError, AttributeError):
  6201. pass
  6202. if self.preferences_changed_flag is True:
  6203. msgbox = QtWidgets.QMessageBox()
  6204. msgbox.setText(_("One or more values are changed.\n"
  6205. "Do you want to save the Preferences?"))
  6206. msgbox.setWindowTitle(_("Save Preferences"))
  6207. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6208. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6209. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6210. msgbox.setDefaultButton(bt_yes)
  6211. msgbox.exec_()
  6212. response = msgbox.clickedButton()
  6213. if response == bt_yes:
  6214. self.on_save_button()
  6215. self.inform.emit('[success] %s' %
  6216. _("Preferences saved."))
  6217. else:
  6218. self.preferences_changed_flag = False
  6219. return
  6220. def on_flipy(self):
  6221. self.report_usage("on_flipy()")
  6222. obj_list = self.collection.get_selected()
  6223. xminlist = []
  6224. yminlist = []
  6225. xmaxlist = []
  6226. ymaxlist = []
  6227. if not obj_list:
  6228. self.inform.emit('[WARNING_NOTCL] %s' %
  6229. _("No object selected to Flip on Y axis."))
  6230. else:
  6231. try:
  6232. # first get a bounding box to fit all
  6233. for obj in obj_list:
  6234. xmin, ymin, xmax, ymax = obj.bounds()
  6235. xminlist.append(xmin)
  6236. yminlist.append(ymin)
  6237. xmaxlist.append(xmax)
  6238. ymaxlist.append(ymax)
  6239. # get the minimum x,y and maximum x,y for all objects selected
  6240. xminimal = min(xminlist)
  6241. yminimal = min(yminlist)
  6242. xmaximal = max(xmaxlist)
  6243. ymaximal = max(ymaxlist)
  6244. px = 0.5 * (xminimal + xmaximal)
  6245. py = 0.5 * (yminimal + ymaximal)
  6246. # execute mirroring
  6247. for obj in obj_list:
  6248. obj.mirror('X', [px, py])
  6249. obj.plot()
  6250. self.object_changed.emit(obj)
  6251. self.inform.emit('[success] %s' %
  6252. _("Flip on Y axis done."))
  6253. except Exception as e:
  6254. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6255. (_("Flip action was not executed."), str(e)))
  6256. return
  6257. def on_flipx(self):
  6258. self.report_usage("on_flipx()")
  6259. obj_list = self.collection.get_selected()
  6260. xminlist = []
  6261. yminlist = []
  6262. xmaxlist = []
  6263. ymaxlist = []
  6264. if not obj_list:
  6265. self.inform.emit('[WARNING_NOTCL] %s' %
  6266. _("No object selected to Flip on X axis."))
  6267. else:
  6268. try:
  6269. # first get a bounding box to fit all
  6270. for obj in obj_list:
  6271. xmin, ymin, xmax, ymax = obj.bounds()
  6272. xminlist.append(xmin)
  6273. yminlist.append(ymin)
  6274. xmaxlist.append(xmax)
  6275. ymaxlist.append(ymax)
  6276. # get the minimum x,y and maximum x,y for all objects selected
  6277. xminimal = min(xminlist)
  6278. yminimal = min(yminlist)
  6279. xmaximal = max(xmaxlist)
  6280. ymaximal = max(ymaxlist)
  6281. px = 0.5 * (xminimal + xmaximal)
  6282. py = 0.5 * (yminimal + ymaximal)
  6283. # execute mirroring
  6284. for obj in obj_list:
  6285. obj.mirror('Y', [px, py])
  6286. obj.plot()
  6287. self.object_changed.emit(obj)
  6288. self.inform.emit('[success] %s' %
  6289. _("Flip on X axis done."))
  6290. except Exception as e:
  6291. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6292. (_("Flip action was not executed."), str(e)))
  6293. return
  6294. def on_rotate(self, silent=False, preset=None):
  6295. self.report_usage("on_rotate()")
  6296. obj_list = self.collection.get_selected()
  6297. xminlist = []
  6298. yminlist = []
  6299. xmaxlist = []
  6300. ymaxlist = []
  6301. if not obj_list:
  6302. self.inform.emit('[WARNING_NOTCL] %s' %
  6303. _("No object selected to Rotate."))
  6304. else:
  6305. if silent is False:
  6306. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6307. min=-360, max=360, decimals=4,
  6308. init_val=float(self.defaults['tools_transform_rotate']))
  6309. num, ok = rotatebox.get_value()
  6310. else:
  6311. num = preset
  6312. ok = True
  6313. if ok:
  6314. try:
  6315. # first get a bounding box to fit all
  6316. for obj in obj_list:
  6317. xmin, ymin, xmax, ymax = obj.bounds()
  6318. xminlist.append(xmin)
  6319. yminlist.append(ymin)
  6320. xmaxlist.append(xmax)
  6321. ymaxlist.append(ymax)
  6322. # get the minimum x,y and maximum x,y for all objects selected
  6323. xminimal = min(xminlist)
  6324. yminimal = min(yminlist)
  6325. xmaximal = max(xmaxlist)
  6326. ymaximal = max(ymaxlist)
  6327. px = 0.5 * (xminimal + xmaximal)
  6328. py = 0.5 * (yminimal + ymaximal)
  6329. for sel_obj in obj_list:
  6330. sel_obj.rotate(-float(num), point=(px, py))
  6331. sel_obj.plot()
  6332. self.object_changed.emit(sel_obj)
  6333. self.inform.emit('[success] %s' %
  6334. _("Rotation done."))
  6335. except Exception as e:
  6336. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6337. (_("Rotation movement was not executed."), str(e)))
  6338. return
  6339. def on_skewx(self):
  6340. self.report_usage("on_skewx()")
  6341. obj_list = self.collection.get_selected()
  6342. xminlist = []
  6343. yminlist = []
  6344. if not obj_list:
  6345. self.inform.emit('[WARNING_NOTCL] %s' %
  6346. _("No object selected to Skew/Shear on X axis."))
  6347. else:
  6348. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6349. min=-360, max=360, decimals=4,
  6350. init_val=float(self.defaults['tools_transform_skew_x']))
  6351. num, ok = skewxbox.get_value()
  6352. if ok:
  6353. # first get a bounding box to fit all
  6354. for obj in obj_list:
  6355. xmin, ymin, xmax, ymax = obj.bounds()
  6356. xminlist.append(xmin)
  6357. yminlist.append(ymin)
  6358. # get the minimum x,y and maximum x,y for all objects selected
  6359. xminimal = min(xminlist)
  6360. yminimal = min(yminlist)
  6361. for obj in obj_list:
  6362. obj.skew(num, 0, point=(xminimal, yminimal))
  6363. obj.plot()
  6364. self.object_changed.emit(obj)
  6365. self.inform.emit('[success] %s' %
  6366. _("Skew on X axis done."))
  6367. def on_skewy(self):
  6368. self.report_usage("on_skewy()")
  6369. obj_list = self.collection.get_selected()
  6370. xminlist = []
  6371. yminlist = []
  6372. if not obj_list:
  6373. self.inform.emit('[WARNING_NOTCL] %s' %
  6374. _("No object selected to Skew/Shear on Y axis."))
  6375. else:
  6376. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6377. min=-360, max=360, decimals=4,
  6378. init_val=float(self.defaults['tools_transform_skew_y']))
  6379. num, ok = skewybox.get_value()
  6380. if ok:
  6381. # first get a bounding box to fit all
  6382. for obj in obj_list:
  6383. xmin, ymin, xmax, ymax = obj.bounds()
  6384. xminlist.append(xmin)
  6385. yminlist.append(ymin)
  6386. # get the minimum x,y and maximum x,y for all objects selected
  6387. xminimal = min(xminlist)
  6388. yminimal = min(yminlist)
  6389. for obj in obj_list:
  6390. obj.skew(0, num, point=(xminimal, yminimal))
  6391. obj.plot()
  6392. self.object_changed.emit(obj)
  6393. self.inform.emit('[success] %s' %
  6394. _("Skew on Y axis done."))
  6395. def on_plots_updated(self):
  6396. """
  6397. Callback used to report when the plots have changed.
  6398. Adjust axes and zooms to fit.
  6399. :return: None
  6400. """
  6401. if self.is_legacy is False:
  6402. self.plotcanvas.update() # TODO: Need update canvas?
  6403. else:
  6404. self.plotcanvas.auto_adjust_axes()
  6405. self.on_zoom_fit(None)
  6406. self.collection.update_view()
  6407. # self.inform.emit(_("Plots updated ..."))
  6408. # TODO: Rework toolbar 'clear', 'replot' functions
  6409. def on_toolbar_replot(self):
  6410. """
  6411. Callback for toolbar button. Re-plots all objects.
  6412. :return: None
  6413. """
  6414. self.report_usage("on_toolbar_replot")
  6415. self.log.debug("on_toolbar_replot()")
  6416. try:
  6417. self.collection.get_active().read_form()
  6418. except AttributeError:
  6419. self.log.debug("on_toolbar_replot(): AttributeError")
  6420. pass
  6421. self.plot_all()
  6422. def on_row_activated(self, index):
  6423. if index.isValid():
  6424. if index.internalPointer().parent_item != self.collection.root_item:
  6425. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6426. self.collection.on_item_activated(index)
  6427. def grid_status(self):
  6428. if self.ui.grid_snap_btn.isChecked():
  6429. return True
  6430. else:
  6431. return False
  6432. def populate_cmenu_grids(self):
  6433. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6434. self.ui.cmenu_gridmenu.clear()
  6435. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  6436. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  6437. grid_toggle.setCheckable(True)
  6438. if self.grid_status() == True:
  6439. grid_toggle.setChecked(True)
  6440. else:
  6441. grid_toggle.setChecked(False)
  6442. self.ui.cmenu_gridmenu.addSeparator()
  6443. for grid in sorted_list:
  6444. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  6445. action.triggered.connect(self.set_grid)
  6446. self.ui.cmenu_gridmenu.addSeparator()
  6447. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  6448. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  6449. grid_add.triggered.connect(self.on_grid_add)
  6450. grid_delete.triggered.connect(self.on_grid_delete)
  6451. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  6452. def set_grid(self):
  6453. self.ui.grid_gap_x_entry.setText(self.sender().text())
  6454. self.ui.grid_gap_y_entry.setText(self.sender().text())
  6455. def on_grid_add(self):
  6456. # ## Current application units in lower Case
  6457. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6458. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  6459. text=_('Enter a Grid Value:'),
  6460. min=0.0000, max=99.9999, decimals=4)
  6461. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  6462. val, ok = grid_add_popup.get_value()
  6463. if ok:
  6464. if float(val) == 0:
  6465. self.inform.emit('[WARNING_NOTCL] %s' %
  6466. _("Please enter a grid value with non-zero value, in Float format."))
  6467. return
  6468. else:
  6469. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  6470. self.defaults["global_grid_context_menu"][str(units)].append(val)
  6471. self.inform.emit('[success] %s...' %
  6472. _("New Grid added"))
  6473. else:
  6474. self.inform.emit('[WARNING_NOTCL] %s...' %
  6475. _("Grid already exists"))
  6476. else:
  6477. self.inform.emit('[WARNING_NOTCL] %s...' %
  6478. _("Adding New Grid cancelled"))
  6479. def on_grid_delete(self):
  6480. # ## Current application units in lower Case
  6481. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6482. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  6483. text='Enter a Grid Value:',
  6484. min=0.0000, max=99.9999, decimals=4)
  6485. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  6486. val, ok = grid_del_popup.get_value()
  6487. if ok:
  6488. if float(val) == 0:
  6489. self.inform.emit('[WARNING_NOTCL] %s' %
  6490. _("Please enter a grid value with non-zero value, in Float format."))
  6491. return
  6492. else:
  6493. try:
  6494. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  6495. except ValueError:
  6496. self.inform.emit('[ERROR_NOTCL]%s...' %
  6497. _(" Grid Value does not exist"))
  6498. return
  6499. self.inform.emit('[success] %s...' %
  6500. _("Grid Value deleted"))
  6501. else:
  6502. self.inform.emit('[WARNING_NOTCL] %s...' %
  6503. _("Delete Grid value cancelled"))
  6504. def on_shortcut_list(self):
  6505. self.report_usage("on_shortcut_list()")
  6506. # add the tab if it was closed
  6507. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  6508. # delete the absolute and relative position and messages in the infobar
  6509. self.ui.position_label.setText("")
  6510. self.ui.rel_position_label.setText("")
  6511. # Switch plot_area to preferences page
  6512. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  6513. # self.ui.show()
  6514. def on_select_tab(self, name):
  6515. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  6516. if self.ui.splitter.sizes()[0] == 0:
  6517. self.ui.splitter.setSizes([1, 1])
  6518. else:
  6519. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  6520. self.ui.splitter.setSizes([0, 1])
  6521. if name == 'project':
  6522. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6523. elif name == 'selected':
  6524. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6525. elif name == 'tool':
  6526. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  6527. def on_copy_name(self):
  6528. self.report_usage("on_copy_name()")
  6529. obj = self.collection.get_active()
  6530. try:
  6531. name = obj.options["name"]
  6532. except AttributeError:
  6533. log.debug("on_copy_name() --> No object selected to copy it's name")
  6534. self.inform.emit('[WARNING_NOTCL]%s' %
  6535. _(" No object selected to copy it's name"))
  6536. return
  6537. self.clipboard.setText(name)
  6538. self.inform.emit(_("Name copied on clipboard ..."))
  6539. def on_mouse_click_over_plot(self, event):
  6540. """
  6541. Default actions are:
  6542. :param event: Contains information about the event, like which button
  6543. was clicked, the pixel coordinates and the axes coordinates.
  6544. :return: None
  6545. """
  6546. self.pos = []
  6547. if self.is_legacy is False:
  6548. event_pos = event.pos
  6549. if self.defaults["global_pan_button"] == '2':
  6550. pan_button = 2
  6551. else:
  6552. pan_button = 3
  6553. # Set the mouse button for panning
  6554. self.plotcanvas.view.camera.pan_button_setting = pan_button
  6555. else:
  6556. event_pos = (event.xdata, event.ydata)
  6557. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6558. if self.defaults["global_pan_button"] == '2':
  6559. pan_button = 3
  6560. else:
  6561. pan_button = 2
  6562. # So it can receive key presses
  6563. self.plotcanvas.native.setFocus()
  6564. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6565. if self.grid_status() == True:
  6566. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  6567. else:
  6568. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  6569. try:
  6570. if event.button == 1:
  6571. # Reset here the relative coordinates so there is a new reference on the click position
  6572. if self.rel_point1 is None:
  6573. self.rel_point1 = self.pos
  6574. else:
  6575. self.rel_point2 = copy(self.rel_point1)
  6576. self.rel_point1 = self.pos
  6577. self.on_mouse_move_over_plot(event, origin_click=True)
  6578. except Exception as e:
  6579. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  6580. def on_double_click_over_plot(self, event):
  6581. if event.button == 1:
  6582. self.doubleclick = True
  6583. def on_mouse_move_over_plot(self, event, origin_click=None):
  6584. """
  6585. Callback for the mouse motion event over the plot.
  6586. :param event: Contains information about the event.
  6587. :param origin_click
  6588. :return: None
  6589. """
  6590. if self.is_legacy is False:
  6591. event_pos = event.pos
  6592. if self.defaults["global_pan_button"] == '2':
  6593. pan_button = 2
  6594. else:
  6595. pan_button = 3
  6596. event_is_dragging = event.is_dragging
  6597. else:
  6598. event_pos = (event.xdata, event.ydata)
  6599. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6600. if self.defaults["global_pan_button"] == '2':
  6601. pan_button = 3
  6602. else:
  6603. pan_button = 2
  6604. event_is_dragging = self.plotcanvas.is_dragging
  6605. # So it can receive key presses
  6606. self.plotcanvas.native.setFocus()
  6607. self.pos_jump = event_pos
  6608. self.ui.popMenu.mouse_is_panning = False
  6609. if not origin_click:
  6610. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  6611. if event.button == pan_button and event_is_dragging == 1:
  6612. self.ui.popMenu.mouse_is_panning = True
  6613. return
  6614. if self.rel_point1 is not None:
  6615. try: # May fail in case mouse not within axes
  6616. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6617. if self.grid_status() == True:
  6618. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6619. # Update cursor
  6620. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  6621. symbol='++', edge_color='black', size=self.defaults["global_cursor_size"])
  6622. else:
  6623. pos = (pos_canvas[0], pos_canvas[1])
  6624. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6625. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  6626. dx = pos[0] - float(self.rel_point1[0])
  6627. dy = pos[1] - float(self.rel_point1[1])
  6628. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6629. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6630. self.mouse = [pos[0], pos[1]]
  6631. # if the mouse is moved and the LMB is clicked then the action is a selection
  6632. if event_is_dragging == 1 and event.button == 1:
  6633. self.delete_selection_shape()
  6634. if dx < 0:
  6635. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  6636. face_color=self.defaults['global_alt_sel_fill'])
  6637. self.selection_type = False
  6638. elif dx > 0:
  6639. self.draw_moving_selection_shape(self.pos, pos)
  6640. self.selection_type = True
  6641. else:
  6642. self.selection_type = None
  6643. # hover effect - enabled in Preferences -> General -> GUI Settings
  6644. if self.defaults['global_hover']:
  6645. for obj in self.collection.get_list():
  6646. try:
  6647. # select the object(s) only if it is enabled (plotted)
  6648. if obj.options['plot']:
  6649. if obj not in self.collection.get_selected():
  6650. poly_obj = Polygon(
  6651. [(obj.options['xmin'], obj.options['ymin']),
  6652. (obj.options['xmax'], obj.options['ymin']),
  6653. (obj.options['xmax'], obj.options['ymax']),
  6654. (obj.options['xmin'], obj.options['ymax'])]
  6655. )
  6656. if Point(pos).within(poly_obj):
  6657. if obj.isHovering is False:
  6658. obj.isHovering = True
  6659. obj.notHovering = True
  6660. # create the selection box around the selected object
  6661. self.draw_hover_shape(obj, color='#d1e0e0FF')
  6662. else:
  6663. if obj.notHovering is True:
  6664. obj.notHovering = False
  6665. obj.isHovering = False
  6666. self.delete_hover_shape()
  6667. except:
  6668. # the Exception here will happen if we try to select on screen and we have an
  6669. # newly (and empty) just created Geometry or Excellon object that do not have the
  6670. # xmin, xmax, ymin, ymax options.
  6671. # In this case poly_obj creation (see above) will fail
  6672. pass
  6673. except:
  6674. self.ui.position_label.setText("")
  6675. self.ui.rel_position_label.setText("")
  6676. self.mouse = None
  6677. def on_mouse_click_release_over_plot(self, event):
  6678. """
  6679. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  6680. and has been registered in ''self.__init__()''.
  6681. :param event: contains information about the event.
  6682. :return:
  6683. """
  6684. pos = 0, 0
  6685. if self.is_legacy is False:
  6686. event_pos = event.pos
  6687. right_button = 2
  6688. else:
  6689. event_pos = (event.xdata, event.ydata)
  6690. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6691. right_button = 3
  6692. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6693. if self.grid_status() == True:
  6694. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6695. else:
  6696. pos = (pos_canvas[0], pos_canvas[1])
  6697. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  6698. # canvas menu
  6699. if event.button == right_button: # right click
  6700. if self.ui.popMenu.mouse_is_panning is False:
  6701. self.cursor = QtGui.QCursor()
  6702. self.populate_cmenu_grids()
  6703. self.ui.popMenu.popup(self.cursor.pos())
  6704. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  6705. # selection and then select a type of selection ("enclosing" or "touching")
  6706. try:
  6707. if event.button == 1: # left click
  6708. modifiers = QtWidgets.QApplication.keyboardModifiers()
  6709. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  6710. if modifiers == QtCore.Qt.ShiftModifier:
  6711. # do not auto open the Project Tab
  6712. self.click_noproject = True
  6713. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  6714. self.inform.emit('[success] %s' %
  6715. _("Coordinates copied to clipboard."))
  6716. return
  6717. if self.doubleclick is True:
  6718. self.doubleclick = False
  6719. if self.collection.get_selected():
  6720. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6721. if self.ui.splitter.sizes()[0] == 0:
  6722. self.ui.splitter.setSizes([1, 1])
  6723. # delete the selection shape(S) as it may be in the way
  6724. self.delete_selection_shape()
  6725. self.delete_hover_shape()
  6726. else:
  6727. if self.selection_type is not None:
  6728. self.selection_area_handler(self.pos, pos, self.selection_type)
  6729. self.selection_type = None
  6730. else:
  6731. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  6732. if key_modifier == QtCore.Qt.ShiftModifier:
  6733. mod_key = 'Shift'
  6734. elif key_modifier == QtCore.Qt.ControlModifier:
  6735. mod_key = 'Control'
  6736. else:
  6737. mod_key = None
  6738. if mod_key == self.defaults["global_mselect_key"]:
  6739. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  6740. # deselect, and if it's not selected then it will be selected
  6741. # If there is no active command (self.command_active is None) then we check if we clicked
  6742. # on a object by checking the bounding limits against mouse click position
  6743. if self.command_active is None:
  6744. self.select_objects(key='CTRL')
  6745. self.delete_hover_shape()
  6746. else:
  6747. # If there is no active command (self.command_active is None) then we check if we clicked
  6748. # on a object by checking the bounding limits against mouse click position
  6749. if self.command_active is None:
  6750. self.select_objects()
  6751. self.delete_hover_shape()
  6752. except Exception as e:
  6753. log.warning("Error: %s" % str(e))
  6754. return
  6755. def selection_area_handler(self, start_pos, end_pos, sel_type):
  6756. """
  6757. :param start_pos: mouse position when the selection LMB click was done
  6758. :param end_pos: mouse position when the left mouse button is released
  6759. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  6760. :return:
  6761. """
  6762. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  6763. self.delete_selection_shape()
  6764. for obj in self.collection.get_list():
  6765. try:
  6766. # select the object(s) only if it is enabled (plotted)
  6767. if obj.options['plot']:
  6768. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  6769. (obj.options['xmax'], obj.options['ymin']),
  6770. (obj.options['xmax'], obj.options['ymax']),
  6771. (obj.options['xmin'], obj.options['ymax'])])
  6772. if sel_type is True:
  6773. if poly_obj.within(poly_selection):
  6774. # create the selection box around the selected object
  6775. if self.defaults['global_selection_shape'] is True:
  6776. self.draw_selection_shape(obj)
  6777. self.collection.set_active(obj.options['name'])
  6778. else:
  6779. if poly_selection.intersects(poly_obj):
  6780. # create the selection box around the selected object
  6781. if self.defaults['global_selection_shape'] is True:
  6782. self.draw_selection_shape(obj)
  6783. self.collection.set_active(obj.options['name'])
  6784. except Exception as e:
  6785. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  6786. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  6787. # In this case poly_obj creation (see above) will fail
  6788. log.debug("App.selection_area_handler() --> %s" % str(e))
  6789. def select_objects(self, key=None):
  6790. # list where we store the overlapped objects under our mouse left click position
  6791. objects_under_the_click_list = []
  6792. # Populate the list with the overlapped objects on the click position
  6793. curr_x, curr_y = self.pos
  6794. for obj in self.all_objects_list:
  6795. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  6796. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  6797. if obj.options['name'] not in objects_under_the_click_list:
  6798. if obj.options['plot']:
  6799. # add objects to the objects_under_the_click list only if the object is plotted
  6800. # (active and not disabled)
  6801. objects_under_the_click_list.append(obj.options['name'])
  6802. try:
  6803. # If there is no element in the overlapped objects list then make everyone inactive
  6804. # because we selected "nothing"
  6805. if not objects_under_the_click_list:
  6806. self.collection.set_all_inactive()
  6807. # delete the possible selection box around a possible selected object
  6808. self.delete_selection_shape()
  6809. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  6810. # only when working on App
  6811. if self.call_source == 'app':
  6812. if self.click_noproject is False:
  6813. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6814. else:
  6815. # restore auto open the Project Tab
  6816. self.click_noproject = False
  6817. # delete any text in the status bar, implicitly the last object name that was selected
  6818. self.inform.emit("")
  6819. else:
  6820. self.call_source = 'app'
  6821. else:
  6822. # case when there is only an object under the click and we toggle it
  6823. if len(objects_under_the_click_list) == 1:
  6824. if self.collection.get_active() is None:
  6825. self.collection.set_active(objects_under_the_click_list[0])
  6826. # create the selection box around the selected object
  6827. curr_sel_obj = self.collection.get_active()
  6828. if self.defaults['global_selection_shape'] is True:
  6829. self.draw_selection_shape(curr_sel_obj)
  6830. # self.inform.emit('[selected] %s: %s selected' %
  6831. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6832. if curr_sel_obj.kind == 'gerber':
  6833. self.inform.emit(
  6834. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6835. color='green', name=str(curr_sel_obj.options['name'])))
  6836. elif curr_sel_obj.kind == 'excellon':
  6837. self.inform.emit(
  6838. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6839. color='brown', name=str(curr_sel_obj.options['name'])))
  6840. elif curr_sel_obj.kind == 'cncjob':
  6841. self.inform.emit(
  6842. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6843. color='blue', name=str(curr_sel_obj.options['name'])))
  6844. elif curr_sel_obj.kind == 'geometry':
  6845. self.inform.emit(
  6846. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6847. color='red', name=str(curr_sel_obj.options['name'])))
  6848. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  6849. self.collection.set_all_inactive()
  6850. self.delete_selection_shape()
  6851. self.collection.set_active(objects_under_the_click_list[0])
  6852. # create the selection box around the selected object
  6853. curr_sel_obj = self.collection.get_active()
  6854. if self.defaults['global_selection_shape'] is True:
  6855. self.draw_selection_shape(curr_sel_obj)
  6856. # self.inform.emit('[selected] %s: %s selected' %
  6857. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6858. if curr_sel_obj.kind == 'gerber':
  6859. self.inform.emit(
  6860. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6861. color='green', name=str(curr_sel_obj.options['name'])))
  6862. elif curr_sel_obj.kind == 'excellon':
  6863. self.inform.emit(
  6864. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6865. color='brown', name=str(curr_sel_obj.options['name'])))
  6866. elif curr_sel_obj.kind == 'cncjob':
  6867. self.inform.emit(
  6868. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6869. color='blue', name=str(curr_sel_obj.options['name'])))
  6870. elif curr_sel_obj.kind == 'geometry':
  6871. self.inform.emit(
  6872. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6873. color='red', name=str(curr_sel_obj.options['name'])))
  6874. else:
  6875. self.collection.set_all_inactive()
  6876. self.delete_selection_shape()
  6877. if self.call_source == 'app':
  6878. # delete any text in the status bar, implicitly the last object name that was selected
  6879. self.inform.emit("")
  6880. else:
  6881. self.call_source = 'app'
  6882. else:
  6883. # If there is no selected object
  6884. # make active the first element of the overlapped objects list
  6885. if self.collection.get_active() is None:
  6886. self.collection.set_active(objects_under_the_click_list[0])
  6887. name_sel_obj = self.collection.get_active().options['name']
  6888. # In case that there is a selected object but it is not in the overlapped object list
  6889. # make that object inactive and activate the first element in the overlapped object list
  6890. if name_sel_obj not in objects_under_the_click_list:
  6891. self.collection.set_inactive(name_sel_obj)
  6892. name_sel_obj = objects_under_the_click_list[0]
  6893. self.collection.set_active(name_sel_obj)
  6894. else:
  6895. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  6896. self.collection.set_all_inactive()
  6897. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  6898. len(objects_under_the_click_list)])
  6899. curr_sel_obj = self.collection.get_active()
  6900. # delete the possible selection box around a possible selected object
  6901. self.delete_selection_shape()
  6902. # create the selection box around the selected object
  6903. if self.defaults['global_selection_shape'] is True:
  6904. self.draw_selection_shape(curr_sel_obj)
  6905. # self.inform.emit('[selected] %s: %s selected' %
  6906. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6907. if curr_sel_obj.kind == 'gerber':
  6908. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6909. color='green', name=str(curr_sel_obj.options['name'])))
  6910. elif curr_sel_obj.kind == 'excellon':
  6911. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6912. color='brown', name=str(curr_sel_obj.options['name'])))
  6913. elif curr_sel_obj.kind == 'cncjob':
  6914. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6915. color='blue', name=str(curr_sel_obj.options['name'])))
  6916. elif curr_sel_obj.kind == 'geometry':
  6917. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6918. color='red', name=str(curr_sel_obj.options['name'])))
  6919. # for obj in self.collection.get_list():
  6920. # obj.plot()
  6921. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  6922. # TODO: on selected objects change the object colors and do not draw the selection box
  6923. # self.plotcanvas.update() # this updates the canvas
  6924. except Exception as e:
  6925. log.error("[ERROR] Something went bad. %s" % str(e))
  6926. return
  6927. def delete_hover_shape(self):
  6928. self.hover_shapes.clear()
  6929. self.hover_shapes.redraw()
  6930. def draw_hover_shape(self, sel_obj, color=None):
  6931. """
  6932. :param sel_obj: the object for which the hover shape must be drawn
  6933. :return:
  6934. """
  6935. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6936. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6937. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6938. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6939. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  6940. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6941. hover_rect = hover_rect.buffer(-0.1)
  6942. hover_rect = hover_rect.buffer(0.2)
  6943. else:
  6944. hover_rect = hover_rect.buffer(-0.00393)
  6945. hover_rect = hover_rect.buffer(0.00787)
  6946. # if color:
  6947. # face = Color(color)
  6948. # face.alpha = 0.2
  6949. # outline = Color(color, alpha=0.8)
  6950. # else:
  6951. # face = Color(self.defaults['global_sel_fill'])
  6952. # face.alpha = 0.2
  6953. # outline = self.defaults['global_sel_line']
  6954. if color:
  6955. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  6956. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  6957. else:
  6958. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  6959. outline = self.defaults['global_sel_line']
  6960. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  6961. if self.is_legacy is True:
  6962. self.hover_shapes.redraw()
  6963. def delete_selection_shape(self):
  6964. self.move_tool.sel_shapes.clear()
  6965. self.move_tool.sel_shapes.redraw()
  6966. def draw_selection_shape(self, sel_obj, color=None):
  6967. """
  6968. :param sel_obj: the object for which the selection shape must be drawn
  6969. :return:
  6970. """
  6971. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6972. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6973. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6974. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6975. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6976. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6977. sel_rect = sel_rect.buffer(-0.1)
  6978. sel_rect = sel_rect.buffer(0.2)
  6979. else:
  6980. sel_rect = sel_rect.buffer(-0.00393)
  6981. sel_rect = sel_rect.buffer(0.00787)
  6982. # if color:
  6983. # face = Color(color, alpha=0.2)
  6984. # outline = Color(color, alpha=0.8)
  6985. # else:
  6986. # face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  6987. # outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  6988. if color:
  6989. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  6990. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  6991. else:
  6992. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  6993. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  6994. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  6995. color=outline,
  6996. face_color=face,
  6997. update=True,
  6998. layer=0,
  6999. tolerance=None))
  7000. if self.is_legacy is True:
  7001. self.move_tool.sel_shapes.redraw()
  7002. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  7003. """
  7004. :param old_coords: old coordinates
  7005. :param coords: new coordinates
  7006. :return:
  7007. """
  7008. if 'color' in kwargs:
  7009. color = kwargs['color']
  7010. else:
  7011. color = self.defaults['global_sel_line']
  7012. if 'face_color' in kwargs:
  7013. face_color = kwargs['face_color']
  7014. else:
  7015. face_color = self.defaults['global_sel_fill']
  7016. if 'face_alpha' in kwargs:
  7017. face_alpha = kwargs['face_alpha']
  7018. else:
  7019. face_alpha = 0.3
  7020. x0, y0 = old_coords
  7021. x1, y1 = coords
  7022. pt1 = (x0, y0)
  7023. pt2 = (x1, y0)
  7024. pt3 = (x1, y1)
  7025. pt4 = (x0, y1)
  7026. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7027. # color_t = Color(face_color)
  7028. # color_t.alpha = face_alpha
  7029. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  7030. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  7031. layer=0, tolerance=None)
  7032. if self.is_legacy is True:
  7033. self.move_tool.sel_shapes.redraw()
  7034. def on_file_new_click(self):
  7035. if self.collection.get_list() and self.should_we_save:
  7036. msgbox = QtWidgets.QMessageBox()
  7037. # msgbox.setText("<B>Save changes ...</B>")
  7038. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7039. "Creating a New project will delete them.\n"
  7040. "Do you want to Save the project?"))
  7041. msgbox.setWindowTitle(_("Save changes"))
  7042. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  7043. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7044. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7045. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7046. msgbox.setDefaultButton(bt_yes)
  7047. msgbox.exec_()
  7048. response = msgbox.clickedButton()
  7049. if response == bt_yes:
  7050. self.on_file_saveprojectas()
  7051. elif response == bt_cancel:
  7052. return
  7053. elif response == bt_no:
  7054. self.on_file_new()
  7055. else:
  7056. self.on_file_new()
  7057. self.inform.emit('[success] %s...' %
  7058. _("New Project created"))
  7059. def on_file_new(self, cli=None):
  7060. """
  7061. Callback for menu item File->New. Returns the application to its
  7062. startup state. This method is thread-safe.
  7063. :return: None
  7064. """
  7065. self.report_usage("on_file_new")
  7066. # Remove everything from memory
  7067. App.log.debug("on_file_new()")
  7068. if self.call_source != 'app':
  7069. self.editor2object(cleanup=True)
  7070. # ## EDITOR section
  7071. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  7072. self.exc_editor = FlatCAMExcEditor(self)
  7073. self.grb_editor = FlatCAMGrbEditor(self)
  7074. # Clear pool
  7075. self.clear_pool()
  7076. for obj in self.collection.get_list():
  7077. # delete shapes left drawn from mark shape_collections, if any
  7078. if isinstance(obj, FlatCAMGerber):
  7079. try:
  7080. obj.mark_shapes.enabled = False
  7081. obj.mark_shapes.clear(update=True)
  7082. except AttributeError:
  7083. pass
  7084. # also delete annotation shapes, if any
  7085. elif isinstance(obj, FlatCAMCNCjob):
  7086. try:
  7087. obj.annotation.enabled = False
  7088. obj.annotation.clear(update=True)
  7089. except AttributeError:
  7090. pass
  7091. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7092. self.init_tcl()
  7093. self.delete_selection_shape()
  7094. self.collection.delete_all()
  7095. self.setup_component_editor()
  7096. # Clear project filename
  7097. self.project_filename = None
  7098. # Load the application defaults
  7099. self.load_defaults(filename='current_defaults')
  7100. # Re-fresh project options
  7101. self.on_options_app2project()
  7102. # Init Tools
  7103. self.init_tools()
  7104. if cli is None:
  7105. # Close any Tabs opened in the Plot Tab Area section
  7106. for index in range(self.ui.plot_tab_area.count()):
  7107. self.ui.plot_tab_area.closeTab(index)
  7108. # for whatever reason previous command does not close the last tab so I do it manually
  7109. self.ui.plot_tab_area.closeTab(0)
  7110. # # And then add again the Plot Area
  7111. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  7112. self.ui.plot_tab_area.protectTab(0)
  7113. # take the focus of the Notebook on Project Tab.
  7114. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7115. self.set_ui_title(name=_("New Project - Not saved"))
  7116. def obj_properties(self):
  7117. self.report_usage("obj_properties()")
  7118. self.properties_tool.run(toggle=False)
  7119. def on_project_context_save(self):
  7120. obj = self.collection.get_active()
  7121. if type(obj) == FlatCAMGeometry:
  7122. self.on_file_exportdxf()
  7123. elif type(obj) == FlatCAMExcellon:
  7124. self.on_file_saveexcellon()
  7125. elif type(obj) == FlatCAMCNCjob:
  7126. obj.on_exportgcode_button_click()
  7127. elif type(obj) == FlatCAMGerber:
  7128. self.on_file_savegerber()
  7129. def obj_move(self):
  7130. self.report_usage("obj_move()")
  7131. self.move_tool.run(toggle=False)
  7132. def on_fileopengerber(self, checked=None, name=None):
  7133. """
  7134. File menu callback for opening a Gerber.
  7135. :return: None
  7136. """
  7137. self.report_usage("on_fileopengerber")
  7138. App.log.debug("on_fileopengerber()")
  7139. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  7140. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  7141. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  7142. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  7143. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  7144. "*.mil);;" \
  7145. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  7146. "Allegro Files (*.art);;" \
  7147. "Mentor Files (*.pho *.gdo);;" \
  7148. "All Files (*.*)"
  7149. if name is None:
  7150. try:
  7151. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  7152. directory=self.get_last_folder(),
  7153. filter=_filter_)
  7154. except TypeError:
  7155. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  7156. filenames = [str(filename) for filename in filenames]
  7157. else:
  7158. filenames = [name]
  7159. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7160. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7161. _("Opening Gerber file.")),
  7162. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7163. color=QtGui.QColor("gray"))
  7164. if len(filenames) == 0:
  7165. self.inform.emit('[WARNING_NOTCL] %s' %
  7166. _("Open Gerber cancelled."))
  7167. else:
  7168. for filename in filenames:
  7169. if filename != '':
  7170. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  7171. def on_fileopenexcellon(self, checked=None, name=None):
  7172. """
  7173. File menu callback for opening an Excellon file.
  7174. :return: None
  7175. """
  7176. self.report_usage("on_fileopenexcellon")
  7177. App.log.debug("on_fileopenexcellon()")
  7178. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  7179. "All Files (*.*)"
  7180. if name is None:
  7181. try:
  7182. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  7183. directory=self.get_last_folder(),
  7184. filter=_filter_)
  7185. except TypeError:
  7186. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  7187. filenames = [str(filename) for filename in filenames]
  7188. else:
  7189. filenames = [str(name)]
  7190. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7191. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7192. _("Opening Excellon file.")),
  7193. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7194. color=QtGui.QColor("gray"))
  7195. if len(filenames) == 0:
  7196. self.inform.emit('[WARNING_NOTCL]%s' %
  7197. _(" Open Excellon cancelled."))
  7198. else:
  7199. for filename in filenames:
  7200. if filename != '':
  7201. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  7202. def on_fileopengcode(self, checked=None, name=None):
  7203. """
  7204. File menu call back for opening gcode.
  7205. :return: None
  7206. """
  7207. self.report_usage("on_fileopengcode")
  7208. App.log.debug("on_fileopengcode()")
  7209. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  7210. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  7211. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  7212. "All Files (*.*)"
  7213. if name is None:
  7214. try:
  7215. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  7216. directory=self.get_last_folder(),
  7217. filter=_filter_)
  7218. except TypeError:
  7219. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  7220. filenames = [str(filename) for filename in filenames]
  7221. else:
  7222. filenames = [name]
  7223. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7224. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7225. _("Opening G-Code file.")),
  7226. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7227. color=QtGui.QColor("gray"))
  7228. if len(filenames) == 0:
  7229. self.inform.emit('[WARNING_NOTCL] %s' %
  7230. _("Open G-Code cancelled."))
  7231. else:
  7232. for filename in filenames:
  7233. if filename != '':
  7234. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename]})
  7235. def on_file_openproject(self, checked=None):
  7236. """
  7237. File menu callback for opening a project.
  7238. :return: None
  7239. """
  7240. self.report_usage("on_file_openproject")
  7241. App.log.debug("on_file_openproject()")
  7242. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  7243. try:
  7244. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  7245. directory=self.get_last_folder(), filter=_filter_)
  7246. except TypeError:
  7247. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  7248. # The Qt methods above will return a QString which can cause problems later.
  7249. # So far json.dump() will fail to serialize it.
  7250. # TODO: Improve the serialization methods and remove this fix.
  7251. filename = str(filename)
  7252. if filename == "":
  7253. self.inform.emit('[WARNING_NOTCL] %s' %
  7254. _("Open Project cancelled."))
  7255. else:
  7256. # self.worker_task.emit({'fcn': self.open_project,
  7257. # 'params': [filename]})
  7258. # The above was failing because open_project() is not
  7259. # thread safe. The new_project()
  7260. self.open_project(filename)
  7261. def on_file_openconfig(self, checked=None):
  7262. """
  7263. File menu callback for opening a config file.
  7264. :return: None
  7265. """
  7266. self.report_usage("on_file_openconfig")
  7267. App.log.debug("on_file_openconfig()")
  7268. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  7269. try:
  7270. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7271. directory=self.data_path, filter=_filter_)
  7272. except TypeError:
  7273. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7274. filter=_filter_)
  7275. if filename == "":
  7276. self.inform.emit('[WARNING_NOTCL] %s' %
  7277. _("Open Config cancelled."))
  7278. else:
  7279. self.open_config_file(filename)
  7280. def on_file_exportsvg(self):
  7281. """
  7282. Callback for menu item File->Export SVG.
  7283. :return: None
  7284. """
  7285. self.report_usage("on_file_exportsvg")
  7286. App.log.debug("on_file_exportsvg()")
  7287. obj = self.collection.get_active()
  7288. if obj is None:
  7289. self.inform.emit('[WARNING_NOTCL] %s' %
  7290. _("No object selected."))
  7291. msg = _("Please Select a Geometry object to export")
  7292. msgbox = QtWidgets.QMessageBox()
  7293. msgbox.setInformativeText(msg)
  7294. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7295. msgbox.setDefaultButton(bt_ok)
  7296. msgbox.exec_()
  7297. return
  7298. # Check for more compatible types and add as required
  7299. if (not isinstance(obj, FlatCAMGeometry)
  7300. and not isinstance(obj, FlatCAMGerber)
  7301. and not isinstance(obj, FlatCAMCNCjob)
  7302. and not isinstance(obj, FlatCAMExcellon)):
  7303. msg = '[ERROR_NOTCL] %s' % \
  7304. _("Only Geometry, Gerber and CNCJob objects can be used.")
  7305. msgbox = QtWidgets.QMessageBox()
  7306. msgbox.setInformativeText(msg)
  7307. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7308. msgbox.setDefaultButton(bt_ok)
  7309. msgbox.exec_()
  7310. return
  7311. name = obj.options["name"]
  7312. _filter = "SVG File (*.svg);;All Files (*.*)"
  7313. try:
  7314. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7315. caption=_("Export SVG"),
  7316. directory=self.get_last_save_folder() + '/' + str(name),
  7317. filter=_filter)
  7318. except TypeError:
  7319. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  7320. filename = str(filename)
  7321. if filename == "":
  7322. self.inform.emit('[WARNING_NOTCL]%s' %
  7323. _(" Export SVG cancelled."))
  7324. return
  7325. else:
  7326. self.export_svg(name, filename)
  7327. if self.defaults["global_open_style"] is False:
  7328. self.file_opened.emit("SVG", filename)
  7329. self.file_saved.emit("SVG", filename)
  7330. def on_file_exportpng(self):
  7331. self.report_usage("on_file_exportpng")
  7332. App.log.debug("on_file_exportpng()")
  7333. self.date = str(datetime.today()).rpartition('.')[0]
  7334. self.date = ''.join(c for c in self.date if c not in ':-')
  7335. self.date = self.date.replace(' ', '_')
  7336. image = _screenshot()
  7337. data = np.asarray(image)
  7338. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  7339. self.inform.emit('[[WARNING_NOTCL]] %s' %
  7340. _('Data must be a 3D array with last dimension 3 or 4'))
  7341. return
  7342. filter_ = "PNG File (*.png);;All Files (*.*)"
  7343. try:
  7344. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7345. caption=_("Export PNG Image"),
  7346. directory=self.get_last_save_folder() + '/png_' + self.date,
  7347. filter=filter_)
  7348. except TypeError:
  7349. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  7350. filename = str(filename)
  7351. if filename == "":
  7352. self.inform.emit(_("Export PNG cancelled."))
  7353. return
  7354. else:
  7355. write_png(filename, data)
  7356. if self.defaults["global_open_style"] is False:
  7357. self.file_opened.emit("png", filename)
  7358. self.file_saved.emit("png", filename)
  7359. def on_file_savegerber(self):
  7360. """
  7361. Callback for menu item in Project context menu.
  7362. :return: None
  7363. """
  7364. self.report_usage("on_file_savegerber")
  7365. App.log.debug("on_file_savegerber()")
  7366. obj = self.collection.get_active()
  7367. if obj is None:
  7368. self.inform.emit('[WARNING_NOTCL] %s' %
  7369. _("No object selected. Please select an Gerber object to export."))
  7370. return
  7371. # Check for more compatible types and add as required
  7372. if not isinstance(obj, FlatCAMGerber):
  7373. self.inform.emit('[ERROR_NOTCL] %s' %
  7374. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7375. return
  7376. name = self.collection.get_active().options["name"]
  7377. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  7378. try:
  7379. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7380. caption="Save Gerber source file",
  7381. directory=self.get_last_save_folder() + '/' + name,
  7382. filter=_filter)
  7383. except TypeError:
  7384. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  7385. filename = str(filename)
  7386. if filename == "":
  7387. self.inform.emit('[WARNING_NOTCL] %s' %
  7388. _("Save Gerber source file cancelled."))
  7389. return
  7390. else:
  7391. self.save_source_file(name, filename)
  7392. if self.defaults["global_open_style"] is False:
  7393. self.file_opened.emit("Gerber", filename)
  7394. self.file_saved.emit("Gerber", filename)
  7395. def on_file_saveexcellon(self):
  7396. """
  7397. Callback for menu item in project context menu.
  7398. :return: None
  7399. """
  7400. self.report_usage("on_file_saveexcellon")
  7401. App.log.debug("on_file_saveexcellon()")
  7402. obj = self.collection.get_active()
  7403. if obj is None:
  7404. self.inform.emit('[WARNING_NOTCL] %s' %
  7405. _("No object selected. Please select an Excellon object to export."))
  7406. return
  7407. # Check for more compatible types and add as required
  7408. if not isinstance(obj, FlatCAMExcellon):
  7409. self.inform.emit('[ERROR_NOTCL] %s' %
  7410. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7411. return
  7412. name = self.collection.get_active().options["name"]
  7413. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7414. try:
  7415. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7416. caption=_("Save Excellon source file"),
  7417. directory=self.get_last_save_folder() + '/' + name,
  7418. filter=_filter)
  7419. except TypeError:
  7420. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  7421. filename = str(filename)
  7422. if filename == "":
  7423. self.inform.emit('[WARNING_NOTCL] %s' %
  7424. _("Saving Excellon source file cancelled."))
  7425. return
  7426. else:
  7427. self.save_source_file(name, filename)
  7428. if self.defaults["global_open_style"] is False:
  7429. self.file_opened.emit("Excellon", filename)
  7430. self.file_saved.emit("Excellon", filename)
  7431. def on_file_exportexcellon(self):
  7432. """
  7433. Callback for menu item File->Export->Excellon.
  7434. :return: None
  7435. """
  7436. self.report_usage("on_file_exportexcellon")
  7437. App.log.debug("on_file_exportexcellon()")
  7438. obj = self.collection.get_active()
  7439. if obj is None:
  7440. self.inform.emit('[WARNING_NOTCL] %s' %
  7441. _("No object selected. Please Select an Excellon object to export."))
  7442. return
  7443. # Check for more compatible types and add as required
  7444. if not isinstance(obj, FlatCAMExcellon):
  7445. self.inform.emit('[ERROR_NOTCL] %s' %
  7446. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7447. return
  7448. name = self.collection.get_active().options["name"]
  7449. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7450. try:
  7451. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7452. caption=_("Export Excellon"),
  7453. directory=self.get_last_save_folder() + '/' + name,
  7454. filter=_filter)
  7455. except TypeError:
  7456. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  7457. filename = str(filename)
  7458. if filename == "":
  7459. self.inform.emit('[WARNING_NOTCL] %s' %
  7460. _("Export Excellon cancelled."))
  7461. return
  7462. else:
  7463. self.export_excellon(name, filename)
  7464. if self.defaults["global_open_style"] is False:
  7465. self.file_opened.emit("Excellon", filename)
  7466. self.file_saved.emit("Excellon", filename)
  7467. def on_file_exportgerber(self):
  7468. """
  7469. Callback for menu item File->Export->Gerber.
  7470. :return: None
  7471. """
  7472. self.report_usage("on_file_exportgerber")
  7473. App.log.debug("on_file_exportgerber()")
  7474. obj = self.collection.get_active()
  7475. if obj is None:
  7476. self.inform.emit('[WARNING_NOTCL] %s' %
  7477. _("No object selected. Please Select an Gerber object to export."))
  7478. return
  7479. # Check for more compatible types and add as required
  7480. if not isinstance(obj, FlatCAMGerber):
  7481. self.inform.emit('[ERROR_NOTCL] %s' %
  7482. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7483. return
  7484. name = self.collection.get_active().options["name"]
  7485. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  7486. try:
  7487. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7488. caption=_("Export Gerber"),
  7489. directory=self.get_last_save_folder() + '/' + name,
  7490. filter=_filter_)
  7491. except TypeError:
  7492. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  7493. filename = str(filename)
  7494. if filename == "":
  7495. self.inform.emit('[WARNING_NOTCL] %s' %
  7496. _("Export Gerber cancelled."))
  7497. return
  7498. else:
  7499. self.export_gerber(name, filename)
  7500. if self.defaults["global_open_style"] is False:
  7501. self.file_opened.emit("Gerber", filename)
  7502. self.file_saved.emit("Gerber", filename)
  7503. def on_file_exportdxf(self):
  7504. """
  7505. Callback for menu item File->Export DXF.
  7506. :return: None
  7507. """
  7508. self.report_usage("on_file_exportdxf")
  7509. App.log.debug("on_file_exportdxf()")
  7510. obj = self.collection.get_active()
  7511. if obj is None:
  7512. self.inform.emit('[WARNING_NOTCL] %s' %
  7513. _("No object selected."))
  7514. msg = _("Please Select a Geometry object to export")
  7515. msgbox = QtWidgets.QMessageBox()
  7516. msgbox.setInformativeText(msg)
  7517. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7518. msgbox.setDefaultButton(bt_ok)
  7519. msgbox.exec_()
  7520. return
  7521. # Check for more compatible types and add as required
  7522. if not isinstance(obj, FlatCAMGeometry):
  7523. msg = '[ERROR_NOTCL] %s' % \
  7524. _("Only Geometry objects can be used.")
  7525. msgbox = QtWidgets.QMessageBox()
  7526. msgbox.setInformativeText(msg)
  7527. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7528. msgbox.setDefaultButton(bt_ok)
  7529. msgbox.exec_()
  7530. return
  7531. name = self.collection.get_active().options["name"]
  7532. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7533. try:
  7534. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7535. caption=_("Export DXF"),
  7536. directory=self.get_last_save_folder() + '/' + name,
  7537. filter=_filter_)
  7538. except TypeError:
  7539. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  7540. filter=_filter_)
  7541. filename = str(filename)
  7542. if filename == "":
  7543. self.inform.emit('[WARNING_NOTCL] %s' %
  7544. _("Export DXF cancelled."))
  7545. return
  7546. else:
  7547. self.export_dxf(name, filename)
  7548. if self.defaults["global_open_style"] is False:
  7549. self.file_opened.emit("DXF", filename)
  7550. self.file_saved.emit("DXF", filename)
  7551. def on_file_importsvg(self, type_of_obj):
  7552. """
  7553. Callback for menu item File->Import SVG.
  7554. :param type_of_obj: to import the SVG as Geometry or as Gerber
  7555. :type type_of_obj: str
  7556. :return: None
  7557. """
  7558. self.report_usage("on_file_importsvg")
  7559. App.log.debug("on_file_importsvg()")
  7560. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  7561. try:
  7562. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7563. directory=self.get_last_folder(), filter=_filter_)
  7564. except TypeError:
  7565. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7566. filter=_filter_)
  7567. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7568. type_of_obj = "geometry"
  7569. filenames = [str(filename) for filename in filenames]
  7570. if len(filenames) == 0:
  7571. self.inform.emit('[WARNING_NOTCL] %s' %
  7572. _("Open SVG cancelled."))
  7573. else:
  7574. for filename in filenames:
  7575. if filename != '':
  7576. self.worker_task.emit({'fcn': self.import_svg,
  7577. 'params': [filename, type_of_obj]})
  7578. def on_file_importdxf(self, type_of_obj):
  7579. """
  7580. Callback for menu item File->Import DXF.
  7581. :param type_of_obj: to import the DXF as Geometry or as Gerber
  7582. :type type_of_obj: str
  7583. :return: None
  7584. """
  7585. self.report_usage("on_file_importdxf")
  7586. App.log.debug("on_file_importdxf()")
  7587. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7588. try:
  7589. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7590. directory=self.get_last_folder(),
  7591. filter=_filter_)
  7592. except TypeError:
  7593. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7594. filter=_filter_)
  7595. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7596. type_of_obj = "geometry"
  7597. filenames = [str(filename) for filename in filenames]
  7598. if len(filenames) == 0:
  7599. self.inform.emit('[WARNING_NOTCL] %s' %
  7600. _("Open DXF cancelled."))
  7601. else:
  7602. for filename in filenames:
  7603. if filename != '':
  7604. self.worker_task.emit({'fcn': self.import_dxf,
  7605. 'params': [filename, type_of_obj]})
  7606. # ###############################################################################################################
  7607. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  7608. # ###############################################################################################################
  7609. def init_code_editor(self, name):
  7610. # Signals section
  7611. # Disconnect the old signals
  7612. try:
  7613. self.ui.buttonOpen.clicked.disconnect()
  7614. except TypeError:
  7615. pass
  7616. try:
  7617. self.ui.buttonSave.clicked.disconnect()
  7618. except TypeError:
  7619. pass
  7620. # add the tab if it was closed
  7621. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, '%s' % name)
  7622. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  7623. # delete the absolute and relative position and messages in the infobar
  7624. self.ui.position_label.setText("")
  7625. self.ui.rel_position_label.setText("")
  7626. # first clear previous text in text editor (if any)
  7627. self.ui.code_editor.clear()
  7628. self.ui.code_editor.setReadOnly(False)
  7629. self.toggle_codeeditor = True
  7630. self.ui.code_editor.completer_enable = False
  7631. self.ui.buttonRun.hide()
  7632. # make sure to keep a reference to the code editor
  7633. self.reference_code_editor = self.ui.code_editor
  7634. # Switch plot_area to CNCJob tab
  7635. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  7636. def on_view_source(self):
  7637. self.inform.emit('%s' %
  7638. _("Viewing the source code of the selected object."))
  7639. self.proc_container.view.set_busy(_("Loading..."))
  7640. try:
  7641. obj = self.collection.get_active()
  7642. except Exception as e:
  7643. log.debug("App.on_view_source() --> %s" % str(e))
  7644. self.inform.emit('[WARNING_NOTCL] %s' %
  7645. _("Select an Gerber or Excellon file to view it's source file."))
  7646. return 'fail'
  7647. if obj.kind == 'gerber':
  7648. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  7649. elif obj.kind == 'excellon':
  7650. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  7651. elif obj.kind == 'cncjob':
  7652. "GCode Files (*.NC);;All Files (*.*)"
  7653. else:
  7654. flt = "All Files (*.*)"
  7655. self.init_code_editor(name=_("Source Editor"))
  7656. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  7657. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  7658. # then append the text from GCode to the text editor
  7659. if obj.kind == 'cncjob':
  7660. try:
  7661. file = obj.export_gcode(
  7662. preamble=self.defaults["cncjob_prepend"],
  7663. postamble=self.defaults["cncjob_append"],
  7664. to_file=True)
  7665. if file == 'fail':
  7666. return 'fail'
  7667. except AttributeError:
  7668. self.inform.emit('[WARNING_NOTCL] %s' %
  7669. _("There is no selected object for which to see it's source file code."))
  7670. return 'fail'
  7671. else:
  7672. try:
  7673. file = StringIO(obj.source_file)
  7674. except AttributeError:
  7675. self.inform.emit('[WARNING_NOTCL] %s' %
  7676. _("There is no selected object for which to see it's source file code."))
  7677. return 'fail'
  7678. self.ui.cncjob_frame.hide()
  7679. try:
  7680. for line in file:
  7681. QtWidgets.QApplication.processEvents()
  7682. proc_line = str(line).strip('\n')
  7683. self.ui.code_editor.append(proc_line)
  7684. except Exception as e:
  7685. log.debug('App.on_view_source() -->%s' % str(e))
  7686. self.inform.emit('[ERROR] %s: %s' %
  7687. (_('Failed to load the source code for the selected object'), str(e)))
  7688. return
  7689. self.handleTextChanged()
  7690. self.ui.cncjob_frame.show()
  7691. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7692. self.proc_container.view.set_idle()
  7693. # self.ui.show()
  7694. def on_toggle_code_editor(self):
  7695. self.report_usage("on_toggle_code_editor()")
  7696. if self.toggle_codeeditor is False:
  7697. self.init_code_editor(name=_("Code Editor"))
  7698. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  7699. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  7700. else:
  7701. for idx in range(self.ui.plot_tab_area.count()):
  7702. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  7703. self.ui.plot_tab_area.closeTab(idx)
  7704. break
  7705. self.toggle_codeeditor = False
  7706. def on_filenewscript(self, silent=False):
  7707. """
  7708. Will create a new script file and open it in the Code Editor
  7709. :param silent: if True will not display status messages
  7710. :return: None
  7711. """
  7712. if silent is False:
  7713. self.inform.emit('[success] %s' %
  7714. _("New TCL script file created in Code Editor."))
  7715. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  7716. self.init_code_editor(name=_("Script Editor"))
  7717. self.ui.code_editor.completer_enable = True
  7718. self.ui.code_editor.append(_(
  7719. "#\n"
  7720. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  7721. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  7722. "#\n\n"
  7723. "# FlatCAM commands list:\n"
  7724. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, ClearCopper,\n"
  7725. "# Cncjob, Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, GetNames,\n"
  7726. "# GetSys, ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillDrills,\n"
  7727. "# MillSlots, Mirror, New, NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"
  7728. "# Options, Paint, Panelize, Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, SubtractPoly,\n"
  7729. "# SubtractRectangle, Version, WriteGCode\n"
  7730. "#\n\n"
  7731. ))
  7732. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  7733. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  7734. self.ui.buttonRun.show()
  7735. try:
  7736. self.ui.buttonRun.clicked.disconnect(self.handleRunCode)
  7737. except TypeError:
  7738. pass
  7739. self.ui.buttonRun.clicked.connect(self.handleRunCode)
  7740. self.handleTextChanged()
  7741. self.ui.code_editor.show()
  7742. def on_fileopenscript(self, name=None, silent=False):
  7743. """
  7744. Will open a Tcl script file into the Code Editor
  7745. :param silent: if True will not display status messages
  7746. :param name: name of a Tcl script file to open
  7747. :return:
  7748. """
  7749. if name:
  7750. filename = name
  7751. else:
  7752. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7753. try:
  7754. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  7755. directory=self.get_last_folder(), filter=_filter_)
  7756. except TypeError:
  7757. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  7758. # The Qt methods above will return a QString which can cause problems later.
  7759. # So far json.dump() will fail to serialize it.
  7760. # TODO: Improve the serialization methods and remove this fix.
  7761. filename = str(filename)
  7762. if filename == "":
  7763. if silent is False:
  7764. self.inform.emit('[WARNING_NOTCL] %s' %
  7765. _("Open TCL script cancelled."))
  7766. else:
  7767. self.on_filenewscript()
  7768. try:
  7769. with open(filename, "r") as opened_script:
  7770. try:
  7771. for line in opened_script:
  7772. proc_line = str(line).strip('\n')
  7773. self.ui.code_editor.append(proc_line)
  7774. except Exception as e:
  7775. log.debug('App.on_fileopenscript() -->%s' % str(e))
  7776. if silent is False:
  7777. self.inform.emit('[ERROR] %s %s' %
  7778. ('App.on_fileopenscript() -->', str(e)))
  7779. return
  7780. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7781. self.handleTextChanged()
  7782. if silent is False:
  7783. self.inform.emit('[success] %s' %
  7784. _("TCL script file opened in Code Editor."))
  7785. # self.ui.show()
  7786. except Exception as e:
  7787. log.debug("App.on_fileopenscript() -> %s" % str(e))
  7788. def on_filerunscript(self, name=None, silent=False):
  7789. """
  7790. File menu callback for loading and running a TCL script.
  7791. :param silent: if True will not display status messages
  7792. :param name: name of a Tcl script file to be run by FlatCAM
  7793. :return: None
  7794. """
  7795. self.report_usage("on_filerunscript")
  7796. App.log.debug("on_file_runscript()")
  7797. if name:
  7798. filename = name
  7799. if self.cmd_line_headless != 1:
  7800. self.splash.showMessage('%s: %ssec\n%s' %
  7801. (_("Canvas initialization started.\n"
  7802. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7803. _("Executing FlatCAMScript file.")
  7804. ),
  7805. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7806. color=QtGui.QColor("gray"))
  7807. else:
  7808. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7809. try:
  7810. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  7811. directory=self.get_last_folder(), filter=_filter_)
  7812. except TypeError:
  7813. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  7814. # The Qt methods above will return a QString which can cause problems later.
  7815. # So far json.dump() will fail to serialize it.
  7816. # TODO: Improve the serialization methods and remove this fix.
  7817. filename = str(filename)
  7818. if filename == "":
  7819. if silent is False:
  7820. self.inform.emit('[WARNING_NOTCL] %s' %
  7821. _("Run TCL script cancelled."))
  7822. else:
  7823. if self.cmd_line_headless != 1:
  7824. if self.ui.shell_dock.isHidden():
  7825. self.ui.shell_dock.show()
  7826. try:
  7827. with open(filename, "r") as tcl_script:
  7828. cmd_line_shellfile_content = tcl_script.read()
  7829. if self.cmd_line_headless != 1:
  7830. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  7831. else:
  7832. self.shell._sysShell.exec_command(cmd_line_shellfile_content, no_echo=True)
  7833. if silent is False:
  7834. self.inform.emit('[success] %s' %
  7835. _("TCL script file opened in Code Editor and executed."))
  7836. except Exception as e:
  7837. log.debug("App.on_filerunscript() -> %s" % str(e))
  7838. sys.exit(2)
  7839. def on_file_saveproject(self, silent=False):
  7840. """
  7841. Callback for menu item File->Save Project. Saves the project to
  7842. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7843. if set to None. The project is saved by calling ``self.save_project()``.
  7844. :param silent: if True will not display status messages
  7845. :return: None
  7846. """
  7847. self.report_usage("on_file_saveproject")
  7848. if self.project_filename is None:
  7849. self.on_file_saveprojectas()
  7850. else:
  7851. self.worker_task.emit({'fcn': self.save_project,
  7852. 'params': [self.project_filename, silent]})
  7853. if self.defaults["global_open_style"] is False:
  7854. self.file_opened.emit("project", self.project_filename)
  7855. self.file_saved.emit("project", self.project_filename)
  7856. self.set_ui_title(name=self.project_filename)
  7857. self.should_we_save = False
  7858. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7859. """
  7860. Callback for menu item File->Save Project As... Opens a file
  7861. chooser and saves the project to the given file via
  7862. ``self.save_project()``.
  7863. :param make_copy if to be create a copy of the project; boolean
  7864. :param use_thread: if to be run in a separate thread; boolean
  7865. :param quit_action: if to be followed by quiting the application; boolean
  7866. :return: None
  7867. """
  7868. self.report_usage("on_file_saveprojectas")
  7869. self.date = str(datetime.today()).rpartition('.')[0]
  7870. self.date = ''.join(c for c in self.date if c not in ':-')
  7871. self.date = self.date.replace(' ', '_')
  7872. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  7873. try:
  7874. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7875. caption=_("Save Project As ..."),
  7876. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  7877. filter=filter_)
  7878. except TypeError:
  7879. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  7880. filename = str(filename)
  7881. if filename == '':
  7882. self.inform.emit('[WARNING_NOTCL] %s' %
  7883. _("Save Project cancelled."))
  7884. return
  7885. try:
  7886. f = open(filename, 'r')
  7887. f.close()
  7888. except IOError:
  7889. pass
  7890. if use_thread is True:
  7891. self.worker_task.emit({'fcn': self.save_project,
  7892. 'params': [filename, quit_action]})
  7893. else:
  7894. self.save_project(filename, quit_action)
  7895. # self.save_project(filename)
  7896. if self.defaults["global_open_style"] is False:
  7897. self.file_opened.emit("project", filename)
  7898. self.file_saved.emit("project", filename)
  7899. if not make_copy:
  7900. self.project_filename = filename
  7901. self.set_ui_title(name=self.project_filename)
  7902. self.should_we_save = False
  7903. def export_svg(self, obj_name, filename, scale_factor=0.00):
  7904. """
  7905. Exports a Geometry Object to an SVG file.
  7906. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7907. :param filename: Path to the SVG file to save to.
  7908. :param scale_factor: factor by which to change/scale the thickness of the features
  7909. :return:
  7910. """
  7911. self.report_usage("export_svg()")
  7912. if filename is None:
  7913. filename = self.defaults["global_last_save_folder"]
  7914. self.log.debug("export_svg()")
  7915. try:
  7916. obj = self.collection.get_by_name(str(obj_name))
  7917. except:
  7918. # TODO: The return behavior has not been established... should raise exception?
  7919. return "Could not retrieve object: %s" % obj_name
  7920. with self.proc_container.new(_("Exporting SVG")) as proc:
  7921. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7922. # Determine bounding area for svg export
  7923. bounds = obj.bounds()
  7924. size = obj.size()
  7925. # Convert everything to strings for use in the xml doc
  7926. svgwidth = str(size[0])
  7927. svgheight = str(size[1])
  7928. minx = str(bounds[0])
  7929. miny = str(bounds[1] - size[1])
  7930. uom = obj.units.lower()
  7931. # Add a SVG Header and footer to the svg output from shapely
  7932. # The transform flips the Y Axis so that everything renders
  7933. # properly within svg apps such as inkscape
  7934. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7935. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7936. svg_header += 'width="' + svgwidth + uom + '" '
  7937. svg_header += 'height="' + svgheight + uom + '" '
  7938. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7939. svg_header += '<g transform="scale(1,-1)">'
  7940. svg_footer = '</g> </svg>'
  7941. svg_elem = svg_header + exported_svg + svg_footer
  7942. # Parse the xml through a xml parser just to add line feeds
  7943. # and to make it look more pretty for the output
  7944. svgcode = parse_xml_string(svg_elem)
  7945. try:
  7946. with open(filename, 'w') as fp:
  7947. fp.write(svgcode.toprettyxml())
  7948. except PermissionError:
  7949. self.inform.emit('[WARNING] %s' %
  7950. _("Permission denied, saving not possible.\n"
  7951. "Most likely another app is holding the file open and not accessible."))
  7952. return 'fail'
  7953. if self.defaults["global_open_style"] is False:
  7954. self.file_opened.emit("SVG", filename)
  7955. self.file_saved.emit("SVG", filename)
  7956. self.inform.emit('[success] %s: %s' %
  7957. (_("SVG file exported to"), filename))
  7958. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  7959. """
  7960. Exports a Geometry Object to an SVG file in negative.
  7961. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7962. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  7963. :param filename: Path to the SVG file to save to.
  7964. :param boundary: thickness of a black border to surround all the features
  7965. :param scale_factor: factor by which to change/scale the thickness of the features
  7966. :param use_thread: if to be run in a separate thread; boolean
  7967. :return:
  7968. """
  7969. self.report_usage("export_negative()")
  7970. if filename is None:
  7971. filename = self.defaults["global_last_save_folder"]
  7972. self.log.debug("export_svg() negative")
  7973. try:
  7974. obj = self.collection.get_by_name(str(obj_name))
  7975. except:
  7976. # TODO: The return behavior has not been established... should raise exception?
  7977. return "Could not retrieve object: %s" % obj_name
  7978. try:
  7979. box = self.collection.get_by_name(str(box_name))
  7980. except:
  7981. # TODO: The return behavior has not been established... should raise exception?
  7982. return "Could not retrieve object: %s" % box_name
  7983. if box is None:
  7984. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  7985. (_("No object Box. Using instead"), obj))
  7986. box = obj
  7987. def make_negative_film():
  7988. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7989. # Determine bounding area for svg export
  7990. bounds = box.bounds()
  7991. size = box.size()
  7992. uom = obj.units.lower()
  7993. # Convert everything to strings for use in the xml doc
  7994. svgwidth = str(size[0] + (2 * boundary))
  7995. svgheight = str(size[1] + (2 * boundary))
  7996. minx = str(bounds[0] - boundary)
  7997. miny = str(bounds[1] + boundary + size[1])
  7998. miny_rect = str(bounds[1] - boundary)
  7999. # Add a SVG Header and footer to the svg output from shapely
  8000. # The transform flips the Y Axis so that everything renders
  8001. # properly within svg apps such as inkscape
  8002. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8003. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8004. svg_header += 'width="' + svgwidth + uom + '" '
  8005. svg_header += 'height="' + svgheight + uom + '" '
  8006. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  8007. svg_header += '>'
  8008. svg_header += '<g transform="scale(1,-1)">'
  8009. svg_footer = '</g> </svg>'
  8010. # Change the attributes of the exported SVG
  8011. # We don't need stroke-width - wrong, we do when we have lines with certain width
  8012. # We set opacity to maximum
  8013. # We set the color to WHITE
  8014. root = ET.fromstring(exported_svg)
  8015. for child in root:
  8016. child.set('fill', '#FFFFFF')
  8017. child.set('opacity', '1.0')
  8018. child.set('stroke', '#FFFFFF')
  8019. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  8020. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  8021. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  8022. first_svg_elem_tag = 'rect'
  8023. first_svg_elem_attribs = {
  8024. 'x': minx,
  8025. 'y': miny_rect,
  8026. 'width': svgwidth,
  8027. 'height': svgheight,
  8028. 'id': 'neg_rect',
  8029. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  8030. }
  8031. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  8032. exported_svg = ET.tostring(root)
  8033. svg_elem = svg_header + str(exported_svg) + svg_footer
  8034. # Parse the xml through a xml parser just to add line feeds
  8035. # and to make it look more pretty for the output
  8036. doc = parse_xml_string(svg_elem)
  8037. try:
  8038. with open(filename, 'w') as fp:
  8039. fp.write(doc.toprettyxml())
  8040. except PermissionError:
  8041. self.inform.emit('[WARNING] %s' %
  8042. _("Permission denied, saving not possible.\n"
  8043. "Most likely another app is holding the file open and not accessible."))
  8044. return 'fail'
  8045. if self.defaults["global_open_style"] is False:
  8046. self.file_opened.emit("SVG", filename)
  8047. self.file_saved.emit("SVG", filename)
  8048. self.inform.emit('[success] %s: %s' %
  8049. (_("SVG file exported to"), filename))
  8050. if use_thread is True:
  8051. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  8052. def job_thread_film(app_obj):
  8053. try:
  8054. make_negative_film()
  8055. except Exception as e:
  8056. proc.done()
  8057. return
  8058. proc.done()
  8059. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  8060. else:
  8061. make_negative_film()
  8062. def export_svg_positive(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  8063. """
  8064. Exports a Geometry Object to an SVG file in positive black.
  8065. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8066. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  8067. :param filename: Path to the SVG file to save to.
  8068. :param scale_factor: factor by which to change/scale the thickness of the features
  8069. :param use_thread: if to be run in a separate thread; boolean
  8070. :return:
  8071. """
  8072. self.report_usage("export_svg_positive()")
  8073. if filename is None:
  8074. filename = self.defaults["global_last_save_folder"]
  8075. self.log.debug("export_svg() black")
  8076. try:
  8077. obj = self.collection.get_by_name(str(obj_name))
  8078. except:
  8079. # TODO: The return behavior has not been established... should raise exception?
  8080. return "Could not retrieve object: %s" % obj_name
  8081. try:
  8082. box = self.collection.get_by_name(str(box_name))
  8083. except:
  8084. # TODO: The return behavior has not been established... should raise exception?
  8085. return "Could not retrieve object: %s" % box_name
  8086. if box is None:
  8087. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  8088. (_("No object Box. Using instead"), obj))
  8089. box = obj
  8090. def make_positive_film():
  8091. exported_svg = obj.export_svg(scale_factor=scale_factor)
  8092. self.progress.emit(40)
  8093. # Change the attributes of the exported SVG
  8094. # We don't need stroke-width
  8095. # We set opacity to maximum
  8096. # We set the colour to WHITE
  8097. root = ET.fromstring(exported_svg)
  8098. for child in root:
  8099. child.set('fill', str(self.defaults['tools_film_color']))
  8100. child.set('opacity', '1.0')
  8101. child.set('stroke', str(self.defaults['tools_film_color']))
  8102. exported_svg = ET.tostring(root)
  8103. # Determine bounding area for svg export
  8104. bounds = box.bounds()
  8105. size = box.size()
  8106. # This contain the measure units
  8107. uom = obj.units.lower()
  8108. # Define a boundary around SVG of about 1.0mm (~39mils)
  8109. if uom in "mm":
  8110. boundary = 1.0
  8111. else:
  8112. boundary = 0.0393701
  8113. self.progress.emit(80)
  8114. # Convert everything to strings for use in the xml doc
  8115. svgwidth = str(size[0] + (2 * boundary))
  8116. svgheight = str(size[1] + (2 * boundary))
  8117. minx = str(bounds[0] - boundary)
  8118. miny = str(bounds[1] + boundary + size[1])
  8119. self.log.debug(minx)
  8120. self.log.debug(miny)
  8121. # Add a SVG Header and footer to the svg output from shapely
  8122. # The transform flips the Y Axis so that everything renders
  8123. # properly within svg apps such as inkscape
  8124. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8125. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8126. svg_header += 'width="' + svgwidth + uom + '" '
  8127. svg_header += 'height="' + svgheight + uom + '" '
  8128. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  8129. svg_header += '>'
  8130. svg_header += '<g transform="scale(1,-1)">'
  8131. svg_footer = '</g> </svg>'
  8132. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  8133. self.progress.emit(90)
  8134. # Parse the xml through a xml parser just to add line feeds
  8135. # and to make it look more pretty for the output
  8136. doc = parse_xml_string(svg_elem)
  8137. try:
  8138. with open(filename, 'w') as fp:
  8139. fp.write(doc.toprettyxml())
  8140. except PermissionError:
  8141. self.inform.emit('[WARNING] %s' %
  8142. _("Permission denied, saving not possible.\n"
  8143. "Most likely another app is holding the file open and not accessible."))
  8144. return 'fail'
  8145. self.progress.emit(100)
  8146. if self.defaults["global_open_style"] is False:
  8147. self.file_opened.emit("SVG", filename)
  8148. self.file_saved.emit("SVG", filename)
  8149. self.inform.emit('[success] %s: %s' %
  8150. (_("SVG file exported to"), filename))
  8151. if use_thread is True:
  8152. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  8153. def job_thread_film(app_obj):
  8154. try:
  8155. make_positive_film()
  8156. except Exception as e:
  8157. proc.done()
  8158. return
  8159. proc.done()
  8160. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  8161. else:
  8162. make_positive_film()
  8163. def save_source_file(self, obj_name, filename, use_thread=True):
  8164. """
  8165. Exports a FlatCAM Object to an Gerber/Excellon file.
  8166. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8167. :param filename: Path to the Gerber file to save to.
  8168. :param use_thread: if to be run in a separate thread
  8169. :return:
  8170. """
  8171. self.report_usage("save source file()")
  8172. if filename is None:
  8173. filename = self.defaults["global_last_save_folder"]
  8174. self.log.debug("save source file()")
  8175. obj = self.collection.get_by_name(obj_name)
  8176. file_string = StringIO(obj.source_file)
  8177. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8178. try:
  8179. with open(filename, 'w') as file:
  8180. file.writelines('G04*\n')
  8181. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8182. (obj.kind.upper(), str(self.version), str(self.version_date)))
  8183. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8184. file.writelines('G04 Created on : %s*\n' % time_string)
  8185. for line in file_string:
  8186. file.writelines(line)
  8187. except PermissionError:
  8188. self.inform.emit('[WARNING] %s' %
  8189. _("Permission denied, saving not possible.\n"
  8190. "Most likely another app is holding the file open and not accessible."))
  8191. return 'fail'
  8192. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  8193. """
  8194. Exports a Excellon Object to an Excellon file.
  8195. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  8196. :param filename: Path to the Excellon file to save to.
  8197. :param use_thread: if to be run in a separate thread
  8198. :return:
  8199. """
  8200. self.report_usage("export_excellon()")
  8201. if filename is None:
  8202. filename = self.defaults["global_last_save_folder"]
  8203. self.log.debug("export_excellon()")
  8204. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  8205. self.defaults["excellon_exp_decimals"]
  8206. )
  8207. units = ''
  8208. if local_use is None:
  8209. try:
  8210. obj = self.collection.get_by_name(str(obj_name))
  8211. except:
  8212. # TODO: The return behavior has not been established... should raise exception?
  8213. return "Could not retrieve object: %s" % obj_name
  8214. else:
  8215. obj = local_use
  8216. # updated units
  8217. eunits = self.defaults["excellon_exp_units"]
  8218. ewhole = self.defaults["excellon_exp_integer"]
  8219. efract = self.defaults["excellon_exp_decimals"]
  8220. ezeros = self.defaults["excellon_exp_zeros"]
  8221. eformat = self.defaults["excellon_exp_format"]
  8222. slot_type = self.defaults["excellon_exp_slot_type"]
  8223. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8224. if fc_units == 'MM':
  8225. factor = 1 if eunits == 'METRIC' else 0.03937
  8226. else:
  8227. factor = 25.4 if eunits == 'METRIC' else 1
  8228. def make_excellon():
  8229. try:
  8230. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8231. header = 'M48\n'
  8232. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  8233. (str(self.version), str(self.version_date))
  8234. header += ';Filename: %s' % str(obj_name) + '\n'
  8235. header += ';Created on : %s' % time_str + '\n'
  8236. if eformat == 'dec':
  8237. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  8238. header += eunits + '\n'
  8239. for tool in obj.tools:
  8240. if eunits == 'METRIC':
  8241. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8242. tool=str(tool),
  8243. dec=2)
  8244. else:
  8245. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8246. tool=str(tool),
  8247. dec=4)
  8248. else:
  8249. if ezeros == 'LZ':
  8250. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8251. form='ndec', e_zeros='LZ', factor=factor,
  8252. slot_type=slot_type)
  8253. header += '%s,%s\n' % (eunits, 'LZ')
  8254. header += format_exc
  8255. for tool in obj.tools:
  8256. if eunits == 'METRIC':
  8257. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8258. tool=str(tool),
  8259. dec=2)
  8260. else:
  8261. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8262. tool=str(tool),
  8263. dec=4)
  8264. else:
  8265. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8266. form='ndec', e_zeros='TZ', factor=factor,
  8267. slot_type=slot_type)
  8268. header += '%s,%s\n' % (eunits, 'TZ')
  8269. header += format_exc
  8270. for tool in obj.tools:
  8271. if eunits == 'METRIC':
  8272. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8273. tool=str(tool),
  8274. dec=2)
  8275. else:
  8276. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8277. tool=str(tool),
  8278. dec=4)
  8279. header += '%\n'
  8280. footer = 'M30\n'
  8281. exported_excellon = header
  8282. exported_excellon += excellon_code
  8283. exported_excellon += footer
  8284. if local_use is None:
  8285. try:
  8286. with open(filename, 'w') as fp:
  8287. fp.write(exported_excellon)
  8288. except PermissionError:
  8289. self.inform.emit('[WARNING] %s' %
  8290. _("Permission denied, saving not possible.\n"
  8291. "Most likely another app is holding the file open and not accessible."))
  8292. return 'fail'
  8293. if self.defaults["global_open_style"] is False:
  8294. self.file_opened.emit("Excellon", filename)
  8295. self.file_saved.emit("Excellon", filename)
  8296. self.inform.emit('[success] %s: %s' %
  8297. (_("Excellon file exported to"), filename))
  8298. else:
  8299. return exported_excellon
  8300. except Exception as e:
  8301. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  8302. return 'fail'
  8303. if use_thread is True:
  8304. with self.proc_container.new(_("Exporting Excellon")) as proc:
  8305. def job_thread_exc(app_obj):
  8306. ret = make_excellon()
  8307. if ret == 'fail':
  8308. self.inform.emit('[ERROR_NOTCL] %s' %
  8309. _('Could not export Excellon file.'))
  8310. return
  8311. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8312. else:
  8313. ret = make_excellon()
  8314. if ret == 'fail':
  8315. self.inform.emit('[ERROR_NOTCL] %s' %
  8316. _('Could not export Excellon file.'))
  8317. return 'fail'
  8318. if local_use is not None:
  8319. return ret
  8320. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  8321. """
  8322. Exports a Gerber Object to an Gerber file.
  8323. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  8324. :param filename: Path to the Gerber file to save to.
  8325. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8326. When not None, the value will be the actual Gerber object for which to create the Gerber code
  8327. :param use_thread: if to be run in a separate thread
  8328. :return:
  8329. """
  8330. self.report_usage("export_gerber()")
  8331. if filename is None:
  8332. filename = self.defaults["global_last_save_folder"]
  8333. self.log.debug("export_gerber()")
  8334. if local_use is None:
  8335. try:
  8336. obj = self.collection.get_by_name(str(obj_name))
  8337. except:
  8338. # TODO: The return behavior has not been established... should raise exception?
  8339. return "Could not retrieve object: %s" % obj_name
  8340. else:
  8341. obj = local_use
  8342. # updated units
  8343. gunits = self.defaults["gerber_exp_units"]
  8344. gwhole = self.defaults["gerber_exp_integer"]
  8345. gfract = self.defaults["gerber_exp_decimals"]
  8346. gzeros = self.defaults["gerber_exp_zeros"]
  8347. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8348. if fc_units == 'MM':
  8349. factor = 1 if gunits == 'MM' else 0.03937
  8350. else:
  8351. factor = 25.4 if gunits == 'MM' else 1
  8352. def make_gerber():
  8353. try:
  8354. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8355. header = 'G04*\n'
  8356. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  8357. (str(self.version), str(self.version_date))
  8358. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  8359. header += 'G04 Created on : %s*' % time_str + '\n'
  8360. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  8361. header += "%MO{units}*%\n".format(units=gunits)
  8362. for apid in obj.apertures:
  8363. if obj.apertures[apid]['type'] == 'C':
  8364. header += "%ADD{apid}{type},{size}*%\n".format(
  8365. apid=str(apid),
  8366. type='C',
  8367. size=(factor * obj.apertures[apid]['size'])
  8368. )
  8369. elif obj.apertures[apid]['type'] == 'R':
  8370. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8371. apid=str(apid),
  8372. type='R',
  8373. width=(factor * obj.apertures[apid]['width']),
  8374. height=(factor * obj.apertures[apid]['height'])
  8375. )
  8376. elif obj.apertures[apid]['type'] == 'O':
  8377. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8378. apid=str(apid),
  8379. type='O',
  8380. width=(factor * obj.apertures[apid]['width']),
  8381. height=(factor * obj.apertures[apid]['height'])
  8382. )
  8383. header += '\n'
  8384. # obsolete units but some software may need it
  8385. if gunits == 'IN':
  8386. header += 'G70*\n'
  8387. else:
  8388. header += 'G71*\n'
  8389. # Absolute Mode
  8390. header += 'G90*\n'
  8391. header += 'G01*\n'
  8392. # positive polarity
  8393. header += '%LPD*%\n'
  8394. footer = 'M02*\n'
  8395. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8396. exported_gerber = header
  8397. exported_gerber += gerber_code
  8398. exported_gerber += footer
  8399. if local_use is None:
  8400. try:
  8401. with open(filename, 'w') as fp:
  8402. fp.write(exported_gerber)
  8403. except PermissionError:
  8404. self.inform.emit('[WARNING] %s' %
  8405. _("Permission denied, saving not possible.\n"
  8406. "Most likely another app is holding the file open and not accessible."))
  8407. return 'fail'
  8408. if self.defaults["global_open_style"] is False:
  8409. self.file_opened.emit("Gerber", filename)
  8410. self.file_saved.emit("Gerber", filename)
  8411. self.inform.emit('[success] %s: %s' %
  8412. (_("Gerber file exported to"), filename))
  8413. else:
  8414. return exported_gerber
  8415. except Exception as e:
  8416. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8417. return 'fail'
  8418. if use_thread is True:
  8419. with self.proc_container.new(_("Exporting Gerber")) as proc:
  8420. def job_thread_grb(app_obj):
  8421. ret = make_gerber()
  8422. if ret == 'fail':
  8423. self.inform.emit('[ERROR_NOTCL] %s' %
  8424. _('Could not export Gerber file.'))
  8425. return
  8426. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8427. else:
  8428. ret = make_gerber()
  8429. if ret == 'fail':
  8430. self.inform.emit('[ERROR_NOTCL] %s' %
  8431. _('Could not export Gerber file.'))
  8432. return 'fail'
  8433. if local_use is not None:
  8434. return ret
  8435. def export_dxf(self, obj_name, filename, use_thread=True):
  8436. """
  8437. Exports a Geometry Object to an DXF file.
  8438. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8439. :param filename: Path to the DXF file to save to.
  8440. :param use_thread: if to be run in a separate thread
  8441. :return:
  8442. """
  8443. self.report_usage("export_dxf()")
  8444. if filename is None:
  8445. filename = self.defaults["global_last_save_folder"]
  8446. self.log.debug("export_dxf()")
  8447. format_exc = ''
  8448. units = ''
  8449. try:
  8450. obj = self.collection.get_by_name(str(obj_name))
  8451. except:
  8452. # TODO: The return behavior has not been established... should raise exception?
  8453. return "Could not retrieve object: %s" % obj_name
  8454. # updated units
  8455. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8456. if units == 'IN' or units == 'INCH':
  8457. units = 'INCH'
  8458. elif units == 'MM' or units == 'METIRC':
  8459. units ='METRIC'
  8460. def make_dxf():
  8461. try:
  8462. dxf_code = obj.export_dxf()
  8463. dxf_code.saveas(filename)
  8464. if self.defaults["global_open_style"] is False:
  8465. self.file_opened.emit("DXF", filename)
  8466. self.file_saved.emit("DXF", filename)
  8467. self.inform.emit('[success] %s: %s' %
  8468. (_("DXF file exported to"), filename))
  8469. except:
  8470. return 'fail'
  8471. if use_thread is True:
  8472. with self.proc_container.new(_("Exporting DXF")) as proc:
  8473. def job_thread_exc(app_obj):
  8474. ret = make_dxf()
  8475. if ret == 'fail':
  8476. app_obj.inform.emit('[WARNING_NOTCL] %s' %
  8477. _('Could not export DXF file.'))
  8478. return
  8479. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8480. else:
  8481. ret = make_dxf()
  8482. if ret == 'fail':
  8483. self.inform.emit('[WARNING_NOTCL] %s' %
  8484. _('Could not export DXF file.'))
  8485. return
  8486. def import_svg(self, filename, geo_type='geometry', outname=None):
  8487. """
  8488. Adds a new Geometry Object to the projects and populates
  8489. it with shapes extracted from the SVG file.
  8490. :param filename: Path to the SVG file.
  8491. :param outname:
  8492. :return:
  8493. """
  8494. self.report_usage("import_svg()")
  8495. obj_type = ""
  8496. if geo_type is None or geo_type == "geometry":
  8497. obj_type = "geometry"
  8498. elif geo_type == "gerber":
  8499. obj_type = geo_type
  8500. else:
  8501. self.inform.emit('[ERROR_NOTCL] %s' %
  8502. _("Not supported type is picked as parameter. "
  8503. "Only Geometry and Gerber are supported"))
  8504. return
  8505. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8506. def obj_init(geo_obj, app_obj):
  8507. geo_obj.import_svg(filename, obj_type, units=units)
  8508. geo_obj.multigeo = False
  8509. with self.proc_container.new(_("Importing SVG")) as proc:
  8510. # Object name
  8511. name = outname or filename.split('/')[-1].split('\\')[-1]
  8512. self.new_object(obj_type, name, obj_init, autoselected=False)
  8513. self.progress.emit(20)
  8514. # Register recent file
  8515. self.file_opened.emit("svg", filename)
  8516. # GUI feedback
  8517. self.inform.emit('[success] %s: %s' %
  8518. (_("Opened"), filename))
  8519. self.progress.emit(100)
  8520. def import_dxf(self, filename, geo_type='geometry', outname=None):
  8521. """
  8522. Adds a new Geometry Object to the projects and populates
  8523. it with shapes extracted from the DXF file.
  8524. :param filename: Path to the DXF file.
  8525. :param outname:
  8526. :type putname: str
  8527. :return:
  8528. """
  8529. self.report_usage("import_dxf()")
  8530. obj_type = ""
  8531. if geo_type is None or geo_type == "geometry":
  8532. obj_type = "geometry"
  8533. elif geo_type == "gerber":
  8534. obj_type = geo_type
  8535. else:
  8536. self.inform.emit('[ERROR_NOTCL] %s' %
  8537. _("Not supported type is picked as parameter. "
  8538. "Only Geometry and Gerber are supported"))
  8539. return
  8540. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8541. def obj_init(geo_obj, app_obj):
  8542. geo_obj.import_dxf(filename, obj_type, units=units)
  8543. geo_obj.multigeo = False
  8544. with self.proc_container.new(_("Importing DXF")) as proc:
  8545. # Object name
  8546. name = outname or filename.split('/')[-1].split('\\')[-1]
  8547. self.new_object(obj_type, name, obj_init, autoselected=False)
  8548. self.progress.emit(20)
  8549. # Register recent file
  8550. self.file_opened.emit("dxf", filename)
  8551. # GUI feedback
  8552. self.inform.emit('[success] %s: %s' %
  8553. (_("Opened"), filename))
  8554. self.progress.emit(100)
  8555. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  8556. """
  8557. Adds a new Geometry Object to the projects and populates
  8558. it with shapes extracted from the SVG file.
  8559. :param filename: Path to the SVG file.
  8560. :param o_type: type of FlatCAM objeect
  8561. :param dpi: dot per inch
  8562. :param mode: black or color
  8563. :param mask: dictate the level of detail
  8564. :param outname: name for the resulting file
  8565. :return:
  8566. """
  8567. self.report_usage("import_image()")
  8568. if o_type is None or o_type == "geometry":
  8569. obj_type = "geometry"
  8570. elif o_type == "gerber":
  8571. obj_type = o_type
  8572. else:
  8573. self.inform.emit('[ERROR_NOTCL] %s' %
  8574. _("Not supported type is picked as parameter. "
  8575. "Only Geometry and Gerber are supported"))
  8576. return
  8577. def obj_init(geo_obj, app_obj):
  8578. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  8579. geo_obj.multigeo = False
  8580. with self.proc_container.new(_("Importing Image")) as proc:
  8581. # Object name
  8582. name = outname or filename.split('/')[-1].split('\\')[-1]
  8583. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  8584. self.new_object(obj_type, name, obj_init)
  8585. self.progress.emit(20)
  8586. # Register recent file
  8587. self.file_opened.emit("image", filename)
  8588. # GUI feedback
  8589. self.inform.emit('[success] %s: %s' %
  8590. (_("Opened"), filename))
  8591. self.progress.emit(100)
  8592. def open_gerber(self, filename, outname=None):
  8593. """
  8594. Opens a Gerber file, parses it and creates a new object for
  8595. it in the program. Thread-safe.
  8596. :param outname: Name of the resulting object. None causes the
  8597. name to be that of the file.
  8598. :param filename: Gerber file filename
  8599. :type filename: str
  8600. :param follow: If true, the parser will not create polygons, just lines
  8601. following the gerber path.
  8602. :type follow: bool
  8603. :return: None
  8604. """
  8605. # How the object should be initialized
  8606. def obj_init(gerber_obj, app_obj):
  8607. assert isinstance(gerber_obj, FlatCAMGerber), \
  8608. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  8609. # Opening the file happens here
  8610. self.progress.emit(30)
  8611. try:
  8612. gerber_obj.parse_file(filename)
  8613. except IOError:
  8614. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8615. (_("Failed to open file"), filename))
  8616. app_obj.progress.emit(0)
  8617. return "fail"
  8618. except ParseError as err:
  8619. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' %
  8620. (_("Failed to parse file"), filename, str(err)))
  8621. app_obj.progress.emit(0)
  8622. self.log.error(str(err))
  8623. return "fail"
  8624. except Exception as e:
  8625. log.debug("App.open_gerber() --> %s" % str(e))
  8626. msg = '[ERROR] %s' % \
  8627. _("An internal error has occurred. See shell.\n")
  8628. msg += traceback.format_exc()
  8629. app_obj.inform.emit(msg)
  8630. return "fail"
  8631. if gerber_obj.is_empty():
  8632. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  8633. # self.collection.set_active(gerber_obj.options["name"])
  8634. # self.collection.delete_active()
  8635. self.inform.emit('[ERROR_NOTCL] %s' %
  8636. _("Object is not Gerber file or empty. Aborting object creation."))
  8637. return "fail"
  8638. # Further parsing
  8639. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  8640. App.log.debug("open_gerber()")
  8641. with self.proc_container.new(_("Opening Gerber")) as proc:
  8642. self.progress.emit(10)
  8643. # Object name
  8644. name = outname or filename.split('/')[-1].split('\\')[-1]
  8645. # # ## Object creation # ##
  8646. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  8647. if ret == 'fail':
  8648. self.inform.emit('[ERROR_NOTCL]%s' %
  8649. _(' Open Gerber failed. Probable not a Gerber file.'))
  8650. return
  8651. # Register recent file
  8652. self.file_opened.emit("gerber", filename)
  8653. self.progress.emit(100)
  8654. # GUI feedback
  8655. self.inform.emit('[success] %s: %s' %
  8656. (_("Opened"), filename))
  8657. def open_excellon(self, filename, outname=None, plot=True):
  8658. """
  8659. Opens an Excellon file, parses it and creates a new object for
  8660. it in the program. Thread-safe.
  8661. :param outname: Name of the resulting object. None causes the
  8662. name to be that of the file.
  8663. :param filename: Excellon file filename
  8664. :type filename: str
  8665. :return: None
  8666. """
  8667. App.log.debug("open_excellon()")
  8668. # How the object should be initialized
  8669. def obj_init(excellon_obj, app_obj):
  8670. # self.progress.emit(20)
  8671. try:
  8672. ret = excellon_obj.parse_file(filename=filename)
  8673. if ret == "fail":
  8674. log.debug("Excellon parsing failed.")
  8675. self.inform.emit('[ERROR_NOTCL] %s' %
  8676. _("This is not Excellon file."))
  8677. return "fail"
  8678. except IOError:
  8679. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8680. (_("Cannot open file"), filename))
  8681. log.debug("Could not open Excellon object.")
  8682. self.progress.emit(0) # TODO: self and app_bjj mixed
  8683. return "fail"
  8684. except:
  8685. msg = '[ERROR_NOTCL] %s' % \
  8686. _("An internal error has occurred. See shell.\n")
  8687. msg += traceback.format_exc()
  8688. app_obj.inform.emit(msg)
  8689. return "fail"
  8690. ret = excellon_obj.create_geometry()
  8691. if ret == 'fail':
  8692. log.debug("Could not create geometry for Excellon object.")
  8693. return "fail"
  8694. for tool in excellon_obj.tools:
  8695. if excellon_obj.tools[tool]['solid_geometry']:
  8696. return
  8697. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8698. (_("No geometry found in file"), filename))
  8699. return "fail"
  8700. with self.proc_container.new(_("Opening Excellon.")):
  8701. # Object name
  8702. name = outname or filename.split('/')[-1].split('\\')[-1]
  8703. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8704. if ret_val == 'fail':
  8705. self.inform.emit('[ERROR_NOTCL] %s' %
  8706. _('Open Excellon file failed. Probable not an Excellon file.'))
  8707. return
  8708. # Register recent file
  8709. self.file_opened.emit("excellon", filename)
  8710. # GUI feedback
  8711. self.inform.emit('[success] %s: %s' %
  8712. (_("Opened"), filename))
  8713. def open_gcode(self, filename, outname=None, plot=True):
  8714. """
  8715. Opens a G-gcode file, parses it and creates a new object for
  8716. it in the program. Thread-safe.
  8717. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8718. :param filename: G-code file filename
  8719. :type filename: str
  8720. :return: None
  8721. """
  8722. App.log.debug("open_gcode()")
  8723. # How the object should be initialized
  8724. def obj_init(job_obj, app_obj_):
  8725. """
  8726. :param job_obj: the resulting object
  8727. :type app_obj_: App
  8728. """
  8729. assert isinstance(app_obj_, App), \
  8730. "Initializer expected App, got %s" % type(app_obj_)
  8731. self.progress.emit(10)
  8732. try:
  8733. f = open(filename)
  8734. gcode = f.read()
  8735. f.close()
  8736. except IOError:
  8737. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  8738. (_("Failed to open"), filename))
  8739. self.progress.emit(0)
  8740. return "fail"
  8741. job_obj.gcode = gcode
  8742. self.progress.emit(20)
  8743. ret = job_obj.gcode_parse()
  8744. if ret == "fail":
  8745. self.inform.emit('[ERROR_NOTCL] %s' %
  8746. _("This is not GCODE"))
  8747. return "fail"
  8748. self.progress.emit(60)
  8749. job_obj.create_geometry()
  8750. with self.proc_container.new(_("Opening G-Code.")):
  8751. # Object name
  8752. name = outname or filename.split('/')[-1].split('\\')[-1]
  8753. # New object creation and file processing
  8754. ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8755. if ret == 'fail':
  8756. self.inform.emit('[ERROR_NOTCL] %s' %
  8757. _("Failed to create CNCJob Object. Probable not a GCode file.\n "
  8758. "Attempting to create a FlatCAM CNCJob Object from "
  8759. "G-Code file failed during processing"))
  8760. return "fail"
  8761. # Register recent file
  8762. self.file_opened.emit("cncjob", filename)
  8763. # GUI feedback
  8764. self.inform.emit('[success] %s: %s' %
  8765. (_("Opened"), filename))
  8766. self.progress.emit(100)
  8767. def open_config_file(self, filename, run_from_arg=None):
  8768. """
  8769. Loads a config file from the specified file.
  8770. :param filename: Name of the file from which to load.
  8771. :type filename: str
  8772. :return: None
  8773. """
  8774. App.log.debug("Opening config file: " + filename)
  8775. if run_from_arg:
  8776. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8777. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8778. _("Opening FlatCAM Config file.")),
  8779. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8780. color=QtGui.QColor("gray"))
  8781. # add the tab if it was closed
  8782. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  8783. # first clear previous text in text editor (if any)
  8784. self.ui.code_editor.clear()
  8785. # Switch plot_area to CNCJob tab
  8786. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  8787. try:
  8788. if filename:
  8789. f = QtCore.QFile(filename)
  8790. if f.open(QtCore.QIODevice.ReadOnly):
  8791. stream = QtCore.QTextStream(f)
  8792. gcode_edited = stream.readAll()
  8793. self.ui.code_editor.setPlainText(gcode_edited)
  8794. f.close()
  8795. except IOError:
  8796. App.log.error("Failed to open config file: %s" % filename)
  8797. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8798. (_("Failed to open config file"), filename))
  8799. return
  8800. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  8801. """
  8802. Loads a project from the specified file.
  8803. 1) Loads and parses file
  8804. 2) Registers the file as recently opened.
  8805. 3) Calls on_file_new()
  8806. 4) Updates options
  8807. 5) Calls new_object() with the object's from_dict() as init method.
  8808. 6) Calls plot_all() if plot=True
  8809. :param filename: Name of the file from which to load.
  8810. :type filename: str
  8811. :param run_from_arg: True if run for arguments
  8812. :param plot: If True plot all objects in the project
  8813. :param cli: run from command line
  8814. :return: None
  8815. """
  8816. App.log.debug("Opening project: " + filename)
  8817. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8818. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8819. if cli is None:
  8820. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8821. if run_from_arg:
  8822. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8823. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8824. _("Opening FlatCAM Project file.")),
  8825. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8826. color=QtGui.QColor("gray"))
  8827. # Open and parse an uncompressed Project file
  8828. try:
  8829. f = open(filename, 'r')
  8830. except IOError:
  8831. App.log.error("Failed to open project file: %s" % filename)
  8832. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8833. (_("Failed to open project file"), filename))
  8834. return
  8835. try:
  8836. d = json.load(f, object_hook=dict2obj)
  8837. except Exception as e:
  8838. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8839. (filename, str(e)))
  8840. f.close()
  8841. # Open and parse a compressed Project file
  8842. try:
  8843. with lzma.open(filename) as f:
  8844. file_content = f.read().decode('utf-8')
  8845. d = json.loads(file_content, object_hook=dict2obj)
  8846. except Exception as e:
  8847. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8848. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8849. (_("Failed to open project file"), filename))
  8850. return
  8851. # Clear the current project
  8852. # # NOT THREAD SAFE # ##
  8853. if run_from_arg is True:
  8854. pass
  8855. elif cli is True:
  8856. self.delete_selection_shape()
  8857. else:
  8858. self.on_file_new()
  8859. # Project options
  8860. self.options.update(d['options'])
  8861. self.project_filename = filename
  8862. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8863. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8864. if cli is None:
  8865. self.set_screen_units(self.options["units"])
  8866. # Re create objects
  8867. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8868. for obj in d['objs']:
  8869. def obj_init(obj_inst, app_inst):
  8870. obj_inst.from_dict(obj)
  8871. App.log.debug("Recreating from opened project an %s object: %s" %
  8872. (obj['kind'].capitalize(), obj['options']['name']))
  8873. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8874. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8875. if cli is None:
  8876. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8877. obj['kind'].upper(),
  8878. obj['options']['name']
  8879. )
  8880. )
  8881. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  8882. self.inform.emit('[success] %s: %s' %
  8883. (_("Project loaded from"), filename))
  8884. self.should_we_save = False
  8885. self.file_opened.emit("project", filename)
  8886. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8887. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8888. if cli is None:
  8889. self.set_ui_title(name=self.project_filename)
  8890. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8891. def propagate_defaults(self, silent=False):
  8892. """
  8893. This method is used to set default values in classes. It's
  8894. an alternative to project options but allows the use
  8895. of values invisible to the user.
  8896. :return: None
  8897. """
  8898. if silent is False:
  8899. self.log.debug("propagate_defaults()")
  8900. # Which objects to update the given parameters.
  8901. routes = {
  8902. "global_zdownrate": CNCjob,
  8903. "excellon_zeros": Excellon,
  8904. "excellon_format_upper_in": Excellon,
  8905. "excellon_format_lower_in": Excellon,
  8906. "excellon_format_upper_mm": Excellon,
  8907. "excellon_format_lower_mm": Excellon,
  8908. "excellon_units": Excellon,
  8909. "gerber_use_buffer_for_union": Gerber,
  8910. "geometry_multidepth": Geometry
  8911. }
  8912. for param in routes:
  8913. if param in routes[param].defaults:
  8914. try:
  8915. routes[param].defaults[param] = self.defaults[param]
  8916. if silent is False:
  8917. self.log.debug(" " + param + " OK")
  8918. except KeyError:
  8919. if silent is False:
  8920. self.log.debug(" ERROR: " + param + " not in defaults.")
  8921. else:
  8922. # Try extracting the name:
  8923. # classname_param here is param in the object
  8924. if param.find(routes[param].__name__.lower() + "_") == 0:
  8925. p = param[len(routes[param].__name__) + 1:]
  8926. if p in routes[param].defaults:
  8927. routes[param].defaults[p] = self.defaults[param]
  8928. if silent is False:
  8929. self.log.debug(" " + param + " OK!")
  8930. def plot_all(self, zoom=True):
  8931. """
  8932. Re-generates all plots from all objects.
  8933. :return: None
  8934. """
  8935. self.log.debug("Plot_all()")
  8936. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  8937. for obj in self.collection.get_list():
  8938. def worker_task(obj):
  8939. with self.proc_container.new("Plotting"):
  8940. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8941. if zoom:
  8942. self.object_plotted.emit(obj)
  8943. # Send to worker
  8944. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  8945. def register_folder(self, filename):
  8946. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8947. def register_save_folder(self, filename):
  8948. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8949. def set_progress_bar(self, percentage, text=""):
  8950. self.ui.progress_bar.setValue(int(percentage))
  8951. def setup_shell(self):
  8952. """
  8953. Creates shell functions. Runs once at startup.
  8954. :return: None
  8955. """
  8956. self.log.debug("setup_shell()")
  8957. def shelp(p=None):
  8958. if not p:
  8959. return _("Available commands:\n") + \
  8960. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  8961. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  8962. if p not in commands:
  8963. return "Unknown command: %s" % p
  8964. return commands[p]["help"]
  8965. # --- Migrated to new architecture ---
  8966. # def options(name):
  8967. # ops = self.collection.get_by_name(str(name)).options
  8968. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  8969. def h(*args):
  8970. """
  8971. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  8972. and standalone parameters into list.
  8973. """
  8974. kwa = {}
  8975. a = []
  8976. n = len(args)
  8977. name = None
  8978. for i in range(n):
  8979. match = re.search(r'^-([a-zA-Z].*)', args[i])
  8980. if match:
  8981. assert name is None
  8982. name = match.group(1)
  8983. continue
  8984. if name is None:
  8985. a.append(args[i])
  8986. else:
  8987. kwa[name] = args[i]
  8988. name = None
  8989. return a, kwa
  8990. @contextmanager
  8991. def wait_signal(signal, timeout=10000):
  8992. """
  8993. Block loop until signal emitted, timeout (ms) elapses
  8994. or unhandled exception happens in a thread.
  8995. :param timeout: time after which the loop is exited
  8996. :param signal: Signal to wait for.
  8997. """
  8998. loop = QtCore.QEventLoop()
  8999. # Normal termination
  9000. signal.connect(loop.quit)
  9001. # Termination by exception in thread
  9002. self.thread_exception.connect(loop.quit)
  9003. status = {'timed_out': False}
  9004. def report_quit():
  9005. status['timed_out'] = True
  9006. loop.quit()
  9007. yield
  9008. # Temporarily change how exceptions are managed.
  9009. oeh = sys.excepthook
  9010. ex = []
  9011. def except_hook(type_, value, traceback_):
  9012. ex.append(value)
  9013. oeh(type_, value, traceback_)
  9014. sys.excepthook = except_hook
  9015. # Terminate on timeout
  9016. if timeout is not None:
  9017. QtCore.QTimer.singleShot(timeout, report_quit)
  9018. # # ## Block ## ##
  9019. loop.exec_()
  9020. # Restore exception management
  9021. sys.excepthook = oeh
  9022. if ex:
  9023. self.raiseTclError(str(ex[0]))
  9024. if status['timed_out']:
  9025. raise Exception('Timed out!')
  9026. def make_docs():
  9027. output = ''
  9028. import collections
  9029. od = collections.OrderedDict(sorted(commands.items()))
  9030. for cmd_, val in od.items():
  9031. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  9032. t = val['help']
  9033. usage_i = t.find('>')
  9034. if usage_i < 0:
  9035. expl = t
  9036. output += expl + '\n\n'
  9037. continue
  9038. expl = t[:usage_i - 1]
  9039. output += expl + '\n\n'
  9040. end_usage_i = t[usage_i:].find('\n')
  9041. if end_usage_i < 0:
  9042. end_usage_i = len(t[usage_i:])
  9043. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  9044. else:
  9045. extras = t[usage_i+end_usage_i+1:]
  9046. parts = [s.strip() for s in extras.split('\n')]
  9047. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  9048. for p in parts:
  9049. output += ' ' + p + '\n\n'
  9050. return output
  9051. '''
  9052. Howto implement TCL shell commands:
  9053. All parameters passed to command should be possible to set as None and test it afterwards.
  9054. This is because we need to see error caused in tcl,
  9055. if None value as default parameter is not allowed TCL will return empty error.
  9056. Use:
  9057. def mycommand(name=None,...):
  9058. Test it like this:
  9059. if name is None:
  9060. self.raise_tcl_error('Argument name is missing.')
  9061. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  9062. otherwise we will miss it and processing will silently continue.
  9063. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  9064. which is catched in exec_command and displayed in TCL shell console with red background.
  9065. Error in console is displayed with TCL trace.
  9066. This behavior works only within main thread,
  9067. errors with promissed tasks can be catched and detected only with log.
  9068. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  9069. TCL shell.
  9070. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  9071. '''
  9072. commands = {
  9073. 'help': {
  9074. 'fcn': shelp,
  9075. 'help': _("Shows list of commands.")
  9076. },
  9077. }
  9078. # Import/overwrite tcl commands as objects of TclCommand descendants
  9079. # This modifies the variable 'commands'.
  9080. tclCommands.register_all_commands(self, commands)
  9081. # Add commands to the tcl interpreter
  9082. for cmd in commands:
  9083. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  9084. # Make the tcl puts function return instead of print to stdout
  9085. self.tcl.eval('''
  9086. rename puts original_puts
  9087. proc puts {args} {
  9088. if {[llength $args] == 1} {
  9089. return "[lindex $args 0]"
  9090. } else {
  9091. eval original_puts $args
  9092. }
  9093. }
  9094. ''')
  9095. def setup_recent_items(self):
  9096. # TODO: Move this to constructor
  9097. icons = {
  9098. "gerber": "share/flatcam_icon16.png",
  9099. "excellon": "share/drill16.png",
  9100. 'geometry': "share/geometry16.png",
  9101. "cncjob": "share/cnc16.png",
  9102. "project": "share/project16.png",
  9103. "svg": "share/geometry16.png",
  9104. "dxf": "share/dxf16.png",
  9105. "pdf": "share/pdf32.png",
  9106. "image": "share/image16.png"
  9107. }
  9108. openers = {
  9109. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  9110. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  9111. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  9112. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  9113. 'project': self.open_project,
  9114. 'svg': self.import_svg,
  9115. 'dxf': self.import_dxf,
  9116. 'image': self.import_image,
  9117. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  9118. }
  9119. # Open recent file for files
  9120. try:
  9121. f = open(self.data_path + '/recent.json')
  9122. except IOError:
  9123. App.log.error("Failed to load recent item list.")
  9124. self.inform.emit('[ERROR_NOTCL] %s' %
  9125. _("Failed to load recent item list."))
  9126. return
  9127. try:
  9128. self.recent = json.load(f)
  9129. except json.scanner.JSONDecodeError:
  9130. App.log.error("Failed to parse recent item list.")
  9131. self.inform.emit('[ERROR_NOTCL] %s' %
  9132. _("Failed to parse recent item list."))
  9133. f.close()
  9134. return
  9135. f.close()
  9136. # Open recent file for projects
  9137. try:
  9138. fp = open(self.data_path + '/recent_projects.json')
  9139. except IOError:
  9140. App.log.error("Failed to load recent project item list.")
  9141. self.inform.emit('[ERROR_NOTCL] %s' %
  9142. _("Failed to load recent projects item list."))
  9143. return
  9144. try:
  9145. self.recent_projects = json.load(fp)
  9146. except json.scanner.JSONDecodeError:
  9147. App.log.error("Failed to parse recent project item list.")
  9148. self.inform.emit('[ERROR_NOTCL] %s' %
  9149. _("Failed to parse recent project item list."))
  9150. fp.close()
  9151. return
  9152. fp.close()
  9153. # Closure needed to create callbacks in a loop.
  9154. # Otherwise late binding occurs.
  9155. def make_callback(func, fname):
  9156. def opener():
  9157. func(fname)
  9158. return opener
  9159. def reset_recent_files():
  9160. # Reset menu
  9161. self.ui.recent.clear()
  9162. self.recent = []
  9163. try:
  9164. f = open(self.data_path + '/recent.json', 'w')
  9165. except IOError:
  9166. App.log.error("Failed to open recent items file for writing.")
  9167. return
  9168. json.dump(self.recent, f)
  9169. def reset_recent_projects():
  9170. # Reset menu
  9171. self.ui.recent_projects.clear()
  9172. self.recent_projects = []
  9173. try:
  9174. fp = open(self.data_path + '/recent_projects.json', 'w')
  9175. except IOError:
  9176. App.log.error("Failed to open recent projects items file for writing.")
  9177. return
  9178. json.dump(self.recent, fp)
  9179. # Reset menu
  9180. self.ui.recent.clear()
  9181. self.ui.recent_projects.clear()
  9182. # Create menu items for projects
  9183. for recent in self.recent_projects:
  9184. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9185. if recent['kind'] == 'project':
  9186. try:
  9187. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9188. # Attach callback
  9189. o = make_callback(openers[recent["kind"]], recent['filename'])
  9190. action.triggered.connect(o)
  9191. self.ui.recent_projects.addAction(action)
  9192. except KeyError:
  9193. App.log.error("Unsupported file type: %s" % recent["kind"])
  9194. # Last action in Recent Files menu is one that Clear the content
  9195. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  9196. clear_action_proj.triggered.connect(reset_recent_projects)
  9197. self.ui.recent_projects.addSeparator()
  9198. self.ui.recent_projects.addAction(clear_action_proj)
  9199. # Create menu items for files
  9200. for recent in self.recent:
  9201. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9202. if recent['kind'] != 'project':
  9203. try:
  9204. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9205. # Attach callback
  9206. o = make_callback(openers[recent["kind"]], recent['filename'])
  9207. action.triggered.connect(o)
  9208. self.ui.recent.addAction(action)
  9209. except KeyError:
  9210. App.log.error("Unsupported file type: %s" % recent["kind"])
  9211. # Last action in Recent Files menu is one that Clear the content
  9212. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  9213. clear_action.triggered.connect(reset_recent_files)
  9214. self.ui.recent.addSeparator()
  9215. self.ui.recent.addAction(clear_action)
  9216. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  9217. # self.ui.menufilerecent.set_submenu(recent_menu)
  9218. # recent_menu.show_all()
  9219. # self.ui.recent.show()
  9220. self.log.debug("Recent items list has been populated.")
  9221. def setup_component_editor(self):
  9222. # label = QtWidgets.QLabel("Choose an item from Project")
  9223. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  9224. sel_title = QtWidgets.QTextEdit(
  9225. _('<b>Shortcut Key List</b>'))
  9226. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  9227. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  9228. settings = QSettings("Open Source", "FlatCAM")
  9229. if settings.contains("notebook_font_size"):
  9230. fsize = settings.value('notebook_font_size', type=int)
  9231. else:
  9232. fsize = 12
  9233. tsize = fsize + int(fsize / 2)
  9234. # selected_text = (_('''
  9235. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  9236. #
  9237. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  9238. # The normal flow when working in FlatCAM is the following:</span></p>
  9239. #
  9240. # <ol>
  9241. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  9242. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  9243. # even dragging and dropping the files on the GUI.<br />
  9244. # <br />
  9245. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  9246. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  9247. # &nbsp;</li>
  9248. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  9249. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  9250. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  9251. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  9252. # <br />
  9253. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  9254. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  9255. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  9256. # it even if it was out of focus.<br />
  9257. # <br />
  9258. # You can change the parameters in this screen and the flow direction is like this:<br />
  9259. # <br />
  9260. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  9261. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  9262. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  9263. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  9264. # </ol>
  9265. #
  9266. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  9267. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  9268. # <strong>F3</strong>.</span></p>
  9269. #
  9270. # ''').format(fsize=fsize, tsize=tsize))
  9271. selected_text = '''
  9272. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  9273. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  9274. {s1}</span></p>
  9275. <ol>
  9276. <li><span style="font-size:{fsize}px">{s2}<br />
  9277. <br />
  9278. {s3}</span><br />
  9279. &nbsp;</li>
  9280. <li><span style="font-size:{fsize}px">{s4}<br />
  9281. &nbsp;</li>
  9282. <br />
  9283. <li><span style="font-size:{fsize}px">{s5}<br />
  9284. &nbsp;</li>
  9285. <br />
  9286. <li><span style="font-size:{fsize}px">{s6}<br />
  9287. <br />
  9288. {s7}</span></li>
  9289. </ol>
  9290. <p><span style="font-size:{fsize}px">{s8}</span></p>
  9291. '''.format(
  9292. title=_("Selected Tab - Choose an Item from Project Tab"),
  9293. subtitle=_("Details"),
  9294. s1=_("The normal flow when working in FlatCAM is the following:"),
  9295. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  9296. "using either the toolbars, key shortcuts or even dragging and dropping the "
  9297. "files on the GUI."),
  9298. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  9299. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  9300. "actions offered within the app."),
  9301. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  9302. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  9303. "SELECTED TAB will be updated with the object properties according to its kind: "
  9304. "Gerber, Excellon, Geometry or CNCJob object."),
  9305. s5=_("If the selection of the object is done on the canvas by single click instead, "
  9306. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  9307. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  9308. "the SELECTED TAB and populate it even if it was out of focus."),
  9309. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  9310. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  9311. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  9312. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  9313. "(again, done in SELECTED TAB) --> Save GCode."),
  9314. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  9315. "or through its own key shortcut: <b>F3</b>."),
  9316. tsize=tsize,
  9317. fsize=fsize
  9318. )
  9319. sel_title.setText(selected_text)
  9320. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  9321. self.ui.selected_scroll_area.setWidget(sel_title)
  9322. def setup_obj_classes(self):
  9323. """
  9324. Sets up application specifics on the FlatCAMObj class.
  9325. :return: None
  9326. """
  9327. FlatCAMObj.app = self
  9328. ObjectCollection.app = self
  9329. Gerber.app = self
  9330. Excellon.app = self
  9331. Geometry.app = self
  9332. CNCjob.app = self
  9333. FCProcess.app = self
  9334. FCProcessContainer.app = self
  9335. def version_check(self):
  9336. """
  9337. Checks for the latest version of the program. Alerts the
  9338. user if theirs is outdated. This method is meant to be run
  9339. in a separate thread.
  9340. :return: None
  9341. """
  9342. self.log.debug("version_check()")
  9343. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  9344. full_url = App.version_url + \
  9345. "?s=" + str(self.defaults['global_serial']) + \
  9346. "&v=" + str(self.version) + \
  9347. "&os=" + str(self.os) + \
  9348. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  9349. else:
  9350. # no_stats dict; just so it won't break things on website
  9351. no_ststs_dict = {}
  9352. no_ststs_dict["global_ststs"] = {}
  9353. full_url = App.version_url + \
  9354. "?s=" + str(self.defaults['global_serial']) + \
  9355. "&v=" + str(self.version) + \
  9356. "&os=" + str(self.os) + \
  9357. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  9358. App.log.debug("Checking for updates @ %s" % full_url)
  9359. # ## Get the data
  9360. try:
  9361. f = urllib.request.urlopen(full_url)
  9362. except:
  9363. # App.log.warning("Failed checking for latest version. Could not connect.")
  9364. self.log.warning("Failed checking for latest version. Could not connect.")
  9365. self.inform.emit('[WARNING_NOTCL] %s' %
  9366. _("Failed checking for latest version. Could not connect."))
  9367. return
  9368. try:
  9369. data = json.load(f)
  9370. except Exception as e:
  9371. App.log.error("Could not parse information about latest version.")
  9372. self.inform.emit('[ERROR_NOTCL] %s' %
  9373. _("Could not parse information about latest version."))
  9374. App.log.debug("json.load(): %s" % str(e))
  9375. f.close()
  9376. return
  9377. f.close()
  9378. # ## Latest version?
  9379. if self.version >= data["version"]:
  9380. App.log.debug("FlatCAM is up to date!")
  9381. self.inform.emit('[success] %s' %
  9382. _("FlatCAM is up to date!"))
  9383. return
  9384. App.log.debug("Newer version available.")
  9385. self.message.emit(
  9386. _("Newer Version Available"),
  9387. _("There is a newer version of FlatCAM available for download:\n\n") +
  9388. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  9389. _("info")
  9390. )
  9391. def on_plotcanvas_setup(self, container=None):
  9392. """
  9393. This is doing the setup for the plot area (VisPy canvas)
  9394. :param container: widget where to install the canvas
  9395. :return: None
  9396. """
  9397. if container:
  9398. plot_container = container
  9399. else:
  9400. plot_container = self.ui.right_layout
  9401. if self.is_legacy is False:
  9402. self.plotcanvas = PlotCanvas(plot_container, self)
  9403. else:
  9404. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  9405. # So it can receive key presses
  9406. self.plotcanvas.native.setFocus()
  9407. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  9408. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  9409. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  9410. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_double_click_over_plot)
  9411. # Keys over plot enabled
  9412. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  9413. if self.defaults['global_cursor_type'] == 'small':
  9414. self.app_cursor = self.plotcanvas.new_cursor()
  9415. else:
  9416. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  9417. if self.ui.grid_snap_btn.isChecked():
  9418. self.app_cursor.enabled = True
  9419. else:
  9420. self.app_cursor.enabled = False
  9421. if self.is_legacy is False:
  9422. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  9423. else:
  9424. # will use the default Matplotlib axes
  9425. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  9426. def on_zoom_fit(self, event):
  9427. """
  9428. Callback for zoom-out request. This can be either from the corresponding
  9429. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  9430. with axes limits from the geometry bounds of all objects.
  9431. :param event: Ignored.
  9432. :return: None
  9433. """
  9434. if self.is_legacy is False:
  9435. self.plotcanvas.fit_view()
  9436. else:
  9437. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  9438. width = xmax - xmin
  9439. height = ymax - ymin
  9440. xmin -= 0.05 * width
  9441. xmax += 0.05 * width
  9442. ymin -= 0.05 * height
  9443. ymax += 0.05 * height
  9444. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  9445. def on_zoom_in(self):
  9446. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  9447. def on_zoom_out(self):
  9448. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  9449. def disable_all_plots(self):
  9450. self.report_usage("disable_all_plots()")
  9451. self.disable_plots(self.collection.get_list())
  9452. self.inform.emit('[success] %s' %
  9453. _("All plots disabled."))
  9454. def disable_other_plots(self):
  9455. self.report_usage("disable_other_plots()")
  9456. self.disable_plots(self.collection.get_non_selected())
  9457. self.inform.emit('[success] %s' %
  9458. _("All non selected plots disabled."))
  9459. def enable_all_plots(self):
  9460. self.report_usage("enable_all_plots()")
  9461. self.enable_plots(self.collection.get_list())
  9462. self.inform.emit('[success] %s' %
  9463. _("All plots enabled."))
  9464. def on_enable_sel_plots(self):
  9465. log.debug("App.on_enable_sel_plot()")
  9466. object_list = self.collection.get_selected()
  9467. self.enable_plots(objects=object_list)
  9468. self.inform.emit('[success] %s' %
  9469. _("Selected plots enabled..."))
  9470. def on_disable_sel_plots(self):
  9471. log.debug("App.on_disable_sel_plot()")
  9472. # self.inform.emit(_("Disabling plots ..."))
  9473. object_list = self.collection.get_selected()
  9474. self.disable_plots(objects=object_list)
  9475. self.inform.emit('[success] %s' %
  9476. _("Selected plots disabled..."))
  9477. def enable_plots(self, objects):
  9478. """
  9479. Disables plots
  9480. :param objects: list of Objects to be enabled
  9481. :return:
  9482. """
  9483. log.debug("Enabling plots ...")
  9484. # self.inform.emit(_("Working ..."))
  9485. for obj in objects:
  9486. if obj.options['plot'] is False:
  9487. obj.options.set_change_callback(lambda x: None)
  9488. obj.options['plot'] = True
  9489. obj.options.set_change_callback(obj.on_options_change)
  9490. def worker_task(objects):
  9491. with self.proc_container.new(_("Enabling plots ...")):
  9492. for obj in objects:
  9493. # obj.options['plot'] = True
  9494. if isinstance(obj, FlatCAMCNCjob):
  9495. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  9496. else:
  9497. obj.plot(visible=True)
  9498. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9499. # self.plots_updated.emit()
  9500. def disable_plots(self, objects):
  9501. """
  9502. Disables plots
  9503. :param objects: list of Objects to be disabled
  9504. :return:
  9505. """
  9506. # if no objects selected then do nothing
  9507. if not self.collection.get_selected():
  9508. return
  9509. log.debug("Disabling plots ...")
  9510. # self.inform.emit(_("Working ..."))
  9511. for obj in objects:
  9512. if obj.options['plot'] is True:
  9513. obj.options.set_change_callback(lambda x: None)
  9514. obj.options['plot'] = False
  9515. obj.options.set_change_callback(obj.on_options_change)
  9516. try:
  9517. self.delete_selection_shape()
  9518. except Exception as e:
  9519. log.debug("App.disable_plots() --> %s" % str(e))
  9520. # self.plots_updated.emit()
  9521. def worker_task(objects):
  9522. with self.proc_container.new(_("Disabling plots ...")):
  9523. for obj in objects:
  9524. # obj.options['plot'] = True
  9525. if isinstance(obj, FlatCAMCNCjob):
  9526. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  9527. else:
  9528. obj.plot(visible=False)
  9529. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9530. def toggle_plots(self, objects):
  9531. """
  9532. Toggle plots visibility
  9533. :param objects: list of Objects for which to be toggled the visibility
  9534. :return:
  9535. """
  9536. # if no objects selected then do nothing
  9537. if not self.collection.get_selected():
  9538. return
  9539. log.debug("Toggling plots ...")
  9540. self.inform.emit(_("Working ..."))
  9541. for obj in objects:
  9542. if obj.options['plot'] is False:
  9543. obj.options['plot'] = True
  9544. else:
  9545. obj.options['plot'] = False
  9546. self.plots_updated.emit()
  9547. def clear_plots(self):
  9548. objects = self.collection.get_list()
  9549. for obj in objects:
  9550. obj.clear(obj == objects[-1])
  9551. # Clear pool to free memory
  9552. self.clear_pool()
  9553. def generate_cnc_job(self, objects):
  9554. self.report_usage("generate_cnc_job()")
  9555. # for obj in objects:
  9556. # obj.generatecncjob()
  9557. for obj in objects:
  9558. obj.on_generatecnc_button_click()
  9559. def save_project(self, filename, quit_action=False, silent=False):
  9560. """
  9561. Saves the current project to the specified file.
  9562. :param filename: Name of the file in which to save.
  9563. :type filename: str
  9564. :param quit_action: if the project saving will be followed by an app quit; boolean
  9565. :param silent: if True will not display status messages
  9566. :return: None
  9567. """
  9568. self.log.debug("save_project()")
  9569. self.save_in_progress = True
  9570. with self.proc_container.new(_("Saving FlatCAM Project")):
  9571. # Capture the latest changes
  9572. # Current object
  9573. try:
  9574. self.collection.get_active().read_form()
  9575. except:
  9576. self.log.debug("There was no active object")
  9577. pass
  9578. # Project options
  9579. self.options_read_form()
  9580. # Serialize the whole project
  9581. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  9582. "options": self.options,
  9583. "version": self.version}
  9584. if self.defaults["global_save_compressed"] is True:
  9585. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  9586. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  9587. # # Write
  9588. f.write(g)
  9589. self.inform.emit('[success] %s: %s' %
  9590. (_("Project saved to"), filename))
  9591. else:
  9592. # Open file
  9593. try:
  9594. f = open(filename, 'w')
  9595. except IOError:
  9596. App.log.error("Failed to open file for saving: %s", filename)
  9597. return
  9598. # Write
  9599. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  9600. f.close()
  9601. # verification of the saved project
  9602. # Open and parse
  9603. try:
  9604. saved_f = open(filename, 'r')
  9605. except IOError:
  9606. if silent is False:
  9607. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9608. (_("Failed to verify project file"), filename, _("Retry to save it."))
  9609. )
  9610. return
  9611. try:
  9612. saved_d = json.load(saved_f, object_hook=dict2obj)
  9613. except:
  9614. if silent is False:
  9615. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9616. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9617. )
  9618. f.close()
  9619. return
  9620. saved_f.close()
  9621. if silent is False:
  9622. if 'version' in saved_d:
  9623. self.inform.emit('[success] %s: %s' %
  9624. (_("Project saved to"), filename))
  9625. else:
  9626. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9627. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9628. )
  9629. settings = QSettings("Open Source", "FlatCAM")
  9630. lock_state = self.ui.lock_action.isChecked()
  9631. settings.setValue('toolbar_lock', lock_state)
  9632. # This will write the setting to the platform specific storage.
  9633. del settings
  9634. # if quit:
  9635. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  9636. # t.start()
  9637. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  9638. def start_delayed_quit(self, delay, filename, should_quit=None):
  9639. """
  9640. :param delay: period of checking if project file size is more than zero; in seconds
  9641. :param filename: the name of the project file to be checked periodically for size more than zero
  9642. :param should_quit: if the task finished will be followed by an app quit; boolean
  9643. :return:
  9644. """
  9645. to_quit = should_quit
  9646. self.save_timer = QtCore.QTimer()
  9647. self.save_timer.setInterval(delay)
  9648. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  9649. self.save_timer.start()
  9650. def check_project_file_size(self, filename, should_quit=None):
  9651. """
  9652. :param filename: the name of the project file to be checked periodically for size more than zero
  9653. :param should_quit: will quit the app if True; boolean
  9654. :return:
  9655. """
  9656. try:
  9657. if os.stat(filename).st_size > 0:
  9658. self.save_in_progress = False
  9659. self.save_timer.stop()
  9660. if should_quit:
  9661. self.app_quit.emit()
  9662. except Exception as e:
  9663. traceback.print_exc()
  9664. def on_options_app2project(self):
  9665. """
  9666. Callback for Options->Transfer Options->App=>Project. Copies options
  9667. from application defaults to project defaults.
  9668. :return: None
  9669. """
  9670. self.report_usage("on_options_app2project")
  9671. self.defaults_read_form()
  9672. self.options.update(self.defaults)
  9673. self.options_write_form()
  9674. def on_options_project2app(self):
  9675. """
  9676. Callback for Options->Transfer Options->Project=>App. Copies options
  9677. from project defaults to application defaults.
  9678. :return: None
  9679. """
  9680. self.report_usage("on_options_project2app")
  9681. self.options_read_form()
  9682. self.defaults.update(self.options)
  9683. self.defaults_write_form()
  9684. def on_options_project2object(self):
  9685. """
  9686. Callback for Options->Transfer Options->Project=>Object. Copies options
  9687. from project defaults to the currently selected object.
  9688. :return: None
  9689. """
  9690. self.report_usage("on_options_project2object")
  9691. self.options_read_form()
  9692. obj = self.collection.get_active()
  9693. if obj is None:
  9694. self.inform.emit('[WARNING_NOTCL] %s' %
  9695. _("No object selected."))
  9696. return
  9697. for option in self.options:
  9698. if option.find(obj.kind + "_") == 0:
  9699. oname = option[len(obj.kind) + 1:]
  9700. obj.options[oname] = self.options[option]
  9701. obj.to_form() # Update UI
  9702. def on_options_object2project(self):
  9703. """
  9704. Callback for Options->Transfer Options->Object=>Project. Copies options
  9705. from the currently selected object to project defaults.
  9706. :return: None
  9707. """
  9708. self.report_usage("on_options_object2project")
  9709. obj = self.collection.get_active()
  9710. if obj is None:
  9711. self.inform.emit('[WARNING_NOTCL] %s' %
  9712. _("No object selected."))
  9713. return
  9714. obj.read_form()
  9715. for option in obj.options:
  9716. if option in ['name']: # TODO: Handle this better...
  9717. continue
  9718. self.options[obj.kind + "_" + option] = obj.options[option]
  9719. self.options_write_form()
  9720. def on_options_object2app(self):
  9721. """
  9722. Callback for Options->Transfer Options->Object=>App. Copies options
  9723. from the currently selected object to application defaults.
  9724. :return: None
  9725. """
  9726. self.report_usage("on_options_object2app")
  9727. obj = self.collection.get_active()
  9728. if obj is None:
  9729. self.inform.emit('[WARNING_NOTCL] %s' %
  9730. _("No object selected."))
  9731. return
  9732. obj.read_form()
  9733. for option in obj.options:
  9734. if option in ['name']: # TODO: Handle this better...
  9735. continue
  9736. self.defaults[obj.kind + "_" + option] = obj.options[option]
  9737. self.defaults_write_form()
  9738. def on_options_app2object(self):
  9739. """
  9740. Callback for Options->Transfer Options->App=>Object. Copies options
  9741. from application defaults to the currently selected object.
  9742. :return: None
  9743. """
  9744. self.report_usage("on_options_app2object")
  9745. self.defaults_read_form()
  9746. obj = self.collection.get_active()
  9747. if obj is None:
  9748. self.inform.emit('[WARNING_NOTCL] %s' %
  9749. _("No object selected."))
  9750. return
  9751. for option in self.defaults:
  9752. if option.find(obj.kind + "_") == 0:
  9753. oname = option[len(obj.kind) + 1:]
  9754. obj.options[oname] = self.defaults[option]
  9755. obj.to_form() # Update UI
  9756. class ArgsThread(QtCore.QObject):
  9757. open_signal = pyqtSignal(list)
  9758. start = pyqtSignal()
  9759. if sys.platform == 'win32':
  9760. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  9761. else:
  9762. address = ('/tmp/testipc', 'AF_UNIX')
  9763. def __init__(self):
  9764. super(ArgsThread, self).__init__()
  9765. self.start.connect(self.run)
  9766. def my_loop(self, address):
  9767. try:
  9768. listener = Listener(*address)
  9769. while True:
  9770. conn = listener.accept()
  9771. self.serve(conn)
  9772. except socket.error as e:
  9773. conn = Client(*address)
  9774. conn.send(sys.argv)
  9775. conn.send('close')
  9776. # close the current instance only if there are args
  9777. if len(sys.argv) > 1:
  9778. sys.exit()
  9779. def serve(self, conn):
  9780. while True:
  9781. msg = conn.recv()
  9782. if msg == 'close':
  9783. break
  9784. self.open_signal.emit(msg)
  9785. conn.close()
  9786. # the decorator is a must; without it this technique will not work unless the start signal is connected
  9787. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  9788. @pyqtSlot()
  9789. def run(self):
  9790. self.my_loop(self.address)
  9791. class GracefulException(Exception):
  9792. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  9793. def __init__(self):
  9794. super().__init__()
  9795. def __str__(self):
  9796. return ('\n\n%s' % _("The user requested a graceful exit of the current task."))
  9797. # end of file