FlatCAMApp.py 528 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736
  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.measurement_tool = None
  2027. self.panelize_tool = None
  2028. self.film_tool = None
  2029. self.paste_tool = None
  2030. self.calculator_tool = None
  2031. self.rules_tool = None
  2032. self.sub_tool = None
  2033. self.move_tool = None
  2034. self.cutout_tool = None
  2035. self.ncclear_tool = None
  2036. self.optimal_tool=None
  2037. self.paint_tool = None
  2038. self.transform_tool = None
  2039. self.properties_tool = None
  2040. self.pdf_tool = None
  2041. self.image_tool = None
  2042. self.pcb_wizard_tool = None
  2043. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  2044. self.install_tools()
  2045. # ### System Font Parsing ###
  2046. # self.f_parse = ParseFont(self)
  2047. # self.parse_system_fonts()
  2048. # #####################################################################################
  2049. # ######################## Check for updates ##########################################
  2050. # #####################################################################################
  2051. # Separate thread (Not worker)
  2052. # Check for updates on startup but only if the user consent and the app is not in Beta version
  2053. if (self.beta is False or self.beta is None) and \
  2054. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  2055. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  2056. self.thr2 = QtCore.QThread()
  2057. self.worker_task.emit({'fcn': self.version_check,
  2058. 'params': []})
  2059. self.thr2.start(QtCore.QThread.LowPriority)
  2060. # #####################################################################################
  2061. # ######################### Register files with FlatCAM; #############################
  2062. # ######################### It works only for Windows for now ########################
  2063. # #####################################################################################
  2064. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  2065. self.on_register_files()
  2066. # #####################################################################################
  2067. # ###################### Variables for global usage ###################################
  2068. # #####################################################################################
  2069. # coordinates for relative position display
  2070. self.rel_point1 = (0, 0)
  2071. self.rel_point2 = (0, 0)
  2072. # variable to store coordinates
  2073. self.pos = (0, 0)
  2074. self.pos_jump = (0, 0)
  2075. # variable to store mouse coordinates
  2076. self.mouse = [0, 0]
  2077. # decide if we have a double click or single click
  2078. self.doubleclick = False
  2079. # variable to store if a command is active (then the var is not None) and which one it is
  2080. self.command_active = None
  2081. # variable to store the status of moving selection action
  2082. # None value means that it's not an selection action
  2083. # True value = a selection from left to right
  2084. # False value = a selection from right to left
  2085. self.selection_type = None
  2086. # List to store the objects that are currently loaded in FlatCAM
  2087. # This list is updated on each object creation or object delete
  2088. self.all_objects_list = list()
  2089. # List to store the objects that are selected
  2090. self.sel_objects_list = list()
  2091. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  2092. self.key_modifiers = None
  2093. # Variable to hold the status of the axis
  2094. self.toggle_axis = True
  2095. # Variable to store the status of the fullscreen event
  2096. self.toggle_fscreen = False
  2097. # Variable to store the status of the code editor
  2098. self.toggle_codeeditor = False
  2099. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  2100. self.click_noproject = False
  2101. self.cursor = None
  2102. # Variable to store the GCODE that was edited
  2103. self.gcode_edited = ""
  2104. # reference for the self.ui.code_editor
  2105. self.reference_code_editor = None
  2106. self.script_code = ''
  2107. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  2108. self.preferences_changed_flag = False
  2109. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  2110. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  2111. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'pho',
  2112. 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top', 'tsm']
  2113. self.exc_list = ['drd', 'drl', 'exc', 'ncd', 'tap', 'txt', 'xln']
  2114. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  2115. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ncp', 'out', 'plt', 'ply', 'rol', 'sbp',
  2116. 'tap', 'xpi']
  2117. self.svg_list = ['svg']
  2118. self.dxf_list = ['dxf']
  2119. self.pdf_list = ['pdf']
  2120. self.prj_list = ['flatprj']
  2121. self.conf_list = ['flatconfig']
  2122. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  2123. # flag for polygons not cleared
  2124. self.poly_not_cleared = False
  2125. # VisPy visuals
  2126. self.isHovering = False
  2127. self.notHovering = True
  2128. # Window geometry
  2129. self.x_pos = None
  2130. self.y_pos = None
  2131. self.width = None
  2132. self.height = None
  2133. # Event signals disconnect id holders
  2134. self.mp = None
  2135. self.mm = None
  2136. self.mr = None
  2137. self.mp_zc = None
  2138. # when True, the app has to return from any thread
  2139. self.abort_flag = False
  2140. # set the value used in the Windows Title
  2141. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  2142. # ###############################################################################
  2143. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  2144. # ############# It's done only once after install ###############
  2145. # ###############################################################################
  2146. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  2147. fac_def_from_file = factory_file.read()
  2148. factory_defaults = json.loads(fac_def_from_file)
  2149. # if the file contain an empty dictionary then save the factory defaults into the file
  2150. if not factory_defaults:
  2151. self.save_factory_defaults(silent=False)
  2152. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  2153. initial_lay = 'compact'
  2154. self.on_layout(lay=initial_lay)
  2155. # Set the combobox in Preferences to the current layout
  2156. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  2157. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  2158. factory_file.close()
  2159. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  2160. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  2161. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  2162. # after the first run, this object should be False
  2163. self.defaults["first_run"] = False
  2164. # ###############################################################################
  2165. # ################# ADDING FlatCAM EDITORS section ##############################
  2166. # ###############################################################################
  2167. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2168. # at the first launch of the App , the editors will not be functional.
  2169. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  2170. self.exc_editor = FlatCAMExcEditor(self)
  2171. self.grb_editor = FlatCAMGrbEditor(self)
  2172. self.log.debug("Finished adding FlatCAM Editor's.")
  2173. self.set_ui_title(name=_("New Project - Not saved"))
  2174. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2175. current_platform = platform.architecture()[0]
  2176. if current_platform != '64bit':
  2177. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2178. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2179. # ###############################################################################
  2180. # ####################### Finished the CONSTRUCTOR ##############################
  2181. # ###############################################################################
  2182. App.log.debug("END of constructor. Releasing control.")
  2183. # #####################################################################################
  2184. # ########################## SHOW GUI #################################################
  2185. # #####################################################################################
  2186. # if the app is not started as headless, show it
  2187. if self.cmd_line_headless != 1:
  2188. if show_splash:
  2189. # finish the splash
  2190. self.splash.finish(self.ui)
  2191. settings = QSettings("Open Source", "FlatCAM")
  2192. if settings.contains("maximized_gui"):
  2193. maximized_ui = settings.value('maximized_gui', type=bool)
  2194. if maximized_ui is True:
  2195. self.ui.showMaximized()
  2196. else:
  2197. self.ui.show()
  2198. else:
  2199. self.ui.show()
  2200. if self.defaults["global_systray_icon"]:
  2201. self.trayIcon.show()
  2202. else:
  2203. log.warning("******************* RUNNING HEADLESS *******************")
  2204. # #####################################################################################
  2205. # ########################## START-UP ARGUMENTS #######################################
  2206. # #####################################################################################
  2207. # test if the program was started with a script as parameter
  2208. if self.cmd_line_shellvar:
  2209. try:
  2210. cnt = 0
  2211. command_tcl = 0
  2212. for i in self.cmd_line_shellvar.split(','):
  2213. if i is not None:
  2214. try:
  2215. command_tcl = eval(i)
  2216. except:
  2217. command_tcl = i
  2218. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  2219. cnt += 1
  2220. # if there are Windows paths then replace the path separator with a Unix like one
  2221. if sys.platform == 'win32':
  2222. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  2223. self.shell._sysShell.exec_command(command_tcl_formatted, no_echo=True)
  2224. except Exception as ext:
  2225. print("ERROR: ", ext)
  2226. sys.exit(2)
  2227. if self.cmd_line_shellfile:
  2228. try:
  2229. if self.ui.shell_dock.isHidden():
  2230. self.ui.shell_dock.show()
  2231. with open(self.cmd_line_shellfile, "r") as myfile:
  2232. if show_splash:
  2233. self.splash.showMessage('%s: %ssec\n%s' % (
  2234. _("Canvas initialization started.\n"
  2235. "Canvas initialization finished in"), '%.2f' % self.used_time,
  2236. _("Executing Tcl Script ...")),
  2237. alignment=Qt.AlignBottom | Qt.AlignLeft,
  2238. color=QtGui.QColor("gray"))
  2239. cmd_line_shellfile_text = myfile.read()
  2240. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  2241. except Exception as ext:
  2242. print("ERROR: ", ext)
  2243. sys.exit(2)
  2244. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2245. # the path/file_name must be enclosed in quotes if it contain spaces
  2246. if App.args:
  2247. self.args_at_startup.emit(App.args)
  2248. @staticmethod
  2249. def copy_and_overwrite(from_path, to_path):
  2250. """
  2251. From here:
  2252. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2253. :param from_path: source path
  2254. :param to_path: destination path
  2255. :return: None
  2256. """
  2257. if os.path.exists(to_path):
  2258. shutil.rmtree(to_path)
  2259. try:
  2260. shutil.copytree(from_path, to_path)
  2261. except FileNotFoundError:
  2262. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2263. shutil.copytree(from_new_path, to_path)
  2264. def on_startup_args(self, args, silent=False):
  2265. """
  2266. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2267. :param args: a list containing the application args at startup
  2268. :return: None
  2269. """
  2270. if args is not None:
  2271. args_to_process = args
  2272. else:
  2273. args_to_process = App.args
  2274. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2275. for argument in args_to_process:
  2276. if '.FlatPrj'.lower() in argument.lower():
  2277. try:
  2278. project_name = str(argument)
  2279. if project_name == "":
  2280. if silent is False:
  2281. self.inform.emit(_("Open cancelled."))
  2282. else:
  2283. # self.open_project(project_name)
  2284. run_from_arg = True
  2285. # self.worker_task.emit({'fcn': self.open_project,
  2286. # 'params': [project_name, run_from_arg]})
  2287. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2288. except Exception as e:
  2289. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2290. elif '.FlatConfig'.lower() in argument.lower():
  2291. try:
  2292. file_name = str(argument)
  2293. if file_name == "":
  2294. if silent is False:
  2295. self.inform.emit(_("Open Config file failed."))
  2296. else:
  2297. run_from_arg = True
  2298. # self.worker_task.emit({'fcn': self.open_config_file,
  2299. # 'params': [file_name, run_from_arg]})
  2300. self.open_config_file(file_name, run_from_arg=run_from_arg)
  2301. except Exception as e:
  2302. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2303. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  2304. try:
  2305. file_name = str(argument)
  2306. if file_name == "":
  2307. if silent is False:
  2308. self.inform.emit(_("Open Script file failed."))
  2309. else:
  2310. if silent is False:
  2311. self.on_fileopenscript(name=file_name)
  2312. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  2313. self.on_filerunscript(name=file_name)
  2314. except Exception as e:
  2315. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2316. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  2317. log.debug("App.on_startup_args() --> Quit event.")
  2318. sys.exit()
  2319. elif 'save'.lower() in argument.lower():
  2320. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  2321. self.save_defaults()
  2322. else:
  2323. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2324. proc_arg = argument.lower()
  2325. for ext in exc_list:
  2326. proc_ext = ext.replace(' ', '')
  2327. proc_ext = '.%s' % proc_ext
  2328. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2329. file_name = str(argument)
  2330. if file_name == "":
  2331. if silent is False:
  2332. self.inform.emit(_("Open Excellon file failed."))
  2333. else:
  2334. self.on_fileopenexcellon(name=file_name)
  2335. return
  2336. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2337. for ext in gco_list:
  2338. proc_ext = ext.replace(' ', '')
  2339. proc_ext = '.%s' % proc_ext
  2340. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2341. file_name = str(argument)
  2342. if file_name == "":
  2343. if silent is False:
  2344. self.inform.emit(_("Open GCode file failed."))
  2345. else:
  2346. self.on_fileopengcode(name=file_name)
  2347. return
  2348. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2349. for ext in grb_list:
  2350. proc_ext = ext.replace(' ', '')
  2351. proc_ext = '.%s' % proc_ext
  2352. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2353. file_name = str(argument)
  2354. if file_name == "":
  2355. if silent is False:
  2356. self.inform.emit(_("Open Gerber file failed."))
  2357. else:
  2358. self.on_fileopengerber(name=file_name)
  2359. return
  2360. # if it reached here without already returning then the app was registered with a file that it does not
  2361. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  2362. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  2363. for arg in args_to_process:
  2364. if 'FlatCAM.exe' in arg:
  2365. continue
  2366. else:
  2367. sys.exit(2)
  2368. def set_ui_title(self, name):
  2369. """
  2370. Sets the title of the main window.
  2371. :param name: String that store the project path and project name
  2372. :return: None
  2373. """
  2374. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  2375. (self.version,
  2376. ('BETA' if self.beta else ''),
  2377. platform.architecture()[0],
  2378. self.engine,
  2379. name)
  2380. )
  2381. def on_app_restart(self):
  2382. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  2383. # be left in the SySTray
  2384. try:
  2385. self.trayIcon.hide()
  2386. except Exception as e:
  2387. log.debug("App.on_app_restart() --> %s" % str(e))
  2388. fcTranslate.restart_program(app=self)
  2389. def defaults_read_form(self):
  2390. """
  2391. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2392. :return: None
  2393. """
  2394. for option in self.defaults_form_fields:
  2395. try:
  2396. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2397. except Exception as e:
  2398. log.debug("App.defaults_read_form() --> %s" % str(e))
  2399. def defaults_write_form(self, factor=None, fl_units=None):
  2400. """
  2401. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2402. self.defaults dictionary.
  2403. :param factor: will apply a factor to the values that written in the GUI elements
  2404. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2405. :return: None
  2406. """
  2407. for option in self.defaults:
  2408. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2409. # try:
  2410. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2411. # except KeyError:
  2412. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2413. # # TODO: Rethink this?
  2414. # pass
  2415. def defaults_write_form_field(self, field, factor=None, units=None):
  2416. """
  2417. Basically it is the worker in the self.defaults_write_form()
  2418. :param field: the GUI element in Preferences GUI to be updated
  2419. :param factor: factor to be applied to the field parameter
  2420. :param units: current FLatCAM measuring units
  2421. :return: None, it updates GUI elements
  2422. """
  2423. try:
  2424. if factor is None:
  2425. if units is None:
  2426. self.defaults_form_fields[field].set_value(self.defaults[field])
  2427. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2428. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=6)
  2429. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2430. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=4)
  2431. else:
  2432. if units is None:
  2433. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2434. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2435. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=6)
  2436. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2437. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=4)
  2438. except KeyError:
  2439. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2440. # TODO: Rethink this?
  2441. pass
  2442. except AttributeError:
  2443. log.debug(field)
  2444. def clear_pool(self):
  2445. """
  2446. Clear the multiprocessing pool and calls garbage collector.
  2447. :return: None
  2448. """
  2449. self.pool.close()
  2450. self.pool = Pool()
  2451. self.pool_recreated.emit(self.pool)
  2452. gc.collect()
  2453. def install_tools(self):
  2454. """
  2455. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2456. Instantiation of the Tools classes.
  2457. The order that the tools are installed is important as they can depend on each other install position.
  2458. :return: None
  2459. """
  2460. self.dblsidedtool = DblSidedTool(self)
  2461. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2462. self.measurement_tool = Distance(self)
  2463. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), pos=self.ui.menuedit,
  2464. before=self.ui.menueditorigin,
  2465. separator=True)
  2466. self.panelize_tool = Panelize(self)
  2467. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  2468. self.film_tool = Film(self)
  2469. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2470. self.paste_tool = SolderPaste(self)
  2471. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2472. self.calculator_tool = ToolCalculator(self)
  2473. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'), separator=True)
  2474. self.sub_tool = ToolSub(self)
  2475. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2476. self.rules_tool = RulesCheck(self)
  2477. self.rules_tool.install(icon=QtGui.QIcon('share/rules32.png'), pos=self.ui.menutool, separator=False)
  2478. self.optimal_tool = ToolOptimal(self)
  2479. self.optimal_tool.install(icon=QtGui.QIcon('share/open_excellon32.png'), pos=self.ui.menutool, separator=True)
  2480. self.move_tool = ToolMove(self)
  2481. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2482. before=self.ui.menueditorigin, separator=True)
  2483. self.cutout_tool = CutOut(self)
  2484. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2485. before=self.measurement_tool.menuAction)
  2486. self.ncclear_tool = NonCopperClear(self)
  2487. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2488. before=self.measurement_tool.menuAction, separator=True)
  2489. self.paint_tool = ToolPaint(self)
  2490. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2491. before=self.measurement_tool.menuAction, separator=True)
  2492. self.transform_tool = ToolTransform(self)
  2493. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2494. self.properties_tool = Properties(self)
  2495. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2496. self.pdf_tool = ToolPDF(self)
  2497. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2498. separator=True)
  2499. self.image_tool = ToolImage(self)
  2500. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2501. separator=True)
  2502. self.pcb_wizard_tool = PcbWizard(self)
  2503. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2504. self.log.debug("Tools are installed.")
  2505. def remove_tools(self):
  2506. """
  2507. Will remove all the actions in the Tool menu.
  2508. :return: None
  2509. """
  2510. for act in self.ui.menutool.actions():
  2511. self.ui.menutool.removeAction(act)
  2512. def init_tools(self):
  2513. """
  2514. Initialize the Tool tab in the notebook side of the central widget.
  2515. Remove the actions in the Tools menu.
  2516. Instantiate again the FlatCAM tools (plugins).
  2517. All this is required when changing the layout: standard, compact etc.
  2518. :return: None
  2519. """
  2520. log.debug("init_tools()")
  2521. # delete the data currently in the Tools Tab and the Tab itself
  2522. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2523. if widget is not None:
  2524. widget.deleteLater()
  2525. self.ui.notebook.removeTab(2)
  2526. # rebuild the Tools Tab
  2527. self.ui.tool_tab = QtWidgets.QWidget()
  2528. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2529. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2530. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2531. self.ui.tool_scroll_area = VerticalScrollArea()
  2532. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2533. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2534. # first remove all of them
  2535. self.remove_tools()
  2536. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2537. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2538. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2539. # third install all of them
  2540. self.install_tools()
  2541. self.log.debug("Tools are initialized.")
  2542. # def parse_system_fonts(self):
  2543. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2544. # 'params': []})
  2545. def connect_toolbar_signals(self):
  2546. """
  2547. Reconnect the signals to the actions in the toolbar.
  2548. This has to be done each time after the FlatCAM tools are removed/installed.
  2549. :return: None
  2550. """
  2551. # Toolbar
  2552. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2553. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2554. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2555. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2556. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2557. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2558. self.ui.replot_btn.triggered.connect(self.plot_all)
  2559. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2560. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2561. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2562. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2563. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2564. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2565. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2566. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2567. self.ui.delete_btn.triggered.connect(self.on_delete)
  2568. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2569. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2570. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2571. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2572. # Tools Toolbar Signals
  2573. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2574. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2575. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2576. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2577. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2578. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2579. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2580. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2581. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  2582. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  2583. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2584. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2585. def object2editor(self):
  2586. """
  2587. Send the current Geometry or Excellon object (if any) into the it's editor.
  2588. :return: None
  2589. """
  2590. self.report_usage("object2editor()")
  2591. edited_object = self.collection.get_active()
  2592. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2593. isinstance(edited_object, FlatCAMExcellon):
  2594. pass
  2595. else:
  2596. self.inform.emit('[WARNING_NOTCL] %s' %
  2597. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2598. return
  2599. if isinstance(edited_object, FlatCAMGeometry):
  2600. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2601. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2602. # we set the notebook to hidden
  2603. self.ui.splitter.setSizes([0, 1])
  2604. if edited_object.multigeo is True:
  2605. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  2606. if len(edited_tools) > 1:
  2607. self.inform.emit('[WARNING_NOTCL] %s' %
  2608. _("Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  2609. "is not possible.\n"
  2610. "Edit only one geometry at a time."))
  2611. # determine the tool dia of the selected tool
  2612. selected_tooldia = float(edited_object.ui.geo_tools_table.item((edited_tools[0] - 1), 1).text())
  2613. # now find the key in the edited_object.tools that has this tooldia
  2614. multi_tool = 1
  2615. for tool in edited_object.tools:
  2616. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2617. multi_tool = tool
  2618. break
  2619. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2620. else:
  2621. self.geo_editor.edit_fcgeometry(edited_object)
  2622. # set call source to the Editor we go into
  2623. self.call_source = 'geo_editor'
  2624. elif isinstance(edited_object, FlatCAMExcellon):
  2625. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2626. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2627. if self.ui.splitter.sizes()[0] == 0:
  2628. self.ui.splitter.setSizes([1, 1])
  2629. self.exc_editor.edit_fcexcellon(edited_object)
  2630. # set call source to the Editor we go into
  2631. self.call_source = 'exc_editor'
  2632. elif isinstance(edited_object, FlatCAMGerber):
  2633. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2634. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2635. if self.ui.splitter.sizes()[0] == 0:
  2636. self.ui.splitter.setSizes([1, 1])
  2637. self.grb_editor.edit_fcgerber(edited_object)
  2638. # set call source to the Editor we go into
  2639. self.call_source = 'grb_editor'
  2640. # make sure that we can't select another object while in Editor Mode:
  2641. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2642. self.ui.project_frame.setDisabled(True)
  2643. # delete any selection shape that might be active as they are not relevant in Editor
  2644. self.delete_selection_shape()
  2645. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2646. self.ui.plot_tab_area.protectTab(0)
  2647. self.inform.emit('[WARNING_NOTCL] %s' %
  2648. _("Editor is activated ..."))
  2649. self.should_we_save = True
  2650. def editor2object(self, cleanup=None):
  2651. """
  2652. Transfers the Geometry or Excellon from it's editor to the current object.
  2653. :return: None
  2654. """
  2655. self.report_usage("editor2object()")
  2656. # do not update a geometry or excellon object unless it comes out of an editor
  2657. if self.call_source != 'app':
  2658. edited_obj = self.collection.get_active()
  2659. if cleanup is None:
  2660. msgbox = QtWidgets.QMessageBox()
  2661. msgbox.setText(_("Do you want to save the edited object?"))
  2662. msgbox.setWindowTitle(_("Close Editor"))
  2663. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2664. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2665. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2666. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2667. msgbox.setDefaultButton(bt_yes)
  2668. msgbox.exec_()
  2669. response = msgbox.clickedButton()
  2670. if response == bt_yes:
  2671. # clean the Tools Tab
  2672. self.ui.tool_scroll_area.takeWidget()
  2673. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2674. self.ui.notebook.setTabText(2, "Tool")
  2675. if isinstance(edited_obj, FlatCAMGeometry):
  2676. obj_type = "Geometry"
  2677. if cleanup is None:
  2678. self.geo_editor.update_fcgeometry(edited_obj)
  2679. self.geo_editor.update_options(edited_obj)
  2680. self.geo_editor.deactivate()
  2681. # update the geo object options so it is including the bounding box values
  2682. try:
  2683. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2684. edited_obj.options['xmin'] = xmin
  2685. edited_obj.options['ymin'] = ymin
  2686. edited_obj.options['xmax'] = xmax
  2687. edited_obj.options['ymax'] = ymax
  2688. except AttributeError as e:
  2689. self.inform.emit('[WARNING] %s' %
  2690. _("Object empty after edit."))
  2691. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2692. elif isinstance(edited_obj, FlatCAMGerber):
  2693. obj_type = "Gerber"
  2694. if cleanup is None:
  2695. self.grb_editor.update_fcgerber()
  2696. self.grb_editor.update_options(edited_obj)
  2697. self.grb_editor.deactivate_grb_editor()
  2698. # delete the old object (the source object) if it was an empty one
  2699. if len(edited_obj.solid_geometry) == 0:
  2700. old_name = edited_obj.options['name']
  2701. self.collection.set_active(old_name)
  2702. self.collection.delete_active()
  2703. # restore GUI to the Selected TAB
  2704. # Remove anything else in the GUI
  2705. self.ui.selected_scroll_area.takeWidget()
  2706. # Switch notebook to Selected page
  2707. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2708. elif isinstance(edited_obj, FlatCAMExcellon):
  2709. obj_type = "Excellon"
  2710. if cleanup is None:
  2711. self.exc_editor.update_fcexcellon(edited_obj)
  2712. self.exc_editor.update_options(edited_obj)
  2713. self.exc_editor.deactivate()
  2714. # delete the old object (the source object) if it was an empty one
  2715. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  2716. old_name = edited_obj.options['name']
  2717. self.collection.set_active(old_name)
  2718. self.collection.delete_active()
  2719. # restore GUI to the Selected TAB
  2720. # Remove anything else in the GUI
  2721. self.ui.tool_scroll_area.takeWidget()
  2722. # Switch notebook to Selected page
  2723. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2724. else:
  2725. self.inform.emit('[WARNING_NOTCL] %s' %
  2726. _("Select a Gerber, Geometry or Excellon Object to update."))
  2727. return
  2728. self.inform.emit('[selected] %s %s' %
  2729. (obj_type, _("is updated, returning to App...")))
  2730. elif response == bt_no:
  2731. # clean the Tools Tab
  2732. self.ui.tool_scroll_area.takeWidget()
  2733. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2734. self.ui.notebook.setTabText(2, "Tool")
  2735. if isinstance(edited_obj, FlatCAMGeometry):
  2736. self.geo_editor.deactivate()
  2737. elif isinstance(edited_obj, FlatCAMGerber):
  2738. self.grb_editor.deactivate_grb_editor()
  2739. elif isinstance(edited_obj, FlatCAMExcellon):
  2740. self.exc_editor.deactivate()
  2741. # set focus on the project tab
  2742. else:
  2743. self.inform.emit('[WARNING_NOTCL] %s' %
  2744. _("Select a Gerber, Geometry or Excellon Object to update."))
  2745. return
  2746. edited_obj.set_ui(edited_obj.ui_type())
  2747. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2748. elif response == bt_cancel:
  2749. return
  2750. else:
  2751. if isinstance(edited_obj, FlatCAMGeometry):
  2752. self.geo_editor.deactivate()
  2753. elif isinstance(edited_obj, FlatCAMGerber):
  2754. self.grb_editor.deactivate_grb_editor()
  2755. elif isinstance(edited_obj, FlatCAMExcellon):
  2756. self.exc_editor.deactivate()
  2757. else:
  2758. self.inform.emit('[WARNING_NOTCL] %s' %
  2759. _("Select a Gerber, Geometry or Excellon Object to update."))
  2760. return
  2761. # if notebook is hidden we show it
  2762. if self.ui.splitter.sizes()[0] == 0:
  2763. self.ui.splitter.setSizes([1, 1])
  2764. # restore the call_source to app
  2765. self.call_source = 'app'
  2766. edited_obj.plot()
  2767. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2768. self.ui.plot_tab_area.protectTab(0)
  2769. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2770. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2771. self.ui.project_frame.setDisabled(False)
  2772. def get_last_folder(self):
  2773. """
  2774. Get the folder path from where the last file was opened.
  2775. :return: String, last opened folder path
  2776. """
  2777. return self.defaults["global_last_folder"]
  2778. def get_last_save_folder(self):
  2779. """
  2780. Get the folder path from where the last file was saved.
  2781. :return: String, last saved folder path
  2782. """
  2783. loc = self.defaults["global_last_save_folder"]
  2784. if loc is None:
  2785. loc = self.defaults["global_last_folder"]
  2786. if loc is None:
  2787. loc = os.path.dirname(__file__)
  2788. return loc
  2789. def report_usage(self, resource):
  2790. """
  2791. Increments usage counter for the given resource
  2792. in self.defaults['global_stats'].
  2793. :param resource: Name of the resource.
  2794. :return: None
  2795. """
  2796. if resource in self.defaults['global_stats']:
  2797. self.defaults['global_stats'][resource] += 1
  2798. else:
  2799. self.defaults['global_stats'][resource] = 1
  2800. def init_tcl(self):
  2801. """
  2802. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2803. :return: None
  2804. """
  2805. if hasattr(self, 'tcl'):
  2806. # self.tcl = None
  2807. # TODO we need to clean non default variables and procedures here
  2808. # new object cannot be used here as it will not remember values created for next passes,
  2809. # because tcl was execudted in old instance of TCL
  2810. pass
  2811. else:
  2812. self.tcl = tk.Tcl()
  2813. self.setup_shell()
  2814. self.log.debug("TCL Shell has been initialized.")
  2815. # TODO: This shouldn't be here.
  2816. class TclErrorException(Exception):
  2817. """
  2818. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2819. """
  2820. pass
  2821. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2822. """
  2823. Shows a message on the FlatCAM Shell
  2824. :param msg: Message to display.
  2825. :param show: Opens the shell.
  2826. :param error: Shows the message as an error.
  2827. :param warning: Shows the message as an warning.
  2828. :param success: Shows the message as an success.
  2829. :param selected: Indicate that something was selected on canvas
  2830. :return: None
  2831. """
  2832. if show:
  2833. self.ui.shell_dock.show()
  2834. try:
  2835. if error:
  2836. self.shell.append_error(msg + "\n")
  2837. elif warning:
  2838. self.shell.append_warning(msg + "\n")
  2839. elif success:
  2840. self.shell.append_success(msg + "\n")
  2841. elif selected:
  2842. self.shell.append_selected(msg + "\n")
  2843. else:
  2844. self.shell.append_output(msg + "\n")
  2845. except AttributeError:
  2846. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2847. def raise_tcl_unknown_error(self, unknownException):
  2848. """
  2849. Raise exception if is different type than TclErrorException
  2850. this is here mainly to show unknown errors inside TCL shell console.
  2851. :param unknownException:
  2852. :return:
  2853. """
  2854. if not isinstance(unknownException, self.TclErrorException):
  2855. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2856. else:
  2857. raise unknownException
  2858. def display_tcl_error(self, error, error_info=None):
  2859. """
  2860. Escape bracket [ with '\' otherwise there is error
  2861. "ERROR: missing close-bracket" instead of real error
  2862. :param error: it may be text or exception
  2863. :param error_info: Some informations about the error
  2864. :return: None
  2865. """
  2866. if isinstance(error, Exception):
  2867. exc_type, exc_value, exc_traceback = error_info
  2868. if not isinstance(error, self.TclErrorException):
  2869. show_trace = 1
  2870. else:
  2871. show_trace = int(self.defaults['global_verbose_error_level'])
  2872. if show_trace > 0:
  2873. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2874. trc_formated = []
  2875. for a in reversed(trc):
  2876. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2877. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2878. else:
  2879. text = "%s" % error
  2880. else:
  2881. text = error
  2882. text = text.replace('[', '\\[').replace('"', '\\"')
  2883. self.tcl.eval('return -code error "%s"' % text)
  2884. def raise_tcl_error(self, text):
  2885. """
  2886. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2887. :param text: text of error
  2888. :return: raise exception
  2889. """
  2890. self.display_tcl_error(text)
  2891. raise self.TclErrorException(text)
  2892. def exec_command(self, text, no_echo=False):
  2893. """
  2894. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2895. Also handles execution in separated threads
  2896. :param text: FlatCAM TclCommand with parameters
  2897. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2898. will create crashes of the _Expandable_Edit widget
  2899. :return: output if there was any
  2900. """
  2901. self.report_usage('exec_command')
  2902. result = self.exec_command_test(text, False, no_echo=no_echo)
  2903. # MS: added this method call so the geometry is updated once the TCL command is executed
  2904. # if no_plot is None:
  2905. # self.plot_all()
  2906. return result
  2907. def exec_command_test(self, text, reraise=True, no_echo=False):
  2908. """
  2909. Same as exec_command(...) with additional control over exceptions.
  2910. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2911. :param text: Input command
  2912. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2913. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2914. will create crashes of the _Expandable_Edit widget
  2915. :return: Output from the command
  2916. """
  2917. tcl_command_string = str(text)
  2918. try:
  2919. if no_echo is False:
  2920. self.shell.open_proccessing() # Disables input box.
  2921. result = self.tcl.eval(str(tcl_command_string))
  2922. if result != 'None' and no_echo is False:
  2923. self.shell.append_output(result + '\n')
  2924. except tk.TclError as e:
  2925. # This will display more precise answer if something in TCL shell fails
  2926. result = self.tcl.eval("set errorInfo")
  2927. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2928. if no_echo is False:
  2929. self.shell.append_error('ERROR: ' + result + '\n')
  2930. # Show error in console and just return or in test raise exception
  2931. if reraise:
  2932. raise e
  2933. finally:
  2934. if no_echo is False:
  2935. self.shell.close_proccessing()
  2936. pass
  2937. return result
  2938. # """
  2939. # Code below is unsused. Saved for later.
  2940. # """
  2941. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2942. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2943. # self.log.debug(parts)
  2944. # try:
  2945. # if parts[0] not in commands:
  2946. # self.shell.append_error("Unknown command\n")
  2947. # return
  2948. #
  2949. # #import inspect
  2950. # #inspect.getargspec(someMethod)
  2951. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2952. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2953. # self.shell.append_error(
  2954. # "Command %s takes %d arguments. %d given.\n" %
  2955. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2956. # )
  2957. # return
  2958. #
  2959. # cmdfcn = commands[parts[0]]["fcn"]
  2960. # cmdconv = commands[parts[0]]["converters"]
  2961. # if len(parts) - 1 > 0:
  2962. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2963. # else:
  2964. # retval = cmdfcn()
  2965. # retfcn = commands[parts[0]]["retfcn"]
  2966. # if retval and retfcn(retval):
  2967. # self.shell.append_output(retfcn(retval) + "\n")
  2968. #
  2969. # except Exception as e:
  2970. # #self.shell.append_error(''.join(traceback.format_exc()))
  2971. # #self.shell.append_error("?\n")
  2972. # self.shell.append_error(str(e) + "\n")
  2973. def info(self, msg):
  2974. """
  2975. Informs the user. Normally on the status bar, optionally
  2976. also on the shell.
  2977. :param msg: Text to write.
  2978. :return: None
  2979. """
  2980. # Type of message in brackets at the beginning of the message.
  2981. match = re.search("\[([^\]]+)\](.*)", msg)
  2982. if match:
  2983. level = match.group(1)
  2984. msg_ = match.group(2)
  2985. self.ui.fcinfo.set_status(str(msg_), level=level)
  2986. if level.lower() == "error":
  2987. self.shell_message(msg, error=True, show=True)
  2988. elif level.lower() == "warning":
  2989. self.shell_message(msg, warning=True, show=True)
  2990. elif level.lower() == "error_notcl":
  2991. self.shell_message(msg, error=True, show=False)
  2992. elif level.lower() == "warning_notcl":
  2993. self.shell_message(msg, warning=True, show=False)
  2994. elif level.lower() == "success":
  2995. self.shell_message(msg, success=True, show=False)
  2996. elif level.lower() == "selected":
  2997. self.shell_message(msg, selected=True, show=False)
  2998. else:
  2999. self.shell_message(msg, show=False)
  3000. else:
  3001. self.ui.fcinfo.set_status(str(msg), level="info")
  3002. # make sure that if the message is to clear the infobar with a space
  3003. # is not printed over and over on the shell
  3004. if msg != '':
  3005. self.shell_message(msg)
  3006. def restore_toolbar_view(self):
  3007. """
  3008. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  3009. was saved in the defaults dictionary.
  3010. :return: None
  3011. """
  3012. tb = self.defaults["global_toolbar_view"]
  3013. if tb & 1:
  3014. self.ui.toolbarfile.setVisible(True)
  3015. else:
  3016. self.ui.toolbarfile.setVisible(False)
  3017. if tb & 2:
  3018. self.ui.toolbargeo.setVisible(True)
  3019. else:
  3020. self.ui.toolbargeo.setVisible(False)
  3021. if tb & 4:
  3022. self.ui.toolbarview.setVisible(True)
  3023. else:
  3024. self.ui.toolbarview.setVisible(False)
  3025. if tb & 8:
  3026. self.ui.toolbartools.setVisible(True)
  3027. else:
  3028. self.ui.toolbartools.setVisible(False)
  3029. if tb & 16:
  3030. self.ui.exc_edit_toolbar.setVisible(True)
  3031. else:
  3032. self.ui.exc_edit_toolbar.setVisible(False)
  3033. if tb & 32:
  3034. self.ui.geo_edit_toolbar.setVisible(True)
  3035. else:
  3036. self.ui.geo_edit_toolbar.setVisible(False)
  3037. if tb & 64:
  3038. self.ui.grb_edit_toolbar.setVisible(True)
  3039. else:
  3040. self.ui.grb_edit_toolbar.setVisible(False)
  3041. if tb & 128:
  3042. self.ui.snap_toolbar.setVisible(True)
  3043. else:
  3044. self.ui.snap_toolbar.setVisible(False)
  3045. if tb & 256:
  3046. self.ui.toolbarshell.setVisible(True)
  3047. else:
  3048. self.ui.toolbarshell.setVisible(False)
  3049. def load_defaults(self, filename):
  3050. """
  3051. Loads the aplication's default settings from current_defaults.FlatConfig into
  3052. ``self.defaults``.
  3053. :return: None
  3054. """
  3055. try:
  3056. f = open(self.data_path + "/" + filename + ".FlatConfig")
  3057. options = f.read()
  3058. f.close()
  3059. except IOError:
  3060. self.log.error("Could not load defaults file.")
  3061. self.inform.emit('[ERROR] %s' %
  3062. _("Could not load defaults file."))
  3063. # in case the defaults file can't be loaded, show all toolbars
  3064. self.defaults["global_toolbar_view"] = 511
  3065. return
  3066. try:
  3067. defaults = json.loads(options)
  3068. except:
  3069. # in case the defaults file can't be loaded, show all toolbars
  3070. self.defaults["global_toolbar_view"] = 511
  3071. e = sys.exc_info()[0]
  3072. App.log.error(str(e))
  3073. self.inform.emit('[ERROR] %s' %
  3074. _("Failed to parse defaults file."))
  3075. return
  3076. self.defaults.update(defaults)
  3077. log.debug("FlatCAM defaults loaded from: %s" % filename)
  3078. # restore the toolbar view
  3079. self.restore_toolbar_view()
  3080. def on_import_preferences(self):
  3081. """
  3082. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  3083. ``self.defaults``.
  3084. :return: None
  3085. """
  3086. self.report_usage("on_import_preferences")
  3087. App.log.debug("on_import_preferences()")
  3088. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  3089. try:
  3090. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3091. directory=self.data_path,
  3092. filter=filter_)
  3093. except TypeError:
  3094. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3095. filter=filter_)
  3096. filename = str(filename)
  3097. if filename == "":
  3098. self.inform.emit('[WARNING_NOTCL] %s' %
  3099. _("FlatCAM preferences import cancelled."))
  3100. else:
  3101. try:
  3102. f = open(filename)
  3103. options = f.read()
  3104. f.close()
  3105. except IOError:
  3106. self.log.error("Could not load defaults file.")
  3107. self.inform.emit('[ERROR_NOTCL] %s' %
  3108. _("Could not load defaults file."))
  3109. return
  3110. try:
  3111. defaults_from_file = json.loads(options)
  3112. except Exception as e:
  3113. e = sys.exc_info()[0]
  3114. App.log.error(str(e))
  3115. self.inform.emit('[ERROR_NOTCL] %s' %
  3116. _("Failed to parse defaults file."))
  3117. return
  3118. self.defaults.update(defaults_from_file)
  3119. self.on_preferences_edited()
  3120. self.inform.emit('[success] %s: %s' %
  3121. (_("Imported Defaults from"), filename))
  3122. def on_export_preferences(self):
  3123. """
  3124. Save the defaults dictionary to a file.
  3125. :return: None
  3126. """
  3127. self.report_usage("on_export_preferences")
  3128. App.log.debug("on_export_preferences()")
  3129. defaults_file_content = None
  3130. self.date = str(datetime.today()).rpartition('.')[0]
  3131. self.date = ''.join(c for c in self.date if c not in ':-')
  3132. self.date = self.date.replace(' ', '_')
  3133. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  3134. try:
  3135. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  3136. caption=_("Export FlatCAM Preferences"),
  3137. directory=self.data_path + '/preferences_' + self.date,
  3138. filter=filter__
  3139. )
  3140. except TypeError:
  3141. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  3142. filter=filter__)
  3143. filename = str(filename)
  3144. defaults_from_file = {}
  3145. if filename == "":
  3146. self.inform.emit('[WARNING_NOTCL] %s' %
  3147. _("FlatCAM preferences export cancelled."))
  3148. return
  3149. else:
  3150. try:
  3151. f = open(filename, 'w')
  3152. defaults_file_content = f.read()
  3153. f.close()
  3154. except PermissionError:
  3155. self.inform.emit('[WARNING] %s' %
  3156. _("Permission denied, saving not possible.\n"
  3157. "Most likely another app is holding the file open and not accessible."))
  3158. return
  3159. except IOError:
  3160. App.log.debug('Creating a new preferences file ...')
  3161. f = open(filename, 'w')
  3162. json.dump({}, f)
  3163. f.close()
  3164. except:
  3165. e = sys.exc_info()[0]
  3166. App.log.error("Could not load defaults file.")
  3167. App.log.error(str(e))
  3168. self.inform.emit('[ERROR_NOTCL] %s' %
  3169. _("Could not load preferences file."))
  3170. return
  3171. try:
  3172. defaults_from_file = json.loads(defaults_file_content)
  3173. except:
  3174. App.log.warning("Trying to read an empty Preferences file. Continue.")
  3175. # Update options
  3176. self.defaults_read_form()
  3177. defaults_from_file.update(self.defaults)
  3178. self.propagate_defaults(silent=True)
  3179. # Save update options
  3180. try:
  3181. f = open(filename, "w")
  3182. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  3183. f.close()
  3184. except:
  3185. self.inform.emit('[ERROR_NOTCL] %s' %
  3186. _("Failed to write defaults to file."))
  3187. return
  3188. if self.defaults["global_open_style"] is False:
  3189. self.file_opened.emit("preferences", filename)
  3190. self.file_saved.emit("preferences", filename)
  3191. self.inform.emit('[success] %s: %s' %
  3192. (_("Exported preferences to"), filename))
  3193. def on_preferences_open_folder(self):
  3194. """
  3195. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  3196. :return: None
  3197. """
  3198. self.report_usage("on_preferences_open_folder()")
  3199. if sys.platform == 'win32':
  3200. subprocess.Popen('explorer %s' % self.data_path)
  3201. elif sys.platform == 'darwin':
  3202. os.system('open "%s"' % self.data_path)
  3203. else:
  3204. subprocess.Popen(['xdg-open', self.data_path])
  3205. self.inform.emit('[success] %s' %
  3206. _("FlatCAM Preferences Folder opened."))
  3207. def save_geometry(self, x, y, width, height, notebook_width):
  3208. """
  3209. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  3210. launch of the application.
  3211. :param x: X position of the main window
  3212. :param y: Y position of the main window
  3213. :param width: width of the main window
  3214. :param height: height of the main window
  3215. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  3216. :return: None
  3217. """
  3218. self.defaults["global_def_win_x"] = x
  3219. self.defaults["global_def_win_y"] = y
  3220. self.defaults["global_def_win_w"] = width
  3221. self.defaults["global_def_win_h"] = height
  3222. self.defaults["global_def_notebook_width"] = notebook_width
  3223. self.save_defaults()
  3224. def restore_main_win_geom(self):
  3225. try:
  3226. self.ui.setGeometry(self.defaults["global_def_win_x"],
  3227. self.defaults["global_def_win_y"],
  3228. self.defaults["global_def_win_w"],
  3229. self.defaults["global_def_win_h"])
  3230. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  3231. except KeyError as e:
  3232. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  3233. def message_dialog(self, title, message, kind="info"):
  3234. """
  3235. Builds and show a custom QMessageBox to be used in FlatCAM.
  3236. :param title: title of the QMessageBox
  3237. :param message: message to be displayed
  3238. :param kind: type of QMessageBox; will display a specific icon.
  3239. :return:
  3240. """
  3241. icon = {"info": QtWidgets.QMessageBox.Information,
  3242. "warning": QtWidgets.QMessageBox.Warning,
  3243. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3244. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  3245. dlg.setText(message)
  3246. dlg.exec_()
  3247. def register_recent(self, kind, filename):
  3248. """
  3249. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  3250. dictionary.
  3251. :param kind: type of file that was opened
  3252. :param filename: the path and file name for the file that was opened
  3253. :return:
  3254. """
  3255. self.log.debug("register_recent()")
  3256. self.log.debug(" %s" % kind)
  3257. self.log.debug(" %s" % filename)
  3258. record = {'kind': str(kind), 'filename': str(filename)}
  3259. if record in self.recent:
  3260. return
  3261. if record in self.recent_projects:
  3262. return
  3263. if record['kind'] == 'project':
  3264. self.recent_projects.insert(0, record)
  3265. else:
  3266. self.recent.insert(0, record)
  3267. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3268. self.recent.pop()
  3269. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3270. self.recent_projects.pop()
  3271. try:
  3272. f = open(self.data_path + '/recent.json', 'w')
  3273. except IOError:
  3274. App.log.error("Failed to open recent items file for writing.")
  3275. self.inform.emit('[ERROR_NOTCL] %s' %
  3276. _('Failed to open recent files file for writing.'))
  3277. return
  3278. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3279. f.close()
  3280. try:
  3281. fp = open(self.data_path + '/recent_projects.json', 'w')
  3282. except IOError:
  3283. App.log.error("Failed to open recent items file for writing.")
  3284. self.inform.emit('[ERROR_NOTCL] %s' %
  3285. _('Failed to open recent projects file for writing.'))
  3286. return
  3287. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3288. fp.close()
  3289. # Re-build the recent items menu
  3290. self.setup_recent_items()
  3291. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3292. """
  3293. Creates a new specialized FlatCAMObj and attaches it to the application,
  3294. this is, updates the GUI accordingly, any other records and plots it.
  3295. This method is thread-safe.
  3296. Notes:
  3297. * If the name is in use, the self.collection will modify it
  3298. when appending it to the collection. There is no need to handle
  3299. name conflicts here.
  3300. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3301. :type kind: str
  3302. :param name: Name for the object.
  3303. :type name: str
  3304. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3305. The function is called with 2 parameters: the new object and the App instance.
  3306. :type initialize: function
  3307. :param active:
  3308. :param fit:
  3309. :param plot: If to plot the resulting object
  3310. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3311. self.colleaction
  3312. :return: None
  3313. :rtype: None
  3314. """
  3315. App.log.debug("new_object()")
  3316. obj_plot = plot
  3317. obj_autoselected = autoselected
  3318. t0 = time.time() # Debug
  3319. # ## Create object
  3320. classdict = {
  3321. "gerber": FlatCAMGerber,
  3322. "excellon": FlatCAMExcellon,
  3323. "cncjob": FlatCAMCNCjob,
  3324. "geometry": FlatCAMGeometry
  3325. }
  3326. App.log.debug("Calling object constructor...")
  3327. obj = classdict[kind](name)
  3328. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3329. # Set options from "Project options" form
  3330. self.options_read_form()
  3331. # IMPORTANT
  3332. # The key names in defaults and options dictionary's are not random:
  3333. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3334. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  3335. # the options from project options form into the self.options. After that, below, depending on the type of
  3336. # object that is created, it will strip the name of the object and the underline (if the original key was
  3337. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3338. # "toolchange"
  3339. for option in self.options:
  3340. if option.find(kind + "_") == 0:
  3341. oname = option[len(kind) + 1:]
  3342. obj.options[oname] = self.options[option]
  3343. obj.isHovering = False
  3344. obj.notHovering = True
  3345. # Initialize as per user request
  3346. # User must take care to implement initialize
  3347. # in a thread-safe way as is is likely that we
  3348. # have been invoked in a separate thread.
  3349. t1 = time.time()
  3350. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3351. try:
  3352. return_value = initialize(obj, self)
  3353. except Exception as e:
  3354. msg = '[ERROR_NOTCL] %s' % \
  3355. _("An internal error has ocurred. See shell.\n")
  3356. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3357. msg += traceback.format_exc()
  3358. self.inform.emit(msg)
  3359. # if str(e) == "Empty Geometry":
  3360. # self.inform.emit("[ERROR_NOTCL] )
  3361. # else:
  3362. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  3363. return "fail"
  3364. t2 = time.time()
  3365. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3366. if return_value == 'fail':
  3367. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3368. return "fail"
  3369. # Check units and convert if necessary
  3370. # This condition CAN be true because initialize() can change obj.units
  3371. if self.options["units"].upper() != obj.units.upper():
  3372. self.inform.emit('%s: %s' %
  3373. (_("Converting units to "), self.options["units"]))
  3374. obj.convert_units(self.options["units"])
  3375. t3 = time.time()
  3376. self.log.debug("%f seconds converting units." % (t3 - t2))
  3377. # Create the bounding box for the object and then add the results to the obj.options
  3378. try:
  3379. xmin, ymin, xmax, ymax = obj.bounds()
  3380. obj.options['xmin'] = xmin
  3381. obj.options['ymin'] = ymin
  3382. obj.options['xmax'] = xmax
  3383. obj.options['ymax'] = ymax
  3384. except Exception as e:
  3385. log.warning("The object has no bounds properties. %s" % str(e))
  3386. return "fail"
  3387. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3388. # Move the object to the main thread and let the app know that it is available.
  3389. obj.moveToThread(self.main_thread)
  3390. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3391. return obj
  3392. def new_excellon_object(self):
  3393. """
  3394. Creates a new, blank Excellon object.
  3395. :return: None
  3396. """
  3397. self.report_usage("new_excellon_object()")
  3398. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3399. def new_geometry_object(self):
  3400. """
  3401. Creates a new, blank and single-tool Geometry object.
  3402. :return: None
  3403. """
  3404. self.report_usage("new_geometry_object()")
  3405. def initialize(obj, self):
  3406. obj.multitool = False
  3407. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3408. def new_gerber_object(self):
  3409. """
  3410. Creates a new, blank Gerber object.
  3411. :return: None
  3412. """
  3413. self.report_usage("new_gerber_object()")
  3414. def initialize(grb_obj, self):
  3415. grb_obj.multitool = False
  3416. grb_obj.source_file = []
  3417. grb_obj.multigeo = False
  3418. grb_obj.follow = False
  3419. grb_obj.apertures = {}
  3420. grb_obj.solid_geometry = []
  3421. try:
  3422. grb_obj.options['xmin'] = 0
  3423. grb_obj.options['ymin'] = 0
  3424. grb_obj.options['xmax'] = 0
  3425. grb_obj.options['ymax'] = 0
  3426. except KeyError:
  3427. pass
  3428. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3429. def on_object_created(self, obj, plot, autoselect):
  3430. """
  3431. Event callback for object creation.
  3432. It will add the new object to the collection. After that it will plot the object in a threaded way
  3433. :param obj: The newly created FlatCAM object.
  3434. :param plot: if the newly create object t obe plotted
  3435. :param autoselect: if the newly created object to be autoselected after creation
  3436. :return: None
  3437. """
  3438. t0 = time.time() # DEBUG
  3439. self.log.debug("on_object_created()")
  3440. # The Collection might change the name if there is a collision
  3441. self.collection.append(obj)
  3442. # after adding the object to the collection always update the list of objects that are in the collection
  3443. self.all_objects_list = self.collection.get_list()
  3444. # self.inform.emit('[selected] %s created & selected: %s' %
  3445. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3446. if obj.kind == 'gerber':
  3447. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3448. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3449. elif obj.kind == 'excellon':
  3450. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3451. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3452. elif obj.kind == 'cncjob':
  3453. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3454. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3455. elif obj.kind == 'geometry':
  3456. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3457. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3458. # update the SHELL auto-completer model with the name of the new object
  3459. self.myKeywords.append(obj.options['name'])
  3460. self.shell._edit.set_model_data(self.myKeywords)
  3461. self.ui.code_editor.set_model_data(self.myKeywords)
  3462. if autoselect:
  3463. # select the just opened object but deselect the previous ones
  3464. self.collection.set_all_inactive()
  3465. self.collection.set_active(obj.options["name"])
  3466. else:
  3467. self.collection.set_all_inactive()
  3468. # here it is done the object plotting
  3469. def worker_task(t_obj):
  3470. with self.proc_container.new(_("Plotting")):
  3471. if isinstance(t_obj, FlatCAMCNCjob):
  3472. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3473. else:
  3474. t_obj.plot()
  3475. t1 = time.time() # DEBUG
  3476. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3477. self.object_plotted.emit(t_obj)
  3478. # Send to worker
  3479. # self.worker.add_task(worker_task, [self])
  3480. if plot is True:
  3481. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3482. def on_object_changed(self, obj):
  3483. """
  3484. Called whenever the geometry of the object was changed in some way.
  3485. This require the update of it's bounding values so it can be the selected on canvas.
  3486. Update the bounding box data from obj.options
  3487. :param obj: the object that was changed
  3488. :return: None
  3489. """
  3490. xmin, ymin, xmax, ymax = obj.bounds()
  3491. obj.options['xmin'] = xmin
  3492. obj.options['ymin'] = ymin
  3493. obj.options['xmax'] = xmax
  3494. obj.options['ymax'] = ymax
  3495. log.debug("Object changed, updating the bounding box data on self.options")
  3496. # delete the old selection shape
  3497. self.delete_selection_shape()
  3498. self.should_we_save = True
  3499. def on_object_plotted(self, obj):
  3500. """
  3501. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3502. :param obj: object to be fit into view
  3503. :return: None
  3504. """
  3505. self.on_zoom_fit(None)
  3506. def options_read_form(self):
  3507. """
  3508. Same as it's equivalent from the defaults.
  3509. self.options use to store the preferences per project. No longer used.
  3510. :return: None
  3511. """
  3512. for option in self.options_form_fields:
  3513. self.options[option] = self.options_form_fields[option].get_value()
  3514. def options_write_form(self):
  3515. """
  3516. Same as it's equivalent from the defaults.
  3517. self.options use to store the preferences per project. No longer used.
  3518. :return: None
  3519. """
  3520. for option in self.options:
  3521. self.options_write_form_field(option)
  3522. def options_write_form_field(self, field):
  3523. """
  3524. Same as it's equivalent from the defaults.
  3525. self.options use to store the preferences per project. No longer used.
  3526. :return: None
  3527. """
  3528. try:
  3529. self.options_form_fields[field].set_value(self.options[field])
  3530. except KeyError:
  3531. # Changed from error to debug. This allows to have data stored
  3532. # which is not user-editable.
  3533. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  3534. pass
  3535. def on_about(self):
  3536. """
  3537. Displays the "about" dialog found in the Menu --> Help.
  3538. :return: None
  3539. """
  3540. self.report_usage("on_about")
  3541. version = self.version
  3542. version_date = self.version_date
  3543. beta = self.beta
  3544. class AboutDialog(QtWidgets.QDialog):
  3545. def __init__(self, parent=None):
  3546. QtWidgets.QDialog.__init__(self, parent)
  3547. # Icon and title
  3548. self.setWindowIcon(parent.app_icon)
  3549. self.setWindowTitle(_("About FlatCAM"))
  3550. self.resize(600, 200)
  3551. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3552. # self.setStyleSheet(
  3553. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3554. # "background-attachment: fixed"
  3555. # )
  3556. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3557. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3558. # palette = QtGui.QPalette()
  3559. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3560. # self.setPalette(palette)
  3561. logo = QtWidgets.QLabel()
  3562. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3563. title = QtWidgets.QLabel(
  3564. "<font size=8><B>FlatCAM</B></font><BR>"
  3565. "{title}<BR>"
  3566. "<BR>"
  3567. "<BR>"
  3568. # "<B>{devel}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3569. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3570. # "<b>{down}</B> area &nbsp;&nbsp;&nbsp;&nbsp;"
  3571. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3572. # "<b> {issue}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3573. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3574. "<B>{issue}</B></a><BR>".format(
  3575. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3576. devel=_("Development"),
  3577. down=_("DOWNLOAD"),
  3578. issue=_("Issue tracker"))
  3579. )
  3580. title.setOpenExternalLinks(True)
  3581. closebtn = QtWidgets.QPushButton(_("Close"))
  3582. tab_widget = QtWidgets.QTabWidget()
  3583. description_label = QtWidgets.QLabel(
  3584. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3585. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3586. version=version,
  3587. beta=('BETA' if beta else ''),
  3588. date=version_date,
  3589. arch=platform.architecture()[0])
  3590. )
  3591. description_label.setOpenExternalLinks(True)
  3592. license_label = QtWidgets.QLabel(
  3593. _(
  3594. '(c) Copyright 2014 Juan Pablo Caram.\n\n'
  3595. 'Licensed under the MIT license:\n'
  3596. 'http://www.opensource.org/licenses/mit-license.php\n\n'
  3597. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3598. 'of this software and associated documentation files (the "Software"), to deal\n'
  3599. 'in the Software without restriction, including without limitation the rights\n'
  3600. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3601. 'copies of the Software, and to permit persons to whom the Software is\n'
  3602. ' furnished to do so, subject to the following conditions:\n\n'
  3603. 'The above copyright notice and this permission notice shall be included in\n'
  3604. 'all copies or substantial portions of the Software.\n\n'
  3605. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3606. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3607. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3608. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3609. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3610. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3611. 'THE SOFTWARE.'
  3612. )
  3613. )
  3614. license_label.setOpenExternalLinks(True)
  3615. # layouts
  3616. layout1 = QtWidgets.QVBoxLayout()
  3617. layout1_1 = QtWidgets.QHBoxLayout()
  3618. layout1_2 = QtWidgets.QHBoxLayout()
  3619. layout2 = QtWidgets.QHBoxLayout()
  3620. layout3 = QtWidgets.QHBoxLayout()
  3621. self.setLayout(layout1)
  3622. layout1.addLayout(layout1_1)
  3623. layout1.addLayout(layout1_2)
  3624. layout1.addLayout(layout2)
  3625. layout1.addLayout(layout3)
  3626. layout1_1.addStretch()
  3627. layout1_1.addWidget(description_label)
  3628. layout1_2.addWidget(tab_widget)
  3629. self.splash_tab = QtWidgets.QWidget()
  3630. self.splash_tab.setObjectName("splash_about")
  3631. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3632. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3633. tab_widget.addTab(self.splash_tab, _("Splash"))
  3634. self.programmmers_tab = QtWidgets.QWidget()
  3635. self.programmmers_tab.setObjectName("programmers_about")
  3636. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3637. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3638. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3639. self.translators_tab = QtWidgets.QWidget()
  3640. self.translators_tab.setObjectName("translators_about")
  3641. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3642. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3643. tab_widget.addTab(self.translators_tab, _("Translators"))
  3644. self.license_tab = QtWidgets.QWidget()
  3645. self.license_tab.setObjectName("license_about")
  3646. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3647. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3648. tab_widget.addTab(self.license_tab, _("License"))
  3649. self.splash_tab_layout.addWidget(logo, stretch=0)
  3650. self.splash_tab_layout.addWidget(title, stretch=1)
  3651. pal = QtGui.QPalette()
  3652. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3653. self.prog_form_lay = QtWidgets.QFormLayout()
  3654. self.prog_form_lay.setHorizontalSpacing(20)
  3655. prog_widget = QtWidgets.QWidget()
  3656. prog_widget.setLayout(self.prog_form_lay)
  3657. prog_scroll = QtWidgets.QScrollArea()
  3658. prog_scroll.setWidget(prog_widget)
  3659. prog_scroll.setWidgetResizable(True)
  3660. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3661. prog_scroll.setPalette(pal)
  3662. self.programmmers_tab_layout.addWidget(prog_scroll)
  3663. self.prog_form_lay.addRow(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")),
  3664. QtWidgets.QLabel('<b>%s</b>' % _("Status")))
  3665. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Juan Pablo Caram"),
  3666. QtWidgets.QLabel('%s' % _("Program Author")))
  3667. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Denis Hayrullin"))
  3668. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Kamil Sopko"))
  3669. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marius Stanciu"),
  3670. QtWidgets.QLabel('%s' % _("Maintainer >=2019")))
  3671. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3672. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Alexandru Lazar"))
  3673. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Matthieu Berthomé"))
  3674. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Evans"))
  3675. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Victor Benso"))
  3676. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3677. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Barnaby Walters"))
  3678. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"))
  3679. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lei Zheng"))
  3680. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marco A Quezada"))
  3681. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3682. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Cedric Dussud"))
  3683. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Chris Hemingway"))
  3684. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Damian Wrobel"))
  3685. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Daniel Sallin"))
  3686. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3687. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Bruno Vunderl"))
  3688. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Gonzalo Lopez"))
  3689. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jakob Staudt"))
  3690. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Smith"))
  3691. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3692. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lubos Medovarsky"))
  3693. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Steve Martina"))
  3694. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Thomas Duffin"))
  3695. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3696. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Idechix"))
  3697. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@SM"))
  3698. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@grbf"))
  3699. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Symonty"))
  3700. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@mgix"))
  3701. self.translator_grid_lay = QtWidgets.QGridLayout()
  3702. # trans_widget = QtWidgets.QWidget()
  3703. # trans_widget.setLayout(self.translator_grid_lay)
  3704. # self.translators_tab_layout.addWidget(trans_widget)
  3705. # self.translators_tab_layout.addStretch()
  3706. trans_widget = QtWidgets.QWidget()
  3707. trans_widget.setLayout(self.translator_grid_lay)
  3708. trans_scroll = QtWidgets.QScrollArea()
  3709. trans_scroll.setWidget(trans_widget)
  3710. trans_scroll.setWidgetResizable(True)
  3711. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3712. trans_scroll.setPalette(pal)
  3713. self.translators_tab_layout.addWidget(trans_scroll)
  3714. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  3715. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  3716. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3717. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Brasilian - Portuguese"), 1, 0)
  3718. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  3719. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 1, 2)
  3720. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  3721. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 2, 1)
  3722. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 2)
  3723. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  3724. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 3, 1)
  3725. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  3726. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  3727. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  3728. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  3729. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  3730. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  3731. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 2)
  3732. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  3733. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 6, 1)
  3734. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 2)
  3735. self.translator_grid_lay.setColumnStretch(0, 0)
  3736. self.translators_tab_layout.addStretch()
  3737. self.license_tab_layout.addWidget(license_label)
  3738. self.license_tab_layout.addStretch()
  3739. layout3.addStretch()
  3740. layout3.addWidget(closebtn)
  3741. closebtn.clicked.connect(self.accept)
  3742. AboutDialog(self.ui).exec_()
  3743. def on_file_savedefaults(self):
  3744. """
  3745. Callback for menu item File->Save Defaults. Saves application default options
  3746. ``self.defaults`` to current_defaults.FlatConfig.
  3747. :return: None
  3748. """
  3749. self.save_defaults()
  3750. # def on_app_exit(self):
  3751. # self.report_usage("on_app_exit()")
  3752. #
  3753. # if self.collection.get_list():
  3754. # msgbox = QtWidgets.QMessageBox()
  3755. # # msgbox.setText("<B>Save changes ...</B>")
  3756. # msgbox.setText("There are files/objects opened in FlatCAM. "
  3757. # "\n"
  3758. # "Do you want to Save the project?")
  3759. # msgbox.setWindowTitle("Save changes")
  3760. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3761. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  3762. # QtWidgets.QMessageBox.Cancel)
  3763. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  3764. #
  3765. # response = msgbox.exec_()
  3766. #
  3767. # if response == QtWidgets.QMessageBox.Yes:
  3768. # self.on_file_saveprojectas(thread=False)
  3769. # elif response == QtWidgets.QMessageBox.Cancel:
  3770. # return
  3771. # self.save_defaults()
  3772. # else:
  3773. # self.save_defaults()
  3774. # log.debug("Application defaults saved ... Exit event.")
  3775. # QtWidgets.qApp.quit()
  3776. def save_defaults(self, silent=False, data_path=None, first_time=False):
  3777. """
  3778. Saves application default options
  3779. ``self.defaults`` to current_defaults.FlatConfig file.
  3780. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  3781. used at the next launch of the application.
  3782. :param silent: whether to display a message in status bar or not; boolean
  3783. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  3784. When the application is portable it should be a mobile location.
  3785. :return: None
  3786. """
  3787. self.report_usage("save_defaults")
  3788. if data_path is None:
  3789. data_path = self.data_path
  3790. # Read options from file
  3791. try:
  3792. f = open(data_path + "/current_defaults.FlatConfig")
  3793. defaults_file_content = f.read()
  3794. f.close()
  3795. except:
  3796. e = sys.exc_info()[0]
  3797. App.log.error("Could not load defaults file.")
  3798. App.log.error(str(e))
  3799. self.inform.emit('[ERROR_NOTCL] %s' %
  3800. _("Could not load defaults file."))
  3801. return
  3802. try:
  3803. defaults = json.loads(defaults_file_content)
  3804. except:
  3805. e = sys.exc_info()[0]
  3806. App.log.error("Failed to parse defaults file.")
  3807. App.log.error(str(e))
  3808. self.inform.emit('[ERROR_NOTCL] %s' %
  3809. _("Failed to parse defaults file."))
  3810. return
  3811. # Update options
  3812. self.defaults_read_form()
  3813. defaults.update(self.defaults)
  3814. self.propagate_defaults(silent=True)
  3815. # Save the toolbar view
  3816. tb_status = 0
  3817. if self.ui.toolbarfile.isVisible():
  3818. tb_status += 1
  3819. if self.ui.toolbargeo.isVisible():
  3820. tb_status += 2
  3821. if self.ui.toolbarview.isVisible():
  3822. tb_status += 4
  3823. if self.ui.toolbartools.isVisible():
  3824. tb_status += 8
  3825. if self.ui.exc_edit_toolbar.isVisible():
  3826. tb_status += 16
  3827. if self.ui.geo_edit_toolbar.isVisible():
  3828. tb_status += 32
  3829. if self.ui.grb_edit_toolbar.isVisible():
  3830. tb_status += 64
  3831. if self.ui.snap_toolbar.isVisible():
  3832. tb_status += 128
  3833. if self.ui.toolbarshell.isVisible():
  3834. tb_status += 256
  3835. if first_time is False:
  3836. self.defaults["global_toolbar_view"] = tb_status
  3837. # Save update options
  3838. try:
  3839. f = open(data_path + "/current_defaults.FlatConfig", "w")
  3840. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  3841. f.close()
  3842. except:
  3843. self.inform.emit('[ERROR_NOTCL] %s' %
  3844. _("Failed to write defaults to file."))
  3845. return
  3846. if not silent:
  3847. self.inform.emit('[success] %s' %
  3848. _("Preferences saved."))
  3849. def save_factory_defaults(self, silent=False, data_path=None):
  3850. """
  3851. Saves application factory default options
  3852. ``self.defaults`` to factory_defaults.FlatConfig.
  3853. It's a one time job done just after the first install.
  3854. :param silent: whether to display a message in status bar or not; boolean
  3855. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  3856. When the application is portable it should be a mobile location.
  3857. :return: None
  3858. """
  3859. self.report_usage("save_factory_defaults")
  3860. if data_path is None:
  3861. data_path = self.data_path
  3862. # Read options from file
  3863. try:
  3864. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  3865. factory_defaults_file_content = f_f_def.read()
  3866. f_f_def.close()
  3867. except:
  3868. e = sys.exc_info()[0]
  3869. App.log.error("Could not load factory defaults file.")
  3870. App.log.error(str(e))
  3871. self.inform.emit('[ERROR_NOTCL] %s' %
  3872. _("Could not load factory defaults file."))
  3873. return
  3874. try:
  3875. factory_defaults = json.loads(factory_defaults_file_content)
  3876. except:
  3877. e = sys.exc_info()[0]
  3878. App.log.error("Failed to parse factory defaults file.")
  3879. App.log.error(str(e))
  3880. self.inform.emit('[ERROR_NOTCL] %s' %
  3881. _("Failed to parse factory defaults file."))
  3882. return
  3883. # Update options
  3884. self.defaults_read_form()
  3885. factory_defaults.update(self.defaults)
  3886. self.propagate_defaults(silent=True)
  3887. # Save update options
  3888. try:
  3889. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  3890. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3891. f_f_def_s.close()
  3892. except:
  3893. self.inform.emit('[ERROR_NOTCL] %s' %
  3894. _("Failed to write factory defaults to file."))
  3895. return
  3896. if silent is False:
  3897. self.inform.emit(_("Factory defaults saved."))
  3898. def final_save(self):
  3899. """
  3900. Callback for doing a preferences save to file whenever the application is about to quit.
  3901. If the project has changes, it will ask the user to save the project.
  3902. :return: None
  3903. """
  3904. if self.save_in_progress:
  3905. self.inform.emit('[WARNING_NOTCL] %s' %
  3906. _("Application is saving the project. Please wait ..."))
  3907. return
  3908. if self.should_we_save and self.collection.get_list():
  3909. msgbox = QtWidgets.QMessageBox()
  3910. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  3911. "\n"
  3912. "Do you want to Save the project?"))
  3913. msgbox.setWindowTitle(_("Save changes"))
  3914. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3915. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  3916. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  3917. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3918. msgbox.setDefaultButton(bt_yes)
  3919. msgbox.exec_()
  3920. response = msgbox.clickedButton()
  3921. if response == bt_yes:
  3922. try:
  3923. self.trayIcon.hide()
  3924. except:
  3925. pass
  3926. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  3927. elif response == bt_no:
  3928. try:
  3929. self.trayIcon.hide()
  3930. except:
  3931. pass
  3932. self.quit_application()
  3933. elif response == bt_cancel:
  3934. return
  3935. else:
  3936. try:
  3937. self.trayIcon.hide()
  3938. except:
  3939. pass
  3940. self.quit_application()
  3941. def quit_application(self):
  3942. """
  3943. Called (as a pyslot or not) when the application is quit.
  3944. :return: None
  3945. """
  3946. self.save_defaults()
  3947. log.debug("App.final_save() --> App Defaults saved.")
  3948. if self.cmd_line_headless != 1:
  3949. # save app state to file
  3950. settings = QSettings("Open Source", "FlatCAM")
  3951. settings.setValue('saved_gui_state', self.ui.saveState())
  3952. settings.setValue('maximized_gui', self.ui.isMaximized())
  3953. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  3954. settings.setValue(
  3955. 'notebook_font_size',
  3956. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  3957. )
  3958. settings.setValue('axis_font_size',
  3959. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value())
  3960. settings.setValue(
  3961. 'textbox_font_size',
  3962. self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  3963. )
  3964. settings.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  3965. # This will write the setting to the platform specific storage.
  3966. del settings
  3967. log.debug("App.final_save() --> App UI state saved.")
  3968. QtWidgets.qApp.quit()
  3969. def on_portable_checked(self, state):
  3970. """
  3971. Callback called when the checkbox in Preferences GUI is checked.
  3972. It will set the application as portable by creating the preferences and recent files in the
  3973. 'config' folder found in the FlatCAM installation folder.
  3974. :param state: boolean, the state of the checkbox when clicked/checked
  3975. :return:
  3976. """
  3977. line_no = 0
  3978. data = None
  3979. if sys.platform != 'win32':
  3980. # this won't work in Linux or MacOS
  3981. return
  3982. # test if the app was frozen and choose the path for the configuration file
  3983. if getattr(sys, "frozen", False) is True:
  3984. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  3985. else:
  3986. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  3987. config_file = current_data_path + '\\configuration.txt'
  3988. try:
  3989. with open(config_file, 'r') as f:
  3990. try:
  3991. data = f.readlines()
  3992. except Exception as e:
  3993. log.debug('App.__init__() -->%s' % str(e))
  3994. return
  3995. except FileNotFoundError:
  3996. pass
  3997. for line in data:
  3998. line = line.strip('\n')
  3999. param = str(line).rpartition('=')
  4000. if param[0] == 'portable':
  4001. break
  4002. line_no += 1
  4003. if state:
  4004. data[line_no] = 'portable=True\n'
  4005. # create the new defauults files
  4006. # create current_defaults.FlatConfig file if there is none
  4007. try:
  4008. f = open(current_data_path + '/current_defaults.FlatConfig')
  4009. f.close()
  4010. except IOError:
  4011. App.log.debug('Creating empty current_defaults.FlatConfig')
  4012. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  4013. json.dump({}, f)
  4014. f.close()
  4015. # create factory_defaults.FlatConfig file if there is none
  4016. try:
  4017. f = open(current_data_path + '/factory_defaults.FlatConfig')
  4018. f.close()
  4019. except IOError:
  4020. App.log.debug('Creating empty factory_defaults.FlatConfig')
  4021. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  4022. json.dump({}, f)
  4023. f.close()
  4024. try:
  4025. f = open(current_data_path + '/recent.json')
  4026. f.close()
  4027. except IOError:
  4028. App.log.debug('Creating empty recent.json')
  4029. f = open(current_data_path + '/recent.json', 'w')
  4030. json.dump([], f)
  4031. f.close()
  4032. try:
  4033. fp = open(current_data_path + '/recent_projects.json')
  4034. fp.close()
  4035. except IOError:
  4036. App.log.debug('Creating empty recent_projects.json')
  4037. fp = open(current_data_path + '/recent_projects.json', 'w')
  4038. json.dump([], fp)
  4039. fp.close()
  4040. # save the current defaults to the new defaults file
  4041. self.save_defaults(silent=True, data_path=current_data_path)
  4042. self.save_factory_defaults(silent=True, data_path=current_data_path)
  4043. else:
  4044. data[line_no] = 'portable=False\n'
  4045. with open(config_file, 'w') as f:
  4046. f.writelines(data)
  4047. def on_toggle_shell(self):
  4048. """
  4049. Toggle shell: if is visible close it, if it is closed then open it
  4050. :return:
  4051. """
  4052. self.report_usage("on_toggle_shell()")
  4053. if self.ui.shell_dock.isVisible():
  4054. self.ui.shell_dock.hide()
  4055. else:
  4056. self.ui.shell_dock.show()
  4057. def on_register_files(self, obj_type=None):
  4058. """
  4059. Called whenever there is a need to register file extensions with FlatCAM.
  4060. Works only in Windows and should be called only when FlatCAM is run in Windows.
  4061. :param obj_type: the type of object to be register for.
  4062. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  4063. :return: None
  4064. """
  4065. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  4066. new_reg_path = 'Software\\Classes\\'
  4067. # find if the current user is admin
  4068. try:
  4069. is_admin = os.getuid() == 0
  4070. except AttributeError:
  4071. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  4072. if is_admin is True:
  4073. root_path = winreg.HKEY_LOCAL_MACHINE
  4074. else:
  4075. root_path = winreg.HKEY_CURRENT_USER
  4076. # create the keys
  4077. def set_reg(name, root_path, new_reg_path, value):
  4078. try:
  4079. winreg.CreateKey(root_path, new_reg_path)
  4080. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  4081. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  4082. return True
  4083. except WindowsError:
  4084. return False
  4085. # delete key in registry
  4086. def delete_reg(root_path, reg_path, key_to_del):
  4087. key_to_del_path = reg_path + key_to_del
  4088. try:
  4089. winreg.DeleteKey(root_path, key_to_del_path)
  4090. return True
  4091. except WindowsError:
  4092. return False
  4093. if obj_type is None or obj_type == 'excellon':
  4094. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4095. exc_list = [x for x in exc_list if x != '']
  4096. # register all keys in the Preferences window
  4097. for ext in exc_list:
  4098. new_k = new_reg_path + '.%s' % ext
  4099. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4100. # and unregister those that are no longer in the Preferences windows but are in the file
  4101. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  4102. if ext not in exc_list:
  4103. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4104. # now write the updated extensions to the self.defaults
  4105. # new_ext = ''
  4106. # for ext in exc_list:
  4107. # new_ext = new_ext + ext + ', '
  4108. # self.defaults["fa_excellon"] = new_ext
  4109. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  4110. if obj_type is None or obj_type == 'gcode':
  4111. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4112. gco_list = [x for x in gco_list if x != '']
  4113. # register all keys in the Preferences window
  4114. for ext in gco_list:
  4115. new_k = new_reg_path + '.%s' % ext
  4116. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4117. # and unregister those that are no longer in the Preferences windows but are in the file
  4118. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  4119. if ext not in gco_list:
  4120. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4121. # now write the updated extensions to the self.defaults
  4122. # new_ext = ''
  4123. # for ext in gco_list:
  4124. # new_ext = new_ext + ext + ', '
  4125. # self.defaults["fa_gcode"] = new_ext
  4126. self.inform.emit('[success] %s' %
  4127. _("Selected GCode file extensions registered with FlatCAM."))
  4128. if obj_type is None or obj_type == 'gerber':
  4129. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4130. grb_list = [x for x in grb_list if x != '']
  4131. # register all keys in the Preferences window
  4132. for ext in grb_list:
  4133. new_k = new_reg_path + '.%s' % ext
  4134. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4135. # and unregister those that are no longer in the Preferences windows but are in the file
  4136. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  4137. if ext not in grb_list:
  4138. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4139. # now write the updated extensions to the self.defaults
  4140. # new_ext = ''
  4141. # for ext in grb_list:
  4142. # new_ext = new_ext + ext + ', '
  4143. # self.defaults["fa_gerber"] = new_ext
  4144. self.inform.emit('[success] %s' %
  4145. _("Selected Gerber file extensions registered with FlatCAM."))
  4146. def add_extension(self, ext_type):
  4147. if ext_type == 'excellon':
  4148. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4149. if new_ext == '':
  4150. return
  4151. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4152. if new_ext in old_val:
  4153. return
  4154. old_val.append(new_ext)
  4155. old_val.sort()
  4156. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4157. if ext_type == 'gcode':
  4158. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4159. if new_ext == '':
  4160. return
  4161. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4162. if new_ext in old_val:
  4163. return
  4164. old_val.append(new_ext)
  4165. old_val.sort()
  4166. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4167. if ext_type == 'gerber':
  4168. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4169. if new_ext == '':
  4170. return
  4171. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4172. if new_ext in old_val:
  4173. return
  4174. old_val.append(new_ext)
  4175. old_val.sort()
  4176. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4177. if ext_type == 'keyword':
  4178. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4179. if new_kw == '':
  4180. return
  4181. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4182. if new_kw in old_val:
  4183. return
  4184. old_val.append(new_kw)
  4185. old_val.sort()
  4186. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4187. # update the self.myKeywords so the model is updated
  4188. self.autocomplete_kw_list = \
  4189. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4190. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4191. self.shell._edit.set_model_data(self.myKeywords)
  4192. self.ui.code_editor.set_model_data(self.myKeywords)
  4193. def del_extension(self, ext_type):
  4194. if ext_type == 'excellon':
  4195. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4196. if new_ext == '':
  4197. return
  4198. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4199. if new_ext not in old_val:
  4200. return
  4201. old_val.remove(new_ext)
  4202. old_val.sort()
  4203. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4204. if ext_type == 'gcode':
  4205. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4206. if new_ext == '':
  4207. return
  4208. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4209. if new_ext not in old_val:
  4210. return
  4211. old_val.remove(new_ext)
  4212. old_val.sort()
  4213. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4214. if ext_type == 'gerber':
  4215. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4216. if new_ext == '':
  4217. return
  4218. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4219. if new_ext not in old_val:
  4220. return
  4221. old_val.remove(new_ext)
  4222. old_val.sort()
  4223. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4224. if ext_type == 'keyword':
  4225. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4226. if new_kw == '':
  4227. return
  4228. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4229. if new_kw not in old_val:
  4230. return
  4231. old_val.remove(new_kw)
  4232. old_val.sort()
  4233. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4234. # update the self.myKeywords so the model is updated
  4235. self.autocomplete_kw_list = \
  4236. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4237. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4238. self.shell._edit.set_model_data(self.myKeywords)
  4239. self.ui.code_editor.set_model_data(self.myKeywords)
  4240. def restore_extensions(self, ext_type):
  4241. if ext_type == 'excellon':
  4242. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  4243. # for the ability to open Excellon files with .txt extension
  4244. new_exc_list = deepcopy(self.exc_list)
  4245. try:
  4246. new_exc_list.remove('txt')
  4247. except ValueError:
  4248. pass
  4249. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  4250. if ext_type == 'gcode':
  4251. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  4252. if ext_type == 'gerber':
  4253. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  4254. if ext_type == 'keyword':
  4255. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  4256. # update the self.myKeywords so the model is updated
  4257. self.autocomplete_kw_list = self.default_keywords
  4258. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4259. self.shell._edit.set_model_data(self.myKeywords)
  4260. self.ui.code_editor.set_model_data(self.myKeywords)
  4261. def delete_all_extensions(self, ext_type):
  4262. if ext_type == 'excellon':
  4263. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4264. if ext_type == 'gcode':
  4265. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4266. if ext_type == 'gerber':
  4267. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4268. if ext_type == 'keyword':
  4269. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4270. # update the self.myKeywords so the model is updated
  4271. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4272. self.shell._edit.set_model_data(self.myKeywords)
  4273. self.ui.code_editor.set_model_data(self.myKeywords)
  4274. def on_edit_join(self, name=None):
  4275. """
  4276. Callback for Edit->Join. Joins the selected geometry objects into
  4277. a new one.
  4278. :return: None
  4279. """
  4280. self.report_usage("on_edit_join()")
  4281. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4282. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4283. tooldias = []
  4284. geo_type_list = set()
  4285. objs = self.collection.get_selected()
  4286. if len(objs) < 2:
  4287. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4288. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4289. return 'fail'
  4290. for obj in objs:
  4291. geo_type_list.add(obj.multigeo)
  4292. # if len(geo_type_list) == 1 means that all list elements are the same
  4293. if len(geo_type_list) != 1:
  4294. self.inform.emit('[ERROR] %s' %
  4295. _("Failed join. The Geometry objects are of different types.\n"
  4296. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4297. "convert from one to another and retry joining \n"
  4298. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4299. "the result may not be what was expected. \n"
  4300. "Check the generated GCODE."))
  4301. return
  4302. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4303. if True in geo_type_list:
  4304. def initialize(obj, app):
  4305. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=True)
  4306. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4307. for v in obj.tools.values():
  4308. v['data']['name'] = obj_name_multi
  4309. self.new_object("geometry", obj_name_multi, initialize)
  4310. else:
  4311. def initialize(obj, app):
  4312. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=False)
  4313. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4314. for v in obj.tools.values():
  4315. v['data']['name'] = obj_name_single
  4316. self.new_object("geometry", obj_name_single, initialize)
  4317. self.should_we_save = True
  4318. def on_edit_join_exc(self):
  4319. """
  4320. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4321. a new Excellon.
  4322. :return: None
  4323. """
  4324. self.report_usage("on_edit_join_exc()")
  4325. objs = self.collection.get_selected()
  4326. for obj in objs:
  4327. if not isinstance(obj, FlatCAMExcellon):
  4328. self.inform.emit('[ERROR_NOTCL] %s' %
  4329. _("Failed. Excellon joining works only on Excellon objects."))
  4330. return
  4331. if len(objs) < 2:
  4332. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4333. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4334. return 'fail'
  4335. def initialize(obj, app):
  4336. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=obj)
  4337. self.new_object("excellon", 'Combo_Excellon', initialize)
  4338. self.should_we_save = True
  4339. def on_edit_join_grb(self):
  4340. """
  4341. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4342. a new Gerber object.
  4343. :return: None
  4344. """
  4345. self.report_usage("on_edit_join_grb()")
  4346. objs = self.collection.get_selected()
  4347. for obj in objs:
  4348. if not isinstance(obj, FlatCAMGerber):
  4349. self.inform.emit('[ERROR_NOTCL] %s' %
  4350. _("Failed. Gerber joining works only on Gerber objects."))
  4351. return
  4352. if len(objs) < 2:
  4353. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4354. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4355. return 'fail'
  4356. def initialize(obj, app):
  4357. FlatCAMGerber.merge(self, grb_list=objs, grb_final=obj)
  4358. self.new_object("gerber", 'Combo_Gerber', initialize)
  4359. self.should_we_save = True
  4360. def on_convert_singlegeo_to_multigeo(self):
  4361. """
  4362. Called for converting a Geometry object from single-geo to multi-geo.
  4363. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4364. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4365. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4366. the solid-geometry of that tool.
  4367. :return: None
  4368. """
  4369. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4370. obj = self.collection.get_active()
  4371. if obj is None:
  4372. self.inform.emit('[ERROR_NOTCL] %s' %
  4373. _("Failed. Select a Geometry Object and try again."))
  4374. return
  4375. if not isinstance(obj, FlatCAMGeometry):
  4376. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4377. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4378. return
  4379. obj.multigeo = True
  4380. for tooluid, dict_value in obj.tools.items():
  4381. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4382. if not isinstance(obj.solid_geometry, list):
  4383. obj.solid_geometry = [obj.solid_geometry]
  4384. obj.solid_geometry[:] = []
  4385. obj.plot()
  4386. self.should_we_save = True
  4387. self.inform.emit('[success] %s' %
  4388. _("A Geometry object was converted to MultiGeo type."))
  4389. def on_convert_multigeo_to_singlegeo(self):
  4390. """
  4391. Called for converting a Geometry object from multi-geo to single-geo.
  4392. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4393. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4394. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4395. the solid-geometry of that tool.
  4396. :return: None
  4397. """
  4398. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4399. obj = self.collection.get_active()
  4400. if obj is None:
  4401. self.inform.emit('[ERROR_NOTCL] %s' %
  4402. _("Failed. Select a Geometry Object and try again."))
  4403. return
  4404. if not isinstance(obj, FlatCAMGeometry):
  4405. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4406. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4407. return
  4408. obj.multigeo = False
  4409. total_solid_geometry = []
  4410. for tooluid, dict_value in obj.tools.items():
  4411. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4412. # clear the original geometry
  4413. dict_value['solid_geometry'][:] = []
  4414. obj.solid_geometry = deepcopy(total_solid_geometry)
  4415. obj.plot()
  4416. self.should_we_save = True
  4417. self.inform.emit('[success] %s' %
  4418. _("A Geometry object was converted to SingleGeo type."))
  4419. def on_options_dict_change(self, field):
  4420. """
  4421. Called whenever a key changed in the self.options dictionary. This dict was used to store the preferences of the
  4422. current project. This feature is no longer used.
  4423. :param field:
  4424. :return:
  4425. """
  4426. self.options_write_form_field(field)
  4427. if field == "units":
  4428. self.set_screen_units(self.options['units'])
  4429. def on_defaults_dict_change(self, field):
  4430. """
  4431. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4432. Edit -> Preferences tab window.
  4433. :param field: the key of the self.defaults dictionary that was changed.
  4434. :return: None
  4435. """
  4436. self.defaults_write_form_field(field)
  4437. if field == "units":
  4438. self.set_screen_units(self.defaults['units'])
  4439. def set_screen_units(self, units):
  4440. """
  4441. Set the FlatCAM units on the status bar.
  4442. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4443. :return: None
  4444. """
  4445. self.ui.units_label.setText("[" + units.lower() + "]")
  4446. def on_toggle_units(self, no_pref=False):
  4447. """
  4448. Callback for the Units radio-button change in the Preferences tab.
  4449. Changes the application's default units adn for the project too.
  4450. If changing the project's units, the change propagates to all of
  4451. the objects in the project.
  4452. :return: None
  4453. """
  4454. self.report_usage("on_toggle_units")
  4455. if self.toggle_units_ignore:
  4456. return
  4457. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4458. # If option is the same, then ignore
  4459. if new_units == self.defaults["units"].upper():
  4460. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4461. return
  4462. # Options to scale
  4463. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin', "gerber_isooverlap",
  4464. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f"
  4465. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  4466. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4467. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  4468. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  4469. "excellon_editor_slot_lin_pitch",
  4470. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4471. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4472. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  4473. "geometry_feedrate_probe", "geometry_startz",
  4474. 'cncjob_tooldia',
  4475. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4476. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia"
  4477. "tools_2sided_drilldia", "tools_film_boundary",
  4478. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4479. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4480. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4481. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4482. "tools_transform_offset_y",
  4483. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4484. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4485. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4486. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4487. 'global_gridx', 'global_gridy', 'global_snap_max']
  4488. def scale_options(sfactor):
  4489. for dim in dimensions:
  4490. if dim == 'excellon_toolchangexy':
  4491. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4492. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4493. coords_xy[0] *= sfactor
  4494. coords_xy[1] *= sfactor
  4495. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4496. elif dim == 'geometry_toolchangexy':
  4497. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4498. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4499. coords_xy[0] *= sfactor
  4500. coords_xy[1] *= sfactor
  4501. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4502. elif dim == 'geometry_cnctooldia':
  4503. tools_diameters = []
  4504. try:
  4505. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4506. tools_diameters = [eval(a) for a in tools_string if a != '']
  4507. except Exception as e:
  4508. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4509. self.options['geometry_cnctooldia'] = ''
  4510. for t in range(len(tools_diameters)):
  4511. tools_diameters[t] *= sfactor
  4512. self.options['geometry_cnctooldia'] += "%f," % tools_diameters[t]
  4513. elif dim == 'tools_ncctools':
  4514. ncctools = []
  4515. try:
  4516. tools_string = self.defaults["tools_ncctools"].split(",")
  4517. ncctools = [eval(a) for a in tools_string if a != '']
  4518. except Exception as e:
  4519. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4520. self.options['tools_ncctools'] = ''
  4521. for t in range(len(ncctools)):
  4522. ncctools[t] *= sfactor
  4523. self.options['tools_ncctools'] += "%f," % ncctools[t]
  4524. elif dim == 'tools_solderpaste_tools':
  4525. sptools = []
  4526. try:
  4527. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4528. sptools = [eval(a) for a in tools_string if a != '']
  4529. except Exception as e:
  4530. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4531. self.options['tools_solderpaste_tools'] = ""
  4532. for t in range(len(sptools)):
  4533. sptools[t] *= sfactor
  4534. self.options['tools_solderpaste_tools'] += "%f," % sptools[t]
  4535. elif dim == 'tools_solderpaste_xy_toolchange':
  4536. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4537. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4538. sp_coords[0] *= sfactor
  4539. sp_coords[1] *= sfactor
  4540. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  4541. elif dim == 'global_gridx' or dim == 'global_gridy':
  4542. if new_units == 'IN':
  4543. val = 0.1
  4544. try:
  4545. val = float(self.defaults[dim]) * sfactor
  4546. except Exception as e:
  4547. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4548. self.options[dim] = float('%.6f' % val)
  4549. else:
  4550. val = 0.1
  4551. try:
  4552. val = float(self.defaults[dim]) * sfactor
  4553. except Exception as e:
  4554. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4555. self.options[dim] = float('%.4f' % val)
  4556. else:
  4557. val = 0.1
  4558. try:
  4559. val = float(self.options[dim]) * sfactor
  4560. except Exception as e:
  4561. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  4562. self.options[dim] = val
  4563. def scale_defaults(sfactor):
  4564. for dim in dimensions:
  4565. if dim == 'excellon_toolchangexy':
  4566. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4567. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4568. coords_xy[0] *= sfactor
  4569. coords_xy[1] *= sfactor
  4570. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4571. elif dim == 'geometry_toolchangexy':
  4572. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4573. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4574. coords_xy[0] *= sfactor
  4575. coords_xy[1] *= sfactor
  4576. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4577. elif dim == 'geometry_cnctooldia':
  4578. tools_diameters = []
  4579. try:
  4580. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4581. tools_diameters = [eval(a) for a in tools_string if a != '']
  4582. except Exception as e:
  4583. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4584. self.defaults['geometry_cnctooldia'] = ''
  4585. for t in range(len(tools_diameters)):
  4586. tools_diameters[t] *= sfactor
  4587. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  4588. elif dim == 'tools_ncctools':
  4589. ncctools = []
  4590. try:
  4591. tools_string = self.defaults["tools_ncctools"].split(",")
  4592. ncctools = [eval(a) for a in tools_string if a != '']
  4593. except Exception as e:
  4594. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4595. self.defaults['tools_ncctools'] = ''
  4596. for t in range(len(ncctools)):
  4597. ncctools[t] *= sfactor
  4598. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  4599. elif dim == 'tools_solderpaste_tools':
  4600. sptools = []
  4601. try:
  4602. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4603. sptools = [eval(a) for a in tools_string if a != '']
  4604. except Exception as e:
  4605. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4606. self.defaults['tools_solderpaste_tools'] = ""
  4607. for t in range(len(sptools)):
  4608. sptools[t] *= sfactor
  4609. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  4610. elif dim == 'tools_solderpaste_xy_toolchange':
  4611. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4612. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4613. sp_coords[0] *= sfactor
  4614. sp_coords[1] *= sfactor
  4615. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  4616. elif dim == 'global_gridx' or dim == 'global_gridy':
  4617. if new_units == 'IN':
  4618. val = 0.1
  4619. try:
  4620. val = float(self.defaults[dim]) * sfactor
  4621. except Exception as e:
  4622. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4623. self.defaults[dim] = float('%.6f' % val)
  4624. else:
  4625. val = 0.1
  4626. try:
  4627. val = float(self.defaults[dim]) * sfactor
  4628. except Exception as e:
  4629. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4630. self.defaults[dim] = float('%.4f' % val)
  4631. else:
  4632. val = 0.1
  4633. try:
  4634. val = float(self.defaults[dim]) * sfactor
  4635. except Exception as e:
  4636. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4637. self.defaults[dim] = val
  4638. # The scaling factor depending on choice of units.
  4639. factor = 1/25.4
  4640. if new_units == 'MM':
  4641. factor = 25.4
  4642. # Changing project units. Warn user.
  4643. msgbox = QtWidgets.QMessageBox()
  4644. msgbox.setWindowTitle(_("Toggle Units"))
  4645. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  4646. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4647. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  4648. "properties of all objects to be scaled accordingly.\nContinue?"))
  4649. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4650. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4651. msgbox.setDefaultButton(bt_ok)
  4652. msgbox.exec_()
  4653. response = msgbox.clickedButton()
  4654. if response == bt_ok:
  4655. if no_pref is False:
  4656. self.options_read_form()
  4657. scale_options(factor)
  4658. self.options_write_form()
  4659. self.defaults_read_form()
  4660. scale_defaults(factor)
  4661. self.defaults_write_form(fl_units=new_units)
  4662. # save the defaults to file, some may assume that the conversion is enough and it's not
  4663. self.on_save_button()
  4664. self.should_we_save = True
  4665. # change this only if the workspace is active
  4666. if self.defaults['global_workspace'] is True:
  4667. self.plotcanvas.draw_workspace()
  4668. # adjust the grid values on the main toolbar
  4669. dec = 6 if new_units == 'IN'else 4
  4670. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  4671. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  4672. if not self.ui.grid_gap_link_cb.isChecked():
  4673. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  4674. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  4675. for obj in self.collection.get_list():
  4676. obj.convert_units(new_units)
  4677. # make that the properties stored in the object are also updated
  4678. self.object_changed.emit(obj)
  4679. obj.build_ui()
  4680. current = self.collection.get_active()
  4681. if current is not None:
  4682. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4683. if not isinstance(current, FlatCAMGeometry):
  4684. current.to_form()
  4685. self.plot_all()
  4686. self.inform.emit('[success] %s: %s' %
  4687. (_("Converted units to"), new_units))
  4688. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4689. self.set_screen_units(new_units)
  4690. else:
  4691. # Undo toggling
  4692. self.toggle_units_ignore = True
  4693. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4694. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4695. else:
  4696. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4697. self.toggle_units_ignore = False
  4698. self.inform.emit('[WARNING_NOTCL]%s' %
  4699. _(" Units conversion cancelled."))
  4700. self.options_read_form()
  4701. self.defaults_read_form()
  4702. def on_toggle_units_click(self):
  4703. try:
  4704. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4705. except (TypeError, AttributeError):
  4706. pass
  4707. if self.defaults["units"] == 'MM':
  4708. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4709. else:
  4710. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4711. self.on_toggle_units(no_pref=True)
  4712. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4713. lambda: self.on_toggle_units(no_pref=False))
  4714. def on_fullscreen(self):
  4715. self.report_usage("on_fullscreen()")
  4716. if self.toggle_fscreen is False:
  4717. # self.ui.showFullScreen()
  4718. self.ui.setWindowFlags(self.ui.windowFlags() | Qt.FramelessWindowHint)
  4719. a = self.ui.geometry()
  4720. self.x_pos = a.x()
  4721. self.y_pos = a.y()
  4722. self.width = a.width()
  4723. self.height = a.height()
  4724. # set new geometry to full desktop rect
  4725. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  4726. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  4727. # everything else will not work without this hack. This happen in Windows.
  4728. # https://bugreports.qt.io/browse/QTBUG-41309
  4729. desktop = QtWidgets.QApplication.desktop()
  4730. screen = desktop.screenNumber(QtGui.QCursor.pos())
  4731. rec = desktop.screenGeometry(screen)
  4732. x = rec.x() - 1
  4733. y = rec.y() - 1
  4734. h = rec.height() + 2
  4735. w = rec.width() + 2
  4736. self.ui.setGeometry(x, y, w, h)
  4737. self.ui.show()
  4738. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4739. tb.setVisible(False)
  4740. self.ui.splitter_left.setVisible(False)
  4741. self.toggle_fscreen = True
  4742. else:
  4743. self.ui.setWindowFlags(self.ui.windowFlags() & ~Qt.FramelessWindowHint)
  4744. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  4745. self.ui.showNormal()
  4746. self.restore_toolbar_view()
  4747. self.ui.splitter_left.setVisible(True)
  4748. self.toggle_fscreen = False
  4749. def on_toggle_plotarea(self):
  4750. self.report_usage("on_toggle_plotarea()")
  4751. try:
  4752. name = self.ui.plot_tab_area.widget(0).objectName()
  4753. except AttributeError:
  4754. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4755. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4756. self.ui.plot_tab_area.protectTab(0)
  4757. return
  4758. if name != 'plotarea':
  4759. self.ui.plot_tab_area.insertTab(0, 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. else:
  4763. self.ui.plot_tab_area.closeTab(0)
  4764. def on_toggle_notebook(self):
  4765. if self.ui.splitter.sizes()[0] == 0:
  4766. self.ui.splitter.setSizes([1, 1])
  4767. else:
  4768. self.ui.splitter.setSizes([0, 1])
  4769. def on_toggle_axis(self):
  4770. self.report_usage("on_toggle_axis()")
  4771. if self.toggle_axis is False:
  4772. if self.is_legacy is False:
  4773. # self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4774. # self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4775. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  4776. parent=self.plotcanvas.view.scene)
  4777. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  4778. parent=self.plotcanvas.view.scene)
  4779. # self.plotcanvas.redraw()
  4780. else:
  4781. self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  4782. self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  4783. self.plotcanvas.canvas.draw()
  4784. pass
  4785. self.toggle_axis = True
  4786. else:
  4787. if self.is_legacy is False:
  4788. # self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4789. # self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4790. # self.plotcanvas.redraw()
  4791. self.plotcanvas.v_line.parent = None
  4792. self.plotcanvas.h_line.parent = None
  4793. else:
  4794. self.plotcanvas.axes.lines[:] = []
  4795. self.plotcanvas.canvas.draw()
  4796. self.toggle_axis = False
  4797. def on_toggle_grid(self):
  4798. self.report_usage("on_toggle_grid()")
  4799. self.ui.grid_snap_btn.trigger()
  4800. def on_options_combo_change(self, sel):
  4801. """
  4802. Called when the combo box to choose between application defaults and
  4803. project option changes value. The corresponding variables are
  4804. copied to the UI.
  4805. :param sel: The option index that was chosen.
  4806. :return: None
  4807. """
  4808. # combo_sel = self.ui.notebook.combo_options.get_active()
  4809. App.log.debug("Options --> %s" % sel)
  4810. # form = [self.defaults_form, self.options_form][sel]
  4811. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  4812. if sel == 0:
  4813. self.gen_form = self.ui.general_defaults_form
  4814. self.ger_form = self.ui.gerber_defaults_form
  4815. self.exc_form = self.ui.excellon_defaults_form
  4816. self.geo_form = self.ui.geometry_defaults_form
  4817. self.cnc_form = self.ui.cncjob_defaults_form
  4818. self.tools_form = self.ui.tools_defaults_form
  4819. self.fa_form = self.ui.util_defaults_form
  4820. elif sel == 1:
  4821. self.gen_form = self.ui.general_options_form
  4822. self.ger_form = self.ui.gerber_options_form
  4823. self.exc_form = self.ui.excellon_options_form
  4824. self.geo_form = self.ui.geometry_options_form
  4825. self.cnc_form = self.ui.cncjob_options_form
  4826. self.tools_form = self.ui.tools_options_form
  4827. self.fa_form = self.ui.util_options_form
  4828. else:
  4829. return
  4830. try:
  4831. self.ui.general_scroll_area.takeWidget()
  4832. except:
  4833. self.log.debug("Nothing to remove")
  4834. self.ui.general_scroll_area.setWidget(self.gen_form)
  4835. self.gen_form.show()
  4836. try:
  4837. self.ui.gerber_scroll_area.takeWidget()
  4838. except:
  4839. self.log.debug("Nothing to remove")
  4840. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  4841. self.ger_form.show()
  4842. try:
  4843. self.ui.excellon_scroll_area.takeWidget()
  4844. except:
  4845. self.log.debug("Nothing to remove")
  4846. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  4847. self.exc_form.show()
  4848. try:
  4849. self.ui.geometry_scroll_area.takeWidget()
  4850. except:
  4851. self.log.debug("Nothing to remove")
  4852. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  4853. self.geo_form.show()
  4854. try:
  4855. self.ui.cncjob_scroll_area.takeWidget()
  4856. except:
  4857. self.log.debug("Nothing to remove")
  4858. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  4859. self.cnc_form.show()
  4860. try:
  4861. self.ui.tools_scroll_area.takeWidget()
  4862. except:
  4863. self.log.debug("Nothing to remove")
  4864. self.ui.tools_scroll_area.setWidget(self.tools_form)
  4865. self.tools_form.show()
  4866. try:
  4867. self.ui.fa_scroll_area.takeWidget()
  4868. except:
  4869. self.log.debug("Nothing to remove")
  4870. self.ui.fa_scroll_area.setWidget(self.fa_form)
  4871. self.fa_form.show()
  4872. self.log.debug("Finished GUI form initialization.")
  4873. # self.options2form()
  4874. def on_excellon_defaults_button(self):
  4875. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  4876. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  4877. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  4878. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  4879. self.defaults_form_fields["excellon_zeros"].set_value('L')
  4880. self.defaults_form_fields["excellon_units"].set_value('INCH')
  4881. log.debug("Excellon app defaults loaded ...")
  4882. def on_excellon_options_button(self):
  4883. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  4884. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  4885. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  4886. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  4887. self.options_form_fields["excellon_zeros"].set_value('L')
  4888. self.options_form_fields["excellon_units"].set_value('INCH')
  4889. log.debug("Excellon options defaults loaded ...")
  4890. def on_update_exc_export(self, state):
  4891. """
  4892. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  4893. if the update_excellon_cb checkbox is checked
  4894. :param state: state of the checkbox whose signals is tied to his slot
  4895. :return:
  4896. """
  4897. if state:
  4898. # first try to disconnect
  4899. try:
  4900. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.\
  4901. disconnect(self.on_excellon_format_changed)
  4902. except TypeError:
  4903. pass
  4904. try:
  4905. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_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_upper_mm_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_lower_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_zeros_radio.activated_custom.\
  4921. disconnect(self.on_excellon_zeros_changed)
  4922. except TypeError:
  4923. pass
  4924. try:
  4925. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  4926. disconnect(self.on_excellon_zeros_changed)
  4927. except TypeError:
  4928. pass
  4929. # the connect them
  4930. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.connect(
  4931. self.on_excellon_format_changed)
  4932. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged.connect(
  4933. self.on_excellon_format_changed)
  4934. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged.connect(
  4935. self.on_excellon_format_changed)
  4936. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged.connect(
  4937. self.on_excellon_format_changed)
  4938. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  4939. self.on_excellon_zeros_changed)
  4940. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  4941. self.on_excellon_units_changed)
  4942. else:
  4943. # disconnect the signals
  4944. try:
  4945. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged. \
  4946. disconnect(self.on_excellon_format_changed)
  4947. except TypeError:
  4948. pass
  4949. try:
  4950. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_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_upper_mm_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_lower_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_zeros_radio.activated_custom. \
  4966. disconnect(self.on_excellon_zeros_changed)
  4967. except TypeError:
  4968. pass
  4969. try:
  4970. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  4971. disconnect(self.on_excellon_zeros_changed)
  4972. except TypeError:
  4973. pass
  4974. def on_excellon_format_changed(self):
  4975. """
  4976. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  4977. :return: None
  4978. """
  4979. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  4980. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4981. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  4982. )
  4983. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4984. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  4985. )
  4986. else:
  4987. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4988. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  4989. )
  4990. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4991. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  4992. )
  4993. def on_excellon_zeros_changed(self):
  4994. """
  4995. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  4996. :return: None
  4997. """
  4998. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  4999. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  5000. )
  5001. def on_excellon_units_changed(self):
  5002. """
  5003. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  5004. :return: None
  5005. """
  5006. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  5007. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  5008. )
  5009. self.on_excellon_format_changed()
  5010. # Setting plot colors handlers
  5011. def on_pf_color_entry(self):
  5012. self.defaults['global_plot_fill'] = \
  5013. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  5014. self.defaults['global_plot_fill'][7:9]
  5015. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5016. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  5017. def on_pf_color_button(self):
  5018. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  5019. c_dialog = QtWidgets.QColorDialog()
  5020. plot_fill_color = c_dialog.getColor(initial=current_color)
  5021. if plot_fill_color.isValid() is False:
  5022. return
  5023. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5024. "background-color:%s" % str(plot_fill_color.name()))
  5025. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  5026. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  5027. self.defaults['global_plot_fill'] = new_val
  5028. def on_pf_color_spinner(self):
  5029. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  5030. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  5031. self.defaults['global_plot_fill'] = \
  5032. self.defaults['global_plot_fill'][:7] + \
  5033. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5034. self.defaults['global_plot_line'] = \
  5035. self.defaults['global_plot_line'][:7] + \
  5036. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5037. def on_pf_color_slider(self):
  5038. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  5039. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  5040. def on_pl_color_entry(self):
  5041. self.defaults['global_plot_line'] = \
  5042. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  5043. self.defaults['global_plot_line'][7:9]
  5044. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5045. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  5046. def on_pl_color_button(self):
  5047. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  5048. # print(current_color)
  5049. c_dialog = QtWidgets.QColorDialog()
  5050. plot_line_color = c_dialog.getColor(initial=current_color)
  5051. if plot_line_color.isValid() is False:
  5052. return
  5053. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5054. "background-color:%s" % str(plot_line_color.name()))
  5055. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  5056. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  5057. self.defaults['global_plot_line'] = new_val_line
  5058. # Setting selection colors (left - right) handlers
  5059. def on_sf_color_entry(self):
  5060. self.defaults['global_sel_fill'] = \
  5061. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  5062. self.defaults['global_sel_fill'][7:9]
  5063. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5064. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  5065. def on_sf_color_button(self):
  5066. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  5067. c_dialog = QtWidgets.QColorDialog()
  5068. plot_fill_color = c_dialog.getColor(initial=current_color)
  5069. if plot_fill_color.isValid() is False:
  5070. return
  5071. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5072. "background-color:%s" % str(plot_fill_color.name()))
  5073. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  5074. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  5075. self.defaults['global_sel_fill'] = new_val
  5076. def on_sf_color_spinner(self):
  5077. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  5078. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  5079. self.defaults['global_sel_fill'] = \
  5080. self.defaults['global_sel_fill'][:7] + \
  5081. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5082. self.defaults['global_sel_line'] = \
  5083. self.defaults['global_sel_line'][:7] + \
  5084. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5085. def on_sf_color_slider(self):
  5086. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  5087. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  5088. def on_sl_color_entry(self):
  5089. self.defaults['global_sel_line'] = \
  5090. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  5091. self.defaults['global_sel_line'][7:9]
  5092. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5093. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  5094. def on_sl_color_button(self):
  5095. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  5096. c_dialog = QtWidgets.QColorDialog()
  5097. plot_line_color = c_dialog.getColor(initial=current_color)
  5098. if plot_line_color.isValid() is False:
  5099. return
  5100. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5101. "background-color:%s" % str(plot_line_color.name()))
  5102. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  5103. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  5104. self.defaults['global_sel_line'] = new_val_line
  5105. # Setting selection colors (right - left) handlers
  5106. def on_alt_sf_color_entry(self):
  5107. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  5108. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  5109. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5110. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  5111. def on_alt_sf_color_button(self):
  5112. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  5113. c_dialog = QtWidgets.QColorDialog()
  5114. plot_fill_color = c_dialog.getColor(initial=current_color)
  5115. if plot_fill_color.isValid() is False:
  5116. return
  5117. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5118. "background-color:%s" % str(plot_fill_color.name()))
  5119. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  5120. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  5121. self.defaults['global_alt_sel_fill'] = new_val
  5122. def on_alt_sf_color_spinner(self):
  5123. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  5124. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  5125. self.defaults['global_alt_sel_fill'] = \
  5126. self.defaults['global_alt_sel_fill'][:7] + \
  5127. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5128. self.defaults['global_alt_sel_line'] = \
  5129. self.defaults['global_alt_sel_line'][:7] + \
  5130. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5131. def on_alt_sf_color_slider(self):
  5132. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  5133. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  5134. def on_alt_sl_color_entry(self):
  5135. self.defaults['global_alt_sel_line'] = \
  5136. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  5137. self.defaults['global_alt_sel_line'][7:9]
  5138. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5139. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  5140. def on_alt_sl_color_button(self):
  5141. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  5142. c_dialog = QtWidgets.QColorDialog()
  5143. plot_line_color = c_dialog.getColor(initial=current_color)
  5144. if plot_line_color.isValid() is False:
  5145. return
  5146. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5147. "background-color:%s" % str(plot_line_color.name()))
  5148. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  5149. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  5150. self.defaults['global_alt_sel_line'] = new_val_line
  5151. # Setting Editor colors
  5152. def on_draw_color_entry(self):
  5153. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5154. .draw_color_entry.get_value()
  5155. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5156. "background-color:%s" % str(self.defaults['global_draw_color']))
  5157. def on_draw_color_button(self):
  5158. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  5159. c_dialog = QtWidgets.QColorDialog()
  5160. draw_color = c_dialog.getColor(initial=current_color)
  5161. if draw_color.isValid() is False:
  5162. return
  5163. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5164. "background-color:%s" % str(draw_color.name()))
  5165. new_val = str(draw_color.name())
  5166. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  5167. self.defaults['global_draw_color'] = new_val
  5168. def on_sel_draw_color_entry(self):
  5169. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5170. .sel_draw_color_entry.get_value()
  5171. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5172. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  5173. def on_sel_draw_color_button(self):
  5174. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  5175. c_dialog = QtWidgets.QColorDialog()
  5176. sel_draw_color = c_dialog.getColor(initial=current_color)
  5177. if sel_draw_color.isValid() is False:
  5178. return
  5179. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5180. "background-color:%s" % str(sel_draw_color.name()))
  5181. new_val_sel = str(sel_draw_color.name())
  5182. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  5183. self.defaults['global_sel_draw_color'] = new_val_sel
  5184. def on_proj_color_entry(self):
  5185. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  5186. .proj_color_entry.get_value()
  5187. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5188. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  5189. def on_proj_color_button(self):
  5190. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  5191. c_dialog = QtWidgets.QColorDialog()
  5192. proj_color = c_dialog.getColor(initial=current_color)
  5193. if proj_color.isValid() is False:
  5194. return
  5195. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5196. "background-color:%s" % str(proj_color.name()))
  5197. new_val_sel = str(proj_color.name())
  5198. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  5199. self.defaults['global_proj_item_color'] = new_val_sel
  5200. def on_proj_color_dis_entry(self):
  5201. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  5202. .proj_color_dis_entry.get_value()
  5203. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5204. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  5205. def on_proj_color_dis_button(self):
  5206. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  5207. c_dialog = QtWidgets.QColorDialog()
  5208. proj_color = c_dialog.getColor(initial=current_color)
  5209. if proj_color.isValid() is False:
  5210. return
  5211. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5212. "background-color:%s" % str(proj_color.name()))
  5213. new_val_sel = str(proj_color.name())
  5214. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  5215. self.defaults['global_proj_item_dis_color'] = new_val_sel
  5216. def on_annotation_fontcolor_entry(self):
  5217. self.defaults['cncjob_annotation_fontcolor'] = \
  5218. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.get_value()
  5219. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5220. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  5221. def on_annotation_fontcolor_button(self):
  5222. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  5223. c_dialog = QtWidgets.QColorDialog()
  5224. annotation_color = c_dialog.getColor(initial=current_color)
  5225. if annotation_color.isValid() is False:
  5226. return
  5227. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5228. "background-color:%s" % str(annotation_color.name()))
  5229. new_val_sel = str(annotation_color.name())
  5230. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(new_val_sel)
  5231. self.defaults['cncjob_annotation_fontcolor'] = new_val_sel
  5232. def on_film_color_entry(self):
  5233. self.defaults['tools_film_color'] = \
  5234. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  5235. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5236. "background-color:%s" % str(self.defaults['tools_film_color']))
  5237. def on_film_color_button(self):
  5238. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  5239. c_dialog = QtWidgets.QColorDialog()
  5240. film_color = c_dialog.getColor(initial=current_color)
  5241. if film_color.isValid() is False:
  5242. return
  5243. # if new color is different then mark that the Preferences are changed
  5244. if film_color != current_color:
  5245. self.on_preferences_edited()
  5246. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5247. "background-color:%s" % str(film_color.name()))
  5248. new_val_sel = str(film_color.name())
  5249. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  5250. self.defaults['tools_film_color'] = new_val_sel
  5251. def on_splash_changed(self, state):
  5252. settings = QSettings("Open Source", "FlatCAM")
  5253. settings.setValue('splash_screen', 1) if state else settings.setValue('splash_screen', 0)
  5254. # This will write the setting to the platform specific storage.
  5255. del settings
  5256. def on_notebook_tab_rmb_click(self, checked):
  5257. self.ui.notebook.set_detachable(val=checked)
  5258. self.defaults["global_tabs_detachable"] = checked
  5259. self.ui.plot_tab_area.set_detachable(val=checked)
  5260. self.defaults["global_tabs_detachable"] = checked
  5261. def on_deselect_all(self):
  5262. self.collection.set_all_inactive()
  5263. self.delete_selection_shape()
  5264. def on_workspace_modified(self):
  5265. self.save_defaults(silent=True)
  5266. self.plotcanvas.draw_workspace()
  5267. def on_workspace(self):
  5268. self.report_usage("on_workspace()")
  5269. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5270. self.plotcanvas.restore_workspace()
  5271. else:
  5272. self.plotcanvas.delete_workspace()
  5273. self.save_defaults(silent=True)
  5274. def on_workspace_menu(self):
  5275. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5276. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  5277. else:
  5278. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  5279. self.on_workspace()
  5280. def on_layout(self, index=None, lay=None):
  5281. """
  5282. Set the toolbars layout (location)
  5283. :param index:
  5284. :param lay: type of layout to be set on the toolbard
  5285. :return: None
  5286. """
  5287. self.report_usage("on_layout()")
  5288. if lay:
  5289. current_layout = lay
  5290. else:
  5291. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  5292. settings = QSettings("Open Source", "FlatCAM")
  5293. settings.setValue('layout', current_layout)
  5294. # This will write the setting to the platform specific storage.
  5295. del settings
  5296. # first remove the toolbars:
  5297. try:
  5298. self.ui.removeToolBar(self.ui.toolbarfile)
  5299. self.ui.removeToolBar(self.ui.toolbargeo)
  5300. self.ui.removeToolBar(self.ui.toolbarview)
  5301. self.ui.removeToolBar(self.ui.toolbarshell)
  5302. self.ui.removeToolBar(self.ui.toolbartools)
  5303. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  5304. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  5305. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  5306. self.ui.removeToolBar(self.ui.snap_toolbar)
  5307. self.ui.removeToolBar(self.ui.toolbarshell)
  5308. except Exception as e:
  5309. pass
  5310. if current_layout == 'standard':
  5311. # ## TOOLBAR INSTALLATION # ##
  5312. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5313. self.ui.toolbarfile.setObjectName('File_TB')
  5314. self.ui.addToolBar(self.ui.toolbarfile)
  5315. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5316. self.ui.toolbargeo.setObjectName('Edit_TB')
  5317. self.ui.addToolBar(self.ui.toolbargeo)
  5318. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5319. self.ui.toolbarview.setObjectName('View_TB')
  5320. self.ui.addToolBar(self.ui.toolbarview)
  5321. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5322. self.ui.toolbarshell.setObjectName('Shell_TB')
  5323. self.ui.addToolBar(self.ui.toolbarshell)
  5324. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5325. self.ui.toolbartools.setObjectName('Tools_TB')
  5326. self.ui.addToolBar(self.ui.toolbartools)
  5327. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5328. # self.ui.exc_edit_toolbar.setVisible(False)
  5329. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5330. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  5331. self.ui.addToolBarBreak()
  5332. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5333. # self.ui.geo_edit_toolbar.setVisible(False)
  5334. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5335. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  5336. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5337. # self.ui.grb_edit_toolbar.setVisible(False)
  5338. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5339. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  5340. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5341. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5342. # self.ui.snap_toolbar.setMaximumHeight(30)
  5343. self.ui.addToolBar(self.ui.snap_toolbar)
  5344. self.ui.corner_snap_btn.setVisible(False)
  5345. self.ui.snap_magnet.setVisible(False)
  5346. elif current_layout == 'compact':
  5347. # ## TOOLBAR INSTALLATION # ##
  5348. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5349. self.ui.toolbarfile.setObjectName('File_TB')
  5350. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  5351. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5352. self.ui.toolbargeo.setObjectName('Edit_TB')
  5353. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  5354. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5355. self.ui.toolbarshell.setObjectName('Shell_TB')
  5356. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  5357. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5358. self.ui.toolbartools.setObjectName('Tools_TB')
  5359. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  5360. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5361. # self.ui.geo_edit_toolbar.setVisible(False)
  5362. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5363. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  5364. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5365. self.ui.toolbarview.setObjectName('View_TB')
  5366. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  5367. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  5368. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5369. # self.ui.grb_edit_toolbar.setVisible(False)
  5370. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5371. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  5372. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5373. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5374. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  5375. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5376. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5377. self.ui.snap_toolbar.setMaximumHeight(30)
  5378. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  5379. self.ui.corner_snap_btn.setVisible(True)
  5380. self.ui.snap_magnet.setVisible(True)
  5381. # add all the actions to the toolbars
  5382. self.ui.populate_toolbars()
  5383. # reconnect all the signals to the toolbar actions
  5384. self.connect_toolbar_signals()
  5385. self.ui.grid_snap_btn.setChecked(True)
  5386. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  5387. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  5388. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  5389. self.ui.grid_gap_link_cb.setChecked(True)
  5390. def on_cursor_type(self, val):
  5391. """
  5392. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  5393. :return: None
  5394. """
  5395. self.app_cursor.enabled = False
  5396. if val == 'small':
  5397. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(False)
  5398. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(False)
  5399. self.app_cursor = self.plotcanvas.new_cursor()
  5400. else:
  5401. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(True)
  5402. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(True)
  5403. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  5404. if self.ui.grid_snap_btn.isChecked():
  5405. self.app_cursor.enabled = True
  5406. else:
  5407. self.app_cursor.enabled = False
  5408. def on_cnc_custom_parameters(self, signal_text):
  5409. if signal_text == 'Parameters':
  5410. return
  5411. else:
  5412. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  5413. def on_save_button(self):
  5414. log.debug("App.on_save_button() --> Saving preferences to file.")
  5415. self.preferences_changed_flag = False
  5416. self.save_defaults(silent=False)
  5417. # load the defaults so they are updated into the app
  5418. self.load_defaults(filename='current_defaults')
  5419. # Re-fresh project options
  5420. self.on_options_app2project()
  5421. settings = QSettings("Open Source", "FlatCAM")
  5422. # save the notebook font size
  5423. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  5424. settings.setValue('notebook_font_size', fsize)
  5425. # save the axis font size
  5426. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  5427. settings.setValue('axis_font_size', g_fsize)
  5428. # save the textbox font size
  5429. tb_fsize = self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  5430. settings.setValue('textbox_font_size', tb_fsize)
  5431. # This will write the setting to the platform specific storage.
  5432. del settings
  5433. def handlePrint(self):
  5434. self.report_usage("handlePrint()")
  5435. dialog = QtPrintSupport.QPrintDialog()
  5436. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  5437. self.ui.code_editor.document().print_(dialog.printer())
  5438. def handlePreview(self):
  5439. self.report_usage("handlePreview()")
  5440. dialog = QtPrintSupport.QPrintPreviewDialog()
  5441. dialog.paintRequested.connect(self.ui.code_editor.print_)
  5442. dialog.exec_()
  5443. def handleTextChanged(self):
  5444. # enable = not self.ui.code_editor.document().isEmpty()
  5445. # self.ui.buttonPrint.setEnabled(enable)
  5446. # self.ui.buttonPreview.setEnabled(enable)
  5447. pass
  5448. def handleOpen(self, filt=None):
  5449. self.report_usage("handleOpen()")
  5450. if filt:
  5451. _filter_ = filt
  5452. else:
  5453. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  5454. "All Files (*.*)"
  5455. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  5456. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  5457. if path:
  5458. file = QtCore.QFile(path)
  5459. if file.open(QtCore.QIODevice.ReadOnly):
  5460. stream = QtCore.QTextStream(file)
  5461. self.gcode_edited = stream.readAll()
  5462. self.ui.code_editor.setPlainText(self.gcode_edited)
  5463. file.close()
  5464. def handleSaveGCode(self, name=None, filt=None):
  5465. self.report_usage("handleSaveGCode()")
  5466. if filt:
  5467. _filter_ = filt
  5468. else:
  5469. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  5470. "All Files (*.*)"
  5471. if name:
  5472. obj_name = name
  5473. else:
  5474. try:
  5475. obj_name = self.collection.get_active().options['name']
  5476. except AttributeError:
  5477. obj_name = 'file'
  5478. if filt is None:
  5479. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  5480. try:
  5481. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  5482. caption=_("Export G-Code ..."),
  5483. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  5484. filter=_filter_
  5485. )[0])
  5486. except TypeError:
  5487. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  5488. if filename == "":
  5489. self.inform.emit('[WARNING_NOTCL] %s' %
  5490. _("Export Code cancelled."))
  5491. return
  5492. else:
  5493. try:
  5494. my_gcode = self.ui.code_editor.toPlainText()
  5495. with open(filename, 'w') as f:
  5496. for line in my_gcode:
  5497. f.write(line)
  5498. except FileNotFoundError:
  5499. self.inform.emit('[WARNING] %s' %
  5500. _("No such file or directory"))
  5501. return
  5502. except PermissionError:
  5503. self.inform.emit('[WARNING] %s' %
  5504. _("Permission denied, saving not possible.\n"
  5505. "Most likely another app is holding the file open and not accessible."))
  5506. return
  5507. # Just for adding it to the recent files list.
  5508. if self.defaults["global_open_style"] is False:
  5509. self.file_opened.emit("cncjob", filename)
  5510. self.file_saved.emit("cncjob", filename)
  5511. self.inform.emit('%s: %s' % (_("Saved to"), str(filename)))
  5512. def handleFindGCode(self):
  5513. self.report_usage("handleFindGCode()")
  5514. flags = QtGui.QTextDocument.FindCaseSensitively
  5515. text_to_be_found = self.ui.entryFind.get_value()
  5516. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  5517. if r is False:
  5518. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5519. def handleReplaceGCode(self):
  5520. self.report_usage("handleReplaceGCode()")
  5521. old = self.ui.entryFind.get_value()
  5522. new = self.ui.entryReplace.get_value()
  5523. if self.ui.sel_all_cb.isChecked():
  5524. while True:
  5525. cursor = self.ui.code_editor.textCursor()
  5526. cursor.beginEditBlock()
  5527. flags = QtGui.QTextDocument.FindCaseSensitively
  5528. # self.ui.editor is the QPlainTextEdit
  5529. r = self.ui.code_editor.find(str(old), flags)
  5530. if r:
  5531. qc = self.ui.code_editor.textCursor()
  5532. if qc.hasSelection():
  5533. qc.insertText(new)
  5534. else:
  5535. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5536. break
  5537. # Mark end of undo block
  5538. cursor.endEditBlock()
  5539. else:
  5540. cursor = self.ui.code_editor.textCursor()
  5541. cursor.beginEditBlock()
  5542. qc = self.ui.code_editor.textCursor()
  5543. if qc.hasSelection():
  5544. qc.insertText(new)
  5545. # Mark end of undo block
  5546. cursor.endEditBlock()
  5547. def handleCopyAll(self):
  5548. text = self.ui.code_editor.toPlainText()
  5549. self.clipboard.setText(text)
  5550. self.inform.emit(_("Code Editor content copied to clipboard ..."))
  5551. def handleRunCode(self):
  5552. # trying to run a Tcl command without having the Shell open will create some warnings because the Tcl Shell
  5553. # tries to print on a hidden widget, therefore show the dock if hidden
  5554. if self.ui.shell_dock.isHidden():
  5555. self.ui.shell_dock.show()
  5556. self.script_code = deepcopy(self.ui.code_editor.toPlainText())
  5557. # self.shell._sysShell.exec_command(script_code)
  5558. old_line = ''
  5559. for tcl_command_line in self.script_code.splitlines():
  5560. # do not process lines starting with '#' = comment and empty lines
  5561. if not tcl_command_line.startswith('#') and tcl_command_line != '':
  5562. # id FlatCAM is run in Windows then replace all the slashes with
  5563. # the UNIX style slash that TCL understands
  5564. if sys.platform == 'win32':
  5565. if "open" in tcl_command_line:
  5566. tcl_command_line = tcl_command_line.replace('\\', '/')
  5567. if old_line != '':
  5568. new_command = old_line + tcl_command_line + '\n'
  5569. else:
  5570. new_command = tcl_command_line
  5571. # execute the actual Tcl command
  5572. try:
  5573. self.shell.open_proccessing() # Disables input box.
  5574. result = self.tcl.eval(str(new_command))
  5575. if result != 'None':
  5576. self.shell.append_output(result + '\n')
  5577. old_line = ''
  5578. except tk.TclError:
  5579. old_line = old_line + tcl_command_line + '\n'
  5580. except Exception as e:
  5581. log.debug("App.handleRunCode() --> %s" % str(e))
  5582. if old_line != '':
  5583. # it means that the script finished with an error
  5584. result = self.tcl.eval("set errorInfo")
  5585. self.log.error("Exec command Exception: %s" % (result + '\n'))
  5586. self.shell.append_error('ERROR: ' + result + '\n')
  5587. self.shell.close_proccessing()
  5588. def on_tool_add_keypress(self):
  5589. # ## Current application units in Upper Case
  5590. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5591. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5592. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5593. if notebook_widget_name == 'selected_tab':
  5594. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5595. # Tool add works for Geometry only if Advanced is True in Preferences
  5596. if self.defaults["global_app_level"] == 'a':
  5597. tool_add_popup = FCInputDialog(title="New Tool ...",
  5598. text='Enter a Tool Diameter:',
  5599. min=0.0000, max=99.9999, decimals=4)
  5600. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5601. val, ok = tool_add_popup.get_value()
  5602. if ok:
  5603. if float(val) == 0:
  5604. self.inform.emit('[WARNING_NOTCL] %s' %
  5605. _("Please enter a tool diameter with non-zero value, in Float format."))
  5606. return
  5607. self.collection.get_active().on_tool_add(dia=float(val))
  5608. else:
  5609. self.inform.emit('[WARNING_NOTCL] %s...' %
  5610. _("Adding Tool cancelled"))
  5611. else:
  5612. msgbox = QtWidgets.QMessageBox()
  5613. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5614. "Go to Preferences -> General - Show Advanced Options."))
  5615. msgbox.setWindowTitle("Tool adding ...")
  5616. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  5617. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5618. msgbox.setDefaultButton(bt_ok)
  5619. msgbox.exec_()
  5620. # work only if the notebook tab on focus is the Tools_Tab
  5621. if notebook_widget_name == 'tool_tab':
  5622. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5623. tool_add_popup = FCInputDialog(title="New Tool ...",
  5624. text='Enter a Tool Diameter:',
  5625. min=0.0000, max=99.9999, decimals=4)
  5626. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5627. val, ok = tool_add_popup.get_value()
  5628. # and only if the tool is NCC Tool
  5629. if tool_widget == self.ncclear_tool.toolName:
  5630. if ok:
  5631. if float(val) == 0:
  5632. self.inform.emit('[WARNING_NOTCL] %s' %
  5633. _("Please enter a tool diameter with non-zero value, in Float format."))
  5634. return
  5635. self.ncclear_tool.on_tool_add(dia=float(val))
  5636. else:
  5637. self.inform.emit('[WARNING_NOTCL] %s...' %
  5638. _("Adding Tool cancelled"))
  5639. # and only if the tool is Paint Area Tool
  5640. elif tool_widget == self.paint_tool.toolName:
  5641. if ok:
  5642. if float(val) == 0:
  5643. self.inform.emit('[WARNING_NOTCL] %s' %
  5644. _("Please enter a tool diameter with non-zero value, in Float format."))
  5645. return
  5646. self.paint_tool.on_tool_add(dia=float(val))
  5647. else:
  5648. self.inform.emit('[WARNING_NOTCL] %s...' %
  5649. _("Adding Tool cancelled"))
  5650. # and only if the tool is Solder Paste Dispensing Tool
  5651. elif tool_widget == self.paste_tool.toolName:
  5652. if ok:
  5653. if float(val) == 0:
  5654. self.inform.emit('[WARNING_NOTCL] %s' %
  5655. _("Please enter a tool diameter with non-zero value, in Float format."))
  5656. return
  5657. self.paste_tool.on_tool_add(dia=float(val))
  5658. else:
  5659. self.inform.emit('[WARNING_NOTCL] %s...' %
  5660. _("Adding Tool cancelled"))
  5661. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5662. # See description bellow.
  5663. def on_delete_keypress(self):
  5664. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5665. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5666. if notebook_widget_name == 'selected_tab':
  5667. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5668. self.collection.get_active().on_tool_delete()
  5669. # work only if the notebook tab on focus is the Tools_Tab
  5670. elif notebook_widget_name == 'tool_tab':
  5671. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5672. # and only if the tool is NCC Tool
  5673. if tool_widget == self.ncclear_tool.toolName:
  5674. self.ncclear_tool.on_tool_delete()
  5675. # and only if the tool is Paint Tool
  5676. elif tool_widget == self.paint_tool.toolName:
  5677. self.paint_tool.on_tool_delete()
  5678. # and only if the tool is Solder Paste Dispensing Tool
  5679. elif tool_widget == self.paste_tool.toolName:
  5680. self.paste_tool.on_tool_delete()
  5681. else:
  5682. self.on_delete()
  5683. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5684. # some screens you have to be careful where you hover with your mouse.
  5685. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5686. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5687. # Complicated, I know :)
  5688. def on_delete(self):
  5689. """
  5690. Delete the currently selected FlatCAMObjs.
  5691. :return: None
  5692. """
  5693. self.report_usage("on_delete()")
  5694. response = None
  5695. bt_ok = None
  5696. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5697. # a geometry object before we update it.
  5698. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5699. and self.grb_editor.editor_active is False:
  5700. if self.defaults["global_delete_confirmation"] is True:
  5701. msgbox = QtWidgets.QMessageBox()
  5702. msgbox.setWindowTitle(_("Delete objects"))
  5703. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  5704. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5705. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5706. "the selected objects?"))
  5707. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5708. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5709. msgbox.setDefaultButton(bt_ok)
  5710. msgbox.exec_()
  5711. response = msgbox.clickedButton()
  5712. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  5713. if self.collection.get_active():
  5714. self.log.debug("App.on_delete()")
  5715. while self.collection.get_active():
  5716. obj_active = self.collection.get_active()
  5717. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  5718. if isinstance(obj_active, FlatCAMGerber):
  5719. for el in obj_active.mark_shapes:
  5720. obj_active.mark_shapes[el].clear(update=True)
  5721. obj_active.mark_shapes[el].enabled = False
  5722. # obj_active.mark_shapes[el] = None
  5723. del el
  5724. elif isinstance(obj_active, FlatCAMCNCjob):
  5725. try:
  5726. obj_active.annotation.clear(update=True)
  5727. obj_active.annotation.enabled = False
  5728. except AttributeError:
  5729. pass
  5730. self.delete_first_selected()
  5731. self.inform.emit('%s...' %
  5732. _("Object(s) deleted"))
  5733. # make sure that the selection shape is deleted, too
  5734. self.delete_selection_shape()
  5735. else:
  5736. self.inform.emit(_("Failed. No object(s) selected..."))
  5737. else:
  5738. self.inform.emit(_("Save the work in Editor and try again ..."))
  5739. def delete_first_selected(self):
  5740. # Keep this for later
  5741. try:
  5742. sel_obj = self.collection.get_active()
  5743. name = sel_obj.options["name"]
  5744. isPlotted = sel_obj.options["plot"]
  5745. except AttributeError:
  5746. self.log.debug("Nothing selected for deletion")
  5747. return
  5748. if self.is_legacy is True:
  5749. # Remove plot only if the object was plotted otherwise delaxes will fail
  5750. if isPlotted:
  5751. try:
  5752. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  5753. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  5754. except Exception as e:
  5755. log.debug("App.delete_first_selected() --> %s" % str(e))
  5756. self.plotcanvas.auto_adjust_axes()
  5757. # Remove from dictionary
  5758. self.collection.delete_active()
  5759. # Clear form
  5760. self.setup_component_editor()
  5761. self.inform.emit('%s: %s' %
  5762. (_("Object deleted"), name))
  5763. def on_set_origin(self):
  5764. """
  5765. Set the origin to the left mouse click position
  5766. :return: None
  5767. """
  5768. # display the message for the user
  5769. # and ask him to click on the desired position
  5770. self.report_usage("on_set_origin()")
  5771. def origin_replot():
  5772. def worker_task():
  5773. with self.proc_container.new('%s...' % _("Plotting")):
  5774. for obj in self.collection.get_list():
  5775. obj.plot()
  5776. self.plotcanvas.fit_view()
  5777. if self.is_legacy:
  5778. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  5779. else:
  5780. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  5781. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5782. self.inform.emit(_('Click to set the origin ...'))
  5783. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  5784. # first disconnect it as it may have been used by something else
  5785. try:
  5786. self.replot_signal.disconnect()
  5787. except TypeError:
  5788. pass
  5789. self.replot_signal[list].connect(origin_replot)
  5790. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  5791. """
  5792. :param event:
  5793. :param location:
  5794. :param noplot:
  5795. :param use_thread:
  5796. :return:
  5797. """
  5798. noplot_sig = noplot
  5799. def worker_task():
  5800. with self.proc_container.new(_("Setting Origin...")):
  5801. for obj in self.collection.get_list():
  5802. obj.offset((x, y))
  5803. self.object_changed.emit(obj)
  5804. # Update the object bounding box options
  5805. a, b, c, d = obj.bounds()
  5806. obj.options['xmin'] = a
  5807. obj.options['ymin'] = b
  5808. obj.options['xmax'] = c
  5809. obj.options['ymax'] = d
  5810. self.inform.emit('[success] %s...' %
  5811. _('Origin set'))
  5812. if noplot_sig is False:
  5813. self.replot_signal.emit([])
  5814. if location is not None:
  5815. if len(location) != 2:
  5816. self.inform.emit('[ERROR_NOTCL] %s...' %
  5817. _("Origin coordinates specified but incomplete."))
  5818. return 'fail'
  5819. x, y = location
  5820. if use_thread is True:
  5821. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5822. else:
  5823. worker_task()
  5824. self.should_we_save = True
  5825. return
  5826. if event.button == 1:
  5827. if self.is_legacy is False:
  5828. event_pos = event.pos
  5829. else:
  5830. event_pos = (event.xdata, event.ydata)
  5831. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5832. if self.grid_status() == True:
  5833. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5834. else:
  5835. pos = pos_canvas
  5836. x = 0 - pos[0]
  5837. y = 0 - pos[1]
  5838. if use_thread is True:
  5839. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5840. else:
  5841. worker_task()
  5842. self.should_we_save = True
  5843. def on_jump_to(self, custom_location=None, fit_center=True):
  5844. """
  5845. Jump to a location by setting the mouse cursor location
  5846. :return:
  5847. """
  5848. self.report_usage("on_jump_to()")
  5849. # if self.is_legacy is True:
  5850. # self.inform.emit(_("Not available with the current Graphic Engine Legacy(2D)."))
  5851. # return
  5852. if not custom_location:
  5853. dia_box_location = None
  5854. try:
  5855. dia_box_location = eval(self.clipboard.text())
  5856. except Exception as e:
  5857. pass
  5858. if type(dia_box_location) == tuple:
  5859. dia_box_location = str(dia_box_location)
  5860. else:
  5861. dia_box_location = None
  5862. dia_box = Dialog_box(title=_("Jump to ..."),
  5863. label=_("Enter the coordinates in format X,Y:"),
  5864. icon=QtGui.QIcon('share/jump_to16.png'),
  5865. initial_text=dia_box_location)
  5866. if dia_box.ok is True:
  5867. try:
  5868. location = eval(dia_box.location)
  5869. if not isinstance(location, tuple):
  5870. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  5871. return
  5872. except:
  5873. return
  5874. else:
  5875. return
  5876. else:
  5877. location = custom_location
  5878. if fit_center:
  5879. self.plotcanvas.fit_center(loc=location)
  5880. cursor = QtGui.QCursor()
  5881. if self.is_legacy is False:
  5882. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5883. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  5884. j_pos = (canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  5885. cursor.setPos(j_pos[0], j_pos[1])
  5886. else:
  5887. # find the canvas origin which is in the top left corner
  5888. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5889. # determine the coordinates for the lowest left point of the canvas
  5890. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  5891. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  5892. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  5893. # canvas) and the point (width, height) is in the top-right location
  5894. loc = self.plotcanvas.axes.transData.transform_point(location)
  5895. j_pos = (x0 + loc[0], y0 - loc[1])
  5896. cursor.setPos(j_pos[0], j_pos[1])
  5897. if self.grid_status() == True:
  5898. # Update cursor
  5899. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  5900. symbol='++', edge_color='black', size=self.defaults["global_cursor_size"])
  5901. # Set the position label
  5902. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5903. "<b>Y</b>: %.4f" % (location[0], location[1]))
  5904. # Set the relative position label
  5905. dx = location[0] - float(self.rel_point1[0])
  5906. dy = location[1] - float(self.rel_point1[1])
  5907. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5908. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  5909. self.inform.emit('[success] %s' %
  5910. _("Done."))
  5911. return location
  5912. def on_copy_object(self):
  5913. self.report_usage("on_copy_object()")
  5914. def initialize(obj_init, app):
  5915. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5916. try:
  5917. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5918. except AttributeError:
  5919. pass
  5920. try:
  5921. obj_init.apertures = deepcopy(obj.apertures)
  5922. except AttributeError:
  5923. pass
  5924. try:
  5925. if obj.tools:
  5926. obj_init.tools = deepcopy(obj.tools)
  5927. except Exception as e:
  5928. log.debug("App.on_copy_object() --> %s" % str(e))
  5929. def initialize_excellon(obj_init, app):
  5930. obj_init.tools = deepcopy(obj.tools)
  5931. # drills are offset, so they need to be deep copied
  5932. obj_init.drills = deepcopy(obj.drills)
  5933. # slots are offset, so they need to be deep copied
  5934. obj_init.slots = deepcopy(obj.slots)
  5935. obj_init.create_geometry()
  5936. for obj in self.collection.get_selected():
  5937. obj_name = obj.options["name"]
  5938. try:
  5939. if isinstance(obj, FlatCAMExcellon):
  5940. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  5941. elif isinstance(obj, FlatCAMGerber):
  5942. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  5943. elif isinstance(obj, FlatCAMGeometry):
  5944. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  5945. except Exception as e:
  5946. return "Operation failed: %s" % str(e)
  5947. def on_copy_object2(self, custom_name):
  5948. def initialize_geometry(obj_init, app):
  5949. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5950. try:
  5951. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5952. except AttributeError:
  5953. pass
  5954. try:
  5955. obj_init.apertures = deepcopy(obj.apertures)
  5956. except AttributeError:
  5957. pass
  5958. try:
  5959. if obj.tools:
  5960. obj_init.tools = deepcopy(obj.tools)
  5961. except Exception as e:
  5962. log.debug("on_copy_object2() --> %s" % str(e))
  5963. def initialize_gerber(obj_init, app):
  5964. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5965. obj_init.apertures = deepcopy(obj.apertures)
  5966. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  5967. def initialize_excellon(obj_init, app):
  5968. obj_init.tools = deepcopy(obj.tools)
  5969. # drills are offset, so they need to be deep copied
  5970. obj_init.drills = deepcopy(obj.drills)
  5971. # slots are offset, so they need to be deep copied
  5972. obj_init.slots = deepcopy(obj.slots)
  5973. obj_init.create_geometry()
  5974. for obj in self.collection.get_selected():
  5975. obj_name = obj.options["name"]
  5976. try:
  5977. if isinstance(obj, FlatCAMExcellon):
  5978. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  5979. elif isinstance(obj, FlatCAMGerber):
  5980. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  5981. elif isinstance(obj, FlatCAMGeometry):
  5982. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  5983. except Exception as e:
  5984. return "Operation failed: %s" % str(e)
  5985. def on_rename_object(self, text):
  5986. self.report_usage("on_rename_object()")
  5987. named_obj = self.collection.get_active()
  5988. for obj in named_obj:
  5989. if obj is list:
  5990. self.on_rename_object(text)
  5991. else:
  5992. try:
  5993. obj.options['name'] = text
  5994. except Exception as e:
  5995. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  5996. def convert_any2geo(self):
  5997. self.report_usage("convert_any2geo()")
  5998. def initialize(obj_init, app):
  5999. obj_init.solid_geometry = obj.solid_geometry
  6000. try:
  6001. obj_init.follow_geometry = obj.follow_geometry
  6002. except AttributeError:
  6003. pass
  6004. try:
  6005. obj_init.apertures = obj.apertures
  6006. except AttributeError:
  6007. pass
  6008. try:
  6009. if obj.tools:
  6010. obj_init.tools = obj.tools
  6011. except AttributeError:
  6012. pass
  6013. def initialize_excellon(obj_init, app):
  6014. # objs = self.collection.get_selected()
  6015. # FlatCAMGeometry.merge(objs, obj)
  6016. solid_geo = []
  6017. for tool in obj.tools:
  6018. for geo in obj.tools[tool]['solid_geometry']:
  6019. solid_geo.append(geo)
  6020. obj_init.solid_geometry = deepcopy(solid_geo)
  6021. if not self.collection.get_selected():
  6022. log.warning("App.convert_any2geo --> No object selected")
  6023. self.inform.emit('[WARNING_NOTCL] %s' %
  6024. _("No object is selected. Select an object and try again."))
  6025. return
  6026. for obj in self.collection.get_selected():
  6027. obj_name = obj.options["name"]
  6028. try:
  6029. if isinstance(obj, FlatCAMExcellon):
  6030. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  6031. else:
  6032. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  6033. except Exception as e:
  6034. return "Operation failed: %s" % str(e)
  6035. def convert_any2gerber(self):
  6036. self.report_usage("convert_any2gerber()")
  6037. def initialize_geometry(obj_init, app):
  6038. apertures = {}
  6039. apid = 0
  6040. apertures[str(apid)] = {}
  6041. apertures[str(apid)]['geometry'] = []
  6042. for obj_orig in obj.solid_geometry:
  6043. new_elem = dict()
  6044. new_elem['solid'] = obj_orig
  6045. new_elem['follow'] = obj_orig.exterior
  6046. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  6047. apertures[str(apid)]['size'] = 0.0
  6048. apertures[str(apid)]['type'] = 'C'
  6049. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6050. obj_init.apertures = deepcopy(apertures)
  6051. def initialize_excellon(obj_init, app):
  6052. apertures = {}
  6053. apid = 10
  6054. for tool in obj.tools:
  6055. apertures[str(apid)] = {}
  6056. apertures[str(apid)]['geometry'] = []
  6057. for geo in obj.tools[tool]['solid_geometry']:
  6058. new_el = dict()
  6059. new_el['solid'] = geo
  6060. new_el['follow'] = geo.exterior
  6061. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  6062. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  6063. apertures[str(apid)]['type'] = 'C'
  6064. apid += 1
  6065. # create solid_geometry
  6066. solid_geometry = []
  6067. for apid in apertures:
  6068. for geo_el in apertures[apid]['geometry']:
  6069. solid_geometry.append(geo_el['solid'])
  6070. solid_geometry = MultiPolygon(solid_geometry)
  6071. solid_geometry = solid_geometry.buffer(0.0000001)
  6072. obj_init.solid_geometry = deepcopy(solid_geometry)
  6073. obj_init.apertures = deepcopy(apertures)
  6074. # clear the working objects (perhaps not necessary due of Python GC)
  6075. apertures.clear()
  6076. if not self.collection.get_selected():
  6077. log.warning("App.convert_any2gerber --> No object selected")
  6078. self.inform.emit('[WARNING_NOTCL] %s' %
  6079. _("No object is selected. Select an object and try again."))
  6080. return
  6081. for obj in self.collection.get_selected():
  6082. obj_name = obj.options["name"]
  6083. try:
  6084. if isinstance(obj, FlatCAMExcellon):
  6085. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  6086. elif isinstance(obj, FlatCAMGeometry):
  6087. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  6088. else:
  6089. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  6090. except Exception as e:
  6091. return "Operation failed: %s" % str(e)
  6092. def abort_all_tasks(self):
  6093. if self.abort_flag is False:
  6094. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  6095. self.abort_flag = True
  6096. def app_is_idle(self):
  6097. if self.abort_flag:
  6098. self.inform.emit('[WARNING_NOTCL] %s' %
  6099. _("The current task was gracefully closed on user request..."))
  6100. self.abort_flag = False
  6101. def on_selectall(self):
  6102. self.report_usage("on_selectall()")
  6103. # delete the possible selection box around a possible selected object
  6104. self.delete_selection_shape()
  6105. for name in self.collection.get_names():
  6106. self.collection.set_active(name)
  6107. curr_sel_obj = self.collection.get_by_name(name)
  6108. # create the selection box around the selected object
  6109. if self.defaults['global_selection_shape'] is True:
  6110. self.draw_selection_shape(curr_sel_obj)
  6111. def on_preferences(self):
  6112. # add the tab if it was closed
  6113. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  6114. # delete the absolute and relative position and messages in the infobar
  6115. self.ui.position_label.setText("")
  6116. self.ui.rel_position_label.setText("")
  6117. # Switch plot_area to preferences page
  6118. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  6119. # self.ui.show()
  6120. # this disconnect() is done so the slot will be connected only once
  6121. try:
  6122. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_preferences_closed)
  6123. except (TypeError, AttributeError):
  6124. pass
  6125. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_preferences_closed)
  6126. # detect changes in the preferences
  6127. for idx in range(self.ui.pref_tab_area.count()):
  6128. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6129. try:
  6130. try:
  6131. tb.textEdited.disconnect(self.on_preferences_edited)
  6132. except (TypeError, AttributeError):
  6133. pass
  6134. tb.textEdited.connect(self.on_preferences_edited)
  6135. except AttributeError:
  6136. pass
  6137. try:
  6138. try:
  6139. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6140. except (TypeError, AttributeError):
  6141. pass
  6142. tb.modificationChanged.connect(self.on_preferences_edited)
  6143. except AttributeError:
  6144. pass
  6145. try:
  6146. try:
  6147. tb.toggled.disconnect(self.on_preferences_edited)
  6148. except (TypeError, AttributeError):
  6149. pass
  6150. tb.toggled.connect(self.on_preferences_edited)
  6151. except AttributeError:
  6152. pass
  6153. try:
  6154. try:
  6155. tb.valueChanged.disconnect(self.on_preferences_edited)
  6156. except (TypeError, AttributeError):
  6157. pass
  6158. tb.valueChanged.connect(self.on_preferences_edited)
  6159. except AttributeError:
  6160. pass
  6161. try:
  6162. try:
  6163. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6164. except (TypeError, AttributeError):
  6165. pass
  6166. tb.currentIndexChanged.connect(self.on_preferences_edited)
  6167. except AttributeError:
  6168. pass
  6169. def on_preferences_edited(self):
  6170. self.inform.emit('[WARNING_NOTCL] %s' %
  6171. _("Preferences edited but not saved."))
  6172. self.preferences_changed_flag = True
  6173. def on_preferences_closed(self):
  6174. # disconnect
  6175. for idx in range(self.ui.pref_tab_area.count()):
  6176. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6177. try:
  6178. tb.textEdited.disconnect(self.on_preferences_edited)
  6179. except (TypeError, AttributeError):
  6180. pass
  6181. try:
  6182. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6183. except (TypeError, AttributeError):
  6184. pass
  6185. try:
  6186. tb.toggled.disconnect(self.on_preferences_edited)
  6187. except (TypeError, AttributeError):
  6188. pass
  6189. try:
  6190. tb.valueChanged.disconnect(self.on_preferences_edited)
  6191. except (TypeError, AttributeError):
  6192. pass
  6193. try:
  6194. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6195. except (TypeError, AttributeError):
  6196. pass
  6197. if self.preferences_changed_flag is True:
  6198. msgbox = QtWidgets.QMessageBox()
  6199. msgbox.setText(_("One or more values are changed.\n"
  6200. "Do you want to save the Preferences?"))
  6201. msgbox.setWindowTitle(_("Save Preferences"))
  6202. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6203. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6204. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6205. msgbox.setDefaultButton(bt_yes)
  6206. msgbox.exec_()
  6207. response = msgbox.clickedButton()
  6208. if response == bt_yes:
  6209. self.on_save_button()
  6210. self.inform.emit('[success] %s' %
  6211. _("Preferences saved."))
  6212. else:
  6213. self.preferences_changed_flag = False
  6214. return
  6215. def on_flipy(self):
  6216. self.report_usage("on_flipy()")
  6217. obj_list = self.collection.get_selected()
  6218. xminlist = []
  6219. yminlist = []
  6220. xmaxlist = []
  6221. ymaxlist = []
  6222. if not obj_list:
  6223. self.inform.emit('[WARNING_NOTCL] %s' %
  6224. _("No object selected to Flip on Y axis."))
  6225. else:
  6226. try:
  6227. # first get a bounding box to fit all
  6228. for obj in obj_list:
  6229. xmin, ymin, xmax, ymax = obj.bounds()
  6230. xminlist.append(xmin)
  6231. yminlist.append(ymin)
  6232. xmaxlist.append(xmax)
  6233. ymaxlist.append(ymax)
  6234. # get the minimum x,y and maximum x,y for all objects selected
  6235. xminimal = min(xminlist)
  6236. yminimal = min(yminlist)
  6237. xmaximal = max(xmaxlist)
  6238. ymaximal = max(ymaxlist)
  6239. px = 0.5 * (xminimal + xmaximal)
  6240. py = 0.5 * (yminimal + ymaximal)
  6241. # execute mirroring
  6242. for obj in obj_list:
  6243. obj.mirror('X', [px, py])
  6244. obj.plot()
  6245. self.object_changed.emit(obj)
  6246. self.inform.emit('[success] %s' %
  6247. _("Flip on Y axis done."))
  6248. except Exception as e:
  6249. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6250. (_("Flip action was not executed."), str(e)))
  6251. return
  6252. def on_flipx(self):
  6253. self.report_usage("on_flipx()")
  6254. obj_list = self.collection.get_selected()
  6255. xminlist = []
  6256. yminlist = []
  6257. xmaxlist = []
  6258. ymaxlist = []
  6259. if not obj_list:
  6260. self.inform.emit('[WARNING_NOTCL] %s' %
  6261. _("No object selected to Flip on X axis."))
  6262. else:
  6263. try:
  6264. # first get a bounding box to fit all
  6265. for obj in obj_list:
  6266. xmin, ymin, xmax, ymax = obj.bounds()
  6267. xminlist.append(xmin)
  6268. yminlist.append(ymin)
  6269. xmaxlist.append(xmax)
  6270. ymaxlist.append(ymax)
  6271. # get the minimum x,y and maximum x,y for all objects selected
  6272. xminimal = min(xminlist)
  6273. yminimal = min(yminlist)
  6274. xmaximal = max(xmaxlist)
  6275. ymaximal = max(ymaxlist)
  6276. px = 0.5 * (xminimal + xmaximal)
  6277. py = 0.5 * (yminimal + ymaximal)
  6278. # execute mirroring
  6279. for obj in obj_list:
  6280. obj.mirror('Y', [px, py])
  6281. obj.plot()
  6282. self.object_changed.emit(obj)
  6283. self.inform.emit('[success] %s' %
  6284. _("Flip on X axis done."))
  6285. except Exception as e:
  6286. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6287. (_("Flip action was not executed."), str(e)))
  6288. return
  6289. def on_rotate(self, silent=False, preset=None):
  6290. self.report_usage("on_rotate()")
  6291. obj_list = self.collection.get_selected()
  6292. xminlist = []
  6293. yminlist = []
  6294. xmaxlist = []
  6295. ymaxlist = []
  6296. if not obj_list:
  6297. self.inform.emit('[WARNING_NOTCL] %s' %
  6298. _("No object selected to Rotate."))
  6299. else:
  6300. if silent is False:
  6301. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6302. min=-360, max=360, decimals=4,
  6303. init_val=float(self.defaults['tools_transform_rotate']))
  6304. num, ok = rotatebox.get_value()
  6305. else:
  6306. num = preset
  6307. ok = True
  6308. if ok:
  6309. try:
  6310. # first get a bounding box to fit all
  6311. for obj in obj_list:
  6312. xmin, ymin, xmax, ymax = obj.bounds()
  6313. xminlist.append(xmin)
  6314. yminlist.append(ymin)
  6315. xmaxlist.append(xmax)
  6316. ymaxlist.append(ymax)
  6317. # get the minimum x,y and maximum x,y for all objects selected
  6318. xminimal = min(xminlist)
  6319. yminimal = min(yminlist)
  6320. xmaximal = max(xmaxlist)
  6321. ymaximal = max(ymaxlist)
  6322. px = 0.5 * (xminimal + xmaximal)
  6323. py = 0.5 * (yminimal + ymaximal)
  6324. for sel_obj in obj_list:
  6325. sel_obj.rotate(-float(num), point=(px, py))
  6326. sel_obj.plot()
  6327. self.object_changed.emit(sel_obj)
  6328. self.inform.emit('[success] %s' %
  6329. _("Rotation done."))
  6330. except Exception as e:
  6331. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6332. (_("Rotation movement was not executed."), str(e)))
  6333. return
  6334. def on_skewx(self):
  6335. self.report_usage("on_skewx()")
  6336. obj_list = self.collection.get_selected()
  6337. xminlist = []
  6338. yminlist = []
  6339. if not obj_list:
  6340. self.inform.emit('[WARNING_NOTCL] %s' %
  6341. _("No object selected to Skew/Shear on X axis."))
  6342. else:
  6343. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6344. min=-360, max=360, decimals=4,
  6345. init_val=float(self.defaults['tools_transform_skew_x']))
  6346. num, ok = skewxbox.get_value()
  6347. if ok:
  6348. # first get a bounding box to fit all
  6349. for obj in obj_list:
  6350. xmin, ymin, xmax, ymax = obj.bounds()
  6351. xminlist.append(xmin)
  6352. yminlist.append(ymin)
  6353. # get the minimum x,y and maximum x,y for all objects selected
  6354. xminimal = min(xminlist)
  6355. yminimal = min(yminlist)
  6356. for obj in obj_list:
  6357. obj.skew(num, 0, point=(xminimal, yminimal))
  6358. obj.plot()
  6359. self.object_changed.emit(obj)
  6360. self.inform.emit('[success] %s' %
  6361. _("Skew on X axis done."))
  6362. def on_skewy(self):
  6363. self.report_usage("on_skewy()")
  6364. obj_list = self.collection.get_selected()
  6365. xminlist = []
  6366. yminlist = []
  6367. if not obj_list:
  6368. self.inform.emit('[WARNING_NOTCL] %s' %
  6369. _("No object selected to Skew/Shear on Y axis."))
  6370. else:
  6371. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6372. min=-360, max=360, decimals=4,
  6373. init_val=float(self.defaults['tools_transform_skew_y']))
  6374. num, ok = skewybox.get_value()
  6375. if ok:
  6376. # first get a bounding box to fit all
  6377. for obj in obj_list:
  6378. xmin, ymin, xmax, ymax = obj.bounds()
  6379. xminlist.append(xmin)
  6380. yminlist.append(ymin)
  6381. # get the minimum x,y and maximum x,y for all objects selected
  6382. xminimal = min(xminlist)
  6383. yminimal = min(yminlist)
  6384. for obj in obj_list:
  6385. obj.skew(0, num, point=(xminimal, yminimal))
  6386. obj.plot()
  6387. self.object_changed.emit(obj)
  6388. self.inform.emit('[success] %s' %
  6389. _("Skew on Y axis done."))
  6390. def on_plots_updated(self):
  6391. """
  6392. Callback used to report when the plots have changed.
  6393. Adjust axes and zooms to fit.
  6394. :return: None
  6395. """
  6396. if self.is_legacy is False:
  6397. self.plotcanvas.update() # TODO: Need update canvas?
  6398. else:
  6399. self.plotcanvas.auto_adjust_axes()
  6400. self.on_zoom_fit(None)
  6401. self.collection.update_view()
  6402. # self.inform.emit(_("Plots updated ..."))
  6403. # TODO: Rework toolbar 'clear', 'replot' functions
  6404. def on_toolbar_replot(self):
  6405. """
  6406. Callback for toolbar button. Re-plots all objects.
  6407. :return: None
  6408. """
  6409. self.report_usage("on_toolbar_replot")
  6410. self.log.debug("on_toolbar_replot()")
  6411. try:
  6412. self.collection.get_active().read_form()
  6413. except AttributeError:
  6414. self.log.debug("on_toolbar_replot(): AttributeError")
  6415. pass
  6416. self.plot_all()
  6417. def on_row_activated(self, index):
  6418. if index.isValid():
  6419. if index.internalPointer().parent_item != self.collection.root_item:
  6420. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6421. self.collection.on_item_activated(index)
  6422. def grid_status(self):
  6423. if self.ui.grid_snap_btn.isChecked():
  6424. return True
  6425. else:
  6426. return False
  6427. def populate_cmenu_grids(self):
  6428. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6429. self.ui.cmenu_gridmenu.clear()
  6430. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  6431. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  6432. grid_toggle.setCheckable(True)
  6433. if self.grid_status() == True:
  6434. grid_toggle.setChecked(True)
  6435. else:
  6436. grid_toggle.setChecked(False)
  6437. self.ui.cmenu_gridmenu.addSeparator()
  6438. for grid in sorted_list:
  6439. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  6440. action.triggered.connect(self.set_grid)
  6441. self.ui.cmenu_gridmenu.addSeparator()
  6442. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  6443. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  6444. grid_add.triggered.connect(self.on_grid_add)
  6445. grid_delete.triggered.connect(self.on_grid_delete)
  6446. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  6447. def set_grid(self):
  6448. self.ui.grid_gap_x_entry.setText(self.sender().text())
  6449. self.ui.grid_gap_y_entry.setText(self.sender().text())
  6450. def on_grid_add(self):
  6451. # ## Current application units in lower Case
  6452. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6453. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  6454. text=_('Enter a Grid Value:'),
  6455. min=0.0000, max=99.9999, decimals=4)
  6456. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  6457. val, ok = grid_add_popup.get_value()
  6458. if ok:
  6459. if float(val) == 0:
  6460. self.inform.emit('[WARNING_NOTCL] %s' %
  6461. _("Please enter a grid value with non-zero value, in Float format."))
  6462. return
  6463. else:
  6464. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  6465. self.defaults["global_grid_context_menu"][str(units)].append(val)
  6466. self.inform.emit('[success] %s...' %
  6467. _("New Grid added"))
  6468. else:
  6469. self.inform.emit('[WARNING_NOTCL] %s...' %
  6470. _("Grid already exists"))
  6471. else:
  6472. self.inform.emit('[WARNING_NOTCL] %s...' %
  6473. _("Adding New Grid cancelled"))
  6474. def on_grid_delete(self):
  6475. # ## Current application units in lower Case
  6476. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6477. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  6478. text='Enter a Grid Value:',
  6479. min=0.0000, max=99.9999, decimals=4)
  6480. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  6481. val, ok = grid_del_popup.get_value()
  6482. if ok:
  6483. if float(val) == 0:
  6484. self.inform.emit('[WARNING_NOTCL] %s' %
  6485. _("Please enter a grid value with non-zero value, in Float format."))
  6486. return
  6487. else:
  6488. try:
  6489. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  6490. except ValueError:
  6491. self.inform.emit('[ERROR_NOTCL]%s...' %
  6492. _(" Grid Value does not exist"))
  6493. return
  6494. self.inform.emit('[success] %s...' %
  6495. _("Grid Value deleted"))
  6496. else:
  6497. self.inform.emit('[WARNING_NOTCL] %s...' %
  6498. _("Delete Grid value cancelled"))
  6499. def on_shortcut_list(self):
  6500. self.report_usage("on_shortcut_list()")
  6501. # add the tab if it was closed
  6502. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  6503. # delete the absolute and relative position and messages in the infobar
  6504. self.ui.position_label.setText("")
  6505. self.ui.rel_position_label.setText("")
  6506. # Switch plot_area to preferences page
  6507. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  6508. # self.ui.show()
  6509. def on_select_tab(self, name):
  6510. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  6511. if self.ui.splitter.sizes()[0] == 0:
  6512. self.ui.splitter.setSizes([1, 1])
  6513. else:
  6514. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  6515. self.ui.splitter.setSizes([0, 1])
  6516. if name == 'project':
  6517. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6518. elif name == 'selected':
  6519. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6520. elif name == 'tool':
  6521. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  6522. def on_copy_name(self):
  6523. self.report_usage("on_copy_name()")
  6524. obj = self.collection.get_active()
  6525. try:
  6526. name = obj.options["name"]
  6527. except AttributeError:
  6528. log.debug("on_copy_name() --> No object selected to copy it's name")
  6529. self.inform.emit('[WARNING_NOTCL]%s' %
  6530. _(" No object selected to copy it's name"))
  6531. return
  6532. self.clipboard.setText(name)
  6533. self.inform.emit(_("Name copied on clipboard ..."))
  6534. def on_mouse_click_over_plot(self, event):
  6535. """
  6536. Default actions are:
  6537. :param event: Contains information about the event, like which button
  6538. was clicked, the pixel coordinates and the axes coordinates.
  6539. :return: None
  6540. """
  6541. self.pos = []
  6542. if self.is_legacy is False:
  6543. event_pos = event.pos
  6544. if self.defaults["global_pan_button"] == '2':
  6545. pan_button = 2
  6546. else:
  6547. pan_button = 3
  6548. # Set the mouse button for panning
  6549. self.plotcanvas.view.camera.pan_button_setting = pan_button
  6550. else:
  6551. event_pos = (event.xdata, event.ydata)
  6552. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6553. if self.defaults["global_pan_button"] == '2':
  6554. pan_button = 3
  6555. else:
  6556. pan_button = 2
  6557. # So it can receive key presses
  6558. self.plotcanvas.native.setFocus()
  6559. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6560. if self.grid_status() == True:
  6561. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  6562. else:
  6563. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  6564. try:
  6565. if event.button == 1:
  6566. # Reset here the relative coordinates so there is a new reference on the click position
  6567. if self.rel_point1 is None:
  6568. self.rel_point1 = self.pos
  6569. else:
  6570. self.rel_point2 = copy(self.rel_point1)
  6571. self.rel_point1 = self.pos
  6572. self.on_mouse_move_over_plot(event, origin_click=True)
  6573. except Exception as e:
  6574. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  6575. def on_double_click_over_plot(self, event):
  6576. if event.button == 1:
  6577. self.doubleclick = True
  6578. def on_mouse_move_over_plot(self, event, origin_click=None):
  6579. """
  6580. Callback for the mouse motion event over the plot.
  6581. :param event: Contains information about the event.
  6582. :param origin_click
  6583. :return: None
  6584. """
  6585. if self.is_legacy is False:
  6586. event_pos = event.pos
  6587. if self.defaults["global_pan_button"] == '2':
  6588. pan_button = 2
  6589. else:
  6590. pan_button = 3
  6591. event_is_dragging = event.is_dragging
  6592. else:
  6593. event_pos = (event.xdata, event.ydata)
  6594. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6595. if self.defaults["global_pan_button"] == '2':
  6596. pan_button = 3
  6597. else:
  6598. pan_button = 2
  6599. event_is_dragging = self.plotcanvas.is_dragging
  6600. # So it can receive key presses
  6601. self.plotcanvas.native.setFocus()
  6602. self.pos_jump = event_pos
  6603. self.ui.popMenu.mouse_is_panning = False
  6604. if not origin_click:
  6605. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  6606. if event.button == pan_button and event_is_dragging == 1:
  6607. self.ui.popMenu.mouse_is_panning = True
  6608. return
  6609. if self.rel_point1 is not None:
  6610. try: # May fail in case mouse not within axes
  6611. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6612. if self.grid_status() == True:
  6613. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6614. # Update cursor
  6615. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  6616. symbol='++', edge_color='black', size=self.defaults["global_cursor_size"])
  6617. else:
  6618. pos = (pos_canvas[0], pos_canvas[1])
  6619. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6620. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  6621. dx = pos[0] - float(self.rel_point1[0])
  6622. dy = pos[1] - float(self.rel_point1[1])
  6623. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6624. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6625. self.mouse = [pos[0], pos[1]]
  6626. # if the mouse is moved and the LMB is clicked then the action is a selection
  6627. if event_is_dragging == 1 and event.button == 1:
  6628. self.delete_selection_shape()
  6629. if dx < 0:
  6630. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  6631. face_color=self.defaults['global_alt_sel_fill'])
  6632. self.selection_type = False
  6633. elif dx > 0:
  6634. self.draw_moving_selection_shape(self.pos, pos)
  6635. self.selection_type = True
  6636. else:
  6637. self.selection_type = None
  6638. # hover effect - enabled in Preferences -> General -> GUI Settings
  6639. if self.defaults['global_hover']:
  6640. for obj in self.collection.get_list():
  6641. try:
  6642. # select the object(s) only if it is enabled (plotted)
  6643. if obj.options['plot']:
  6644. if obj not in self.collection.get_selected():
  6645. poly_obj = Polygon(
  6646. [(obj.options['xmin'], obj.options['ymin']),
  6647. (obj.options['xmax'], obj.options['ymin']),
  6648. (obj.options['xmax'], obj.options['ymax']),
  6649. (obj.options['xmin'], obj.options['ymax'])]
  6650. )
  6651. if Point(pos).within(poly_obj):
  6652. if obj.isHovering is False:
  6653. obj.isHovering = True
  6654. obj.notHovering = True
  6655. # create the selection box around the selected object
  6656. self.draw_hover_shape(obj, color='#d1e0e0FF')
  6657. else:
  6658. if obj.notHovering is True:
  6659. obj.notHovering = False
  6660. obj.isHovering = False
  6661. self.delete_hover_shape()
  6662. except:
  6663. # the Exception here will happen if we try to select on screen and we have an
  6664. # newly (and empty) just created Geometry or Excellon object that do not have the
  6665. # xmin, xmax, ymin, ymax options.
  6666. # In this case poly_obj creation (see above) will fail
  6667. pass
  6668. except:
  6669. self.ui.position_label.setText("")
  6670. self.ui.rel_position_label.setText("")
  6671. self.mouse = None
  6672. def on_mouse_click_release_over_plot(self, event):
  6673. """
  6674. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  6675. and has been registered in ''self.__init__()''.
  6676. :param event: contains information about the event.
  6677. :return:
  6678. """
  6679. pos = 0, 0
  6680. if self.is_legacy is False:
  6681. event_pos = event.pos
  6682. right_button = 2
  6683. else:
  6684. event_pos = (event.xdata, event.ydata)
  6685. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6686. right_button = 3
  6687. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6688. if self.grid_status() == True:
  6689. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6690. else:
  6691. pos = (pos_canvas[0], pos_canvas[1])
  6692. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  6693. # canvas menu
  6694. if event.button == right_button: # right click
  6695. if self.ui.popMenu.mouse_is_panning is False:
  6696. self.cursor = QtGui.QCursor()
  6697. self.populate_cmenu_grids()
  6698. self.ui.popMenu.popup(self.cursor.pos())
  6699. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  6700. # selection and then select a type of selection ("enclosing" or "touching")
  6701. try:
  6702. if event.button == 1: # left click
  6703. modifiers = QtWidgets.QApplication.keyboardModifiers()
  6704. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  6705. if modifiers == QtCore.Qt.ShiftModifier:
  6706. # do not auto open the Project Tab
  6707. self.click_noproject = True
  6708. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  6709. self.inform.emit('[success] %s' %
  6710. _("Coordinates copied to clipboard."))
  6711. return
  6712. if self.doubleclick is True:
  6713. self.doubleclick = False
  6714. if self.collection.get_selected():
  6715. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6716. if self.ui.splitter.sizes()[0] == 0:
  6717. self.ui.splitter.setSizes([1, 1])
  6718. # delete the selection shape(S) as it may be in the way
  6719. self.delete_selection_shape()
  6720. self.delete_hover_shape()
  6721. else:
  6722. if self.selection_type is not None:
  6723. self.selection_area_handler(self.pos, pos, self.selection_type)
  6724. self.selection_type = None
  6725. else:
  6726. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  6727. if key_modifier == QtCore.Qt.ShiftModifier:
  6728. mod_key = 'Shift'
  6729. elif key_modifier == QtCore.Qt.ControlModifier:
  6730. mod_key = 'Control'
  6731. else:
  6732. mod_key = None
  6733. if mod_key == self.defaults["global_mselect_key"]:
  6734. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  6735. # deselect, and if it's not selected then it will be selected
  6736. # If there is no active command (self.command_active is None) then we check if we clicked
  6737. # on a object by checking the bounding limits against mouse click position
  6738. if self.command_active is None:
  6739. self.select_objects(key='CTRL')
  6740. self.delete_hover_shape()
  6741. else:
  6742. # If there is no active command (self.command_active is None) then we check if we clicked
  6743. # on a object by checking the bounding limits against mouse click position
  6744. if self.command_active is None:
  6745. self.select_objects()
  6746. self.delete_hover_shape()
  6747. except Exception as e:
  6748. log.warning("Error: %s" % str(e))
  6749. return
  6750. def selection_area_handler(self, start_pos, end_pos, sel_type):
  6751. """
  6752. :param start_pos: mouse position when the selection LMB click was done
  6753. :param end_pos: mouse position when the left mouse button is released
  6754. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  6755. :return:
  6756. """
  6757. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  6758. self.delete_selection_shape()
  6759. for obj in self.collection.get_list():
  6760. try:
  6761. # select the object(s) only if it is enabled (plotted)
  6762. if obj.options['plot']:
  6763. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  6764. (obj.options['xmax'], obj.options['ymin']),
  6765. (obj.options['xmax'], obj.options['ymax']),
  6766. (obj.options['xmin'], obj.options['ymax'])])
  6767. if sel_type is True:
  6768. if poly_obj.within(poly_selection):
  6769. # create the selection box around the selected object
  6770. if self.defaults['global_selection_shape'] is True:
  6771. self.draw_selection_shape(obj)
  6772. self.collection.set_active(obj.options['name'])
  6773. else:
  6774. if poly_selection.intersects(poly_obj):
  6775. # create the selection box around the selected object
  6776. if self.defaults['global_selection_shape'] is True:
  6777. self.draw_selection_shape(obj)
  6778. self.collection.set_active(obj.options['name'])
  6779. except Exception as e:
  6780. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  6781. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  6782. # In this case poly_obj creation (see above) will fail
  6783. log.debug("App.selection_area_handler() --> %s" % str(e))
  6784. def select_objects(self, key=None):
  6785. # list where we store the overlapped objects under our mouse left click position
  6786. objects_under_the_click_list = []
  6787. # Populate the list with the overlapped objects on the click position
  6788. curr_x, curr_y = self.pos
  6789. for obj in self.all_objects_list:
  6790. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  6791. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  6792. if obj.options['name'] not in objects_under_the_click_list:
  6793. if obj.options['plot']:
  6794. # add objects to the objects_under_the_click list only if the object is plotted
  6795. # (active and not disabled)
  6796. objects_under_the_click_list.append(obj.options['name'])
  6797. try:
  6798. # If there is no element in the overlapped objects list then make everyone inactive
  6799. # because we selected "nothing"
  6800. if not objects_under_the_click_list:
  6801. self.collection.set_all_inactive()
  6802. # delete the possible selection box around a possible selected object
  6803. self.delete_selection_shape()
  6804. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  6805. # only when working on App
  6806. if self.call_source == 'app':
  6807. if self.click_noproject is False:
  6808. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6809. else:
  6810. # restore auto open the Project Tab
  6811. self.click_noproject = False
  6812. # delete any text in the status bar, implicitly the last object name that was selected
  6813. self.inform.emit("")
  6814. else:
  6815. self.call_source = 'app'
  6816. else:
  6817. # case when there is only an object under the click and we toggle it
  6818. if len(objects_under_the_click_list) == 1:
  6819. if self.collection.get_active() is None:
  6820. self.collection.set_active(objects_under_the_click_list[0])
  6821. # create the selection box around the selected object
  6822. curr_sel_obj = self.collection.get_active()
  6823. if self.defaults['global_selection_shape'] is True:
  6824. self.draw_selection_shape(curr_sel_obj)
  6825. # self.inform.emit('[selected] %s: %s selected' %
  6826. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6827. if curr_sel_obj.kind == 'gerber':
  6828. self.inform.emit(
  6829. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6830. color='green', name=str(curr_sel_obj.options['name'])))
  6831. elif curr_sel_obj.kind == 'excellon':
  6832. self.inform.emit(
  6833. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6834. color='brown', name=str(curr_sel_obj.options['name'])))
  6835. elif curr_sel_obj.kind == 'cncjob':
  6836. self.inform.emit(
  6837. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6838. color='blue', name=str(curr_sel_obj.options['name'])))
  6839. elif curr_sel_obj.kind == 'geometry':
  6840. self.inform.emit(
  6841. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6842. color='red', name=str(curr_sel_obj.options['name'])))
  6843. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  6844. self.collection.set_all_inactive()
  6845. self.delete_selection_shape()
  6846. self.collection.set_active(objects_under_the_click_list[0])
  6847. # create the selection box around the selected object
  6848. curr_sel_obj = self.collection.get_active()
  6849. if self.defaults['global_selection_shape'] is True:
  6850. self.draw_selection_shape(curr_sel_obj)
  6851. # self.inform.emit('[selected] %s: %s selected' %
  6852. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6853. if curr_sel_obj.kind == 'gerber':
  6854. self.inform.emit(
  6855. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6856. color='green', name=str(curr_sel_obj.options['name'])))
  6857. elif curr_sel_obj.kind == 'excellon':
  6858. self.inform.emit(
  6859. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6860. color='brown', name=str(curr_sel_obj.options['name'])))
  6861. elif curr_sel_obj.kind == 'cncjob':
  6862. self.inform.emit(
  6863. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6864. color='blue', name=str(curr_sel_obj.options['name'])))
  6865. elif curr_sel_obj.kind == 'geometry':
  6866. self.inform.emit(
  6867. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6868. color='red', name=str(curr_sel_obj.options['name'])))
  6869. else:
  6870. self.collection.set_all_inactive()
  6871. self.delete_selection_shape()
  6872. if self.call_source == 'app':
  6873. # delete any text in the status bar, implicitly the last object name that was selected
  6874. self.inform.emit("")
  6875. else:
  6876. self.call_source = 'app'
  6877. else:
  6878. # If there is no selected object
  6879. # make active the first element of the overlapped objects list
  6880. if self.collection.get_active() is None:
  6881. self.collection.set_active(objects_under_the_click_list[0])
  6882. name_sel_obj = self.collection.get_active().options['name']
  6883. # In case that there is a selected object but it is not in the overlapped object list
  6884. # make that object inactive and activate the first element in the overlapped object list
  6885. if name_sel_obj not in objects_under_the_click_list:
  6886. self.collection.set_inactive(name_sel_obj)
  6887. name_sel_obj = objects_under_the_click_list[0]
  6888. self.collection.set_active(name_sel_obj)
  6889. else:
  6890. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  6891. self.collection.set_all_inactive()
  6892. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  6893. len(objects_under_the_click_list)])
  6894. curr_sel_obj = self.collection.get_active()
  6895. # delete the possible selection box around a possible selected object
  6896. self.delete_selection_shape()
  6897. # create the selection box around the selected object
  6898. if self.defaults['global_selection_shape'] is True:
  6899. self.draw_selection_shape(curr_sel_obj)
  6900. # self.inform.emit('[selected] %s: %s selected' %
  6901. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6902. if curr_sel_obj.kind == 'gerber':
  6903. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6904. color='green', name=str(curr_sel_obj.options['name'])))
  6905. elif curr_sel_obj.kind == 'excellon':
  6906. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6907. color='brown', name=str(curr_sel_obj.options['name'])))
  6908. elif curr_sel_obj.kind == 'cncjob':
  6909. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6910. color='blue', name=str(curr_sel_obj.options['name'])))
  6911. elif curr_sel_obj.kind == 'geometry':
  6912. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6913. color='red', name=str(curr_sel_obj.options['name'])))
  6914. # for obj in self.collection.get_list():
  6915. # obj.plot()
  6916. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  6917. # TODO: on selected objects change the object colors and do not draw the selection box
  6918. # self.plotcanvas.update() # this updates the canvas
  6919. except Exception as e:
  6920. log.error("[ERROR] Something went bad. %s" % str(e))
  6921. return
  6922. def delete_hover_shape(self):
  6923. self.hover_shapes.clear()
  6924. self.hover_shapes.redraw()
  6925. def draw_hover_shape(self, sel_obj, color=None):
  6926. """
  6927. :param sel_obj: the object for which the hover shape must be drawn
  6928. :return:
  6929. """
  6930. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6931. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6932. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6933. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6934. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  6935. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6936. hover_rect = hover_rect.buffer(-0.1)
  6937. hover_rect = hover_rect.buffer(0.2)
  6938. else:
  6939. hover_rect = hover_rect.buffer(-0.00393)
  6940. hover_rect = hover_rect.buffer(0.00787)
  6941. # if color:
  6942. # face = Color(color)
  6943. # face.alpha = 0.2
  6944. # outline = Color(color, alpha=0.8)
  6945. # else:
  6946. # face = Color(self.defaults['global_sel_fill'])
  6947. # face.alpha = 0.2
  6948. # outline = self.defaults['global_sel_line']
  6949. if color:
  6950. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  6951. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  6952. else:
  6953. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  6954. outline = self.defaults['global_sel_line']
  6955. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  6956. if self.is_legacy is True:
  6957. self.hover_shapes.redraw()
  6958. def delete_selection_shape(self):
  6959. self.move_tool.sel_shapes.clear()
  6960. self.move_tool.sel_shapes.redraw()
  6961. def draw_selection_shape(self, sel_obj, color=None):
  6962. """
  6963. :param sel_obj: the object for which the selection shape must be drawn
  6964. :return:
  6965. """
  6966. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6967. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6968. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6969. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6970. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6971. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6972. sel_rect = sel_rect.buffer(-0.1)
  6973. sel_rect = sel_rect.buffer(0.2)
  6974. else:
  6975. sel_rect = sel_rect.buffer(-0.00393)
  6976. sel_rect = sel_rect.buffer(0.00787)
  6977. # if color:
  6978. # face = Color(color, alpha=0.2)
  6979. # outline = Color(color, alpha=0.8)
  6980. # else:
  6981. # face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  6982. # outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  6983. if color:
  6984. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  6985. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  6986. else:
  6987. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  6988. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  6989. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  6990. color=outline,
  6991. face_color=face,
  6992. update=True,
  6993. layer=0,
  6994. tolerance=None))
  6995. if self.is_legacy is True:
  6996. self.move_tool.sel_shapes.redraw()
  6997. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  6998. """
  6999. :param old_coords: old coordinates
  7000. :param coords: new coordinates
  7001. :return:
  7002. """
  7003. if 'color' in kwargs:
  7004. color = kwargs['color']
  7005. else:
  7006. color = self.defaults['global_sel_line']
  7007. if 'face_color' in kwargs:
  7008. face_color = kwargs['face_color']
  7009. else:
  7010. face_color = self.defaults['global_sel_fill']
  7011. if 'face_alpha' in kwargs:
  7012. face_alpha = kwargs['face_alpha']
  7013. else:
  7014. face_alpha = 0.3
  7015. x0, y0 = old_coords
  7016. x1, y1 = coords
  7017. pt1 = (x0, y0)
  7018. pt2 = (x1, y0)
  7019. pt3 = (x1, y1)
  7020. pt4 = (x0, y1)
  7021. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7022. # color_t = Color(face_color)
  7023. # color_t.alpha = face_alpha
  7024. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  7025. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  7026. layer=0, tolerance=None)
  7027. if self.is_legacy is True:
  7028. self.move_tool.sel_shapes.redraw()
  7029. def on_file_new_click(self):
  7030. if self.collection.get_list() and self.should_we_save:
  7031. msgbox = QtWidgets.QMessageBox()
  7032. # msgbox.setText("<B>Save changes ...</B>")
  7033. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7034. "Creating a New project will delete them.\n"
  7035. "Do you want to Save the project?"))
  7036. msgbox.setWindowTitle(_("Save changes"))
  7037. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  7038. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7039. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7040. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7041. msgbox.setDefaultButton(bt_yes)
  7042. msgbox.exec_()
  7043. response = msgbox.clickedButton()
  7044. if response == bt_yes:
  7045. self.on_file_saveprojectas()
  7046. elif response == bt_cancel:
  7047. return
  7048. elif response == bt_no:
  7049. self.on_file_new()
  7050. else:
  7051. self.on_file_new()
  7052. self.inform.emit('[success] %s...' %
  7053. _("New Project created"))
  7054. def on_file_new(self, cli=None):
  7055. """
  7056. Callback for menu item File->New. Returns the application to its
  7057. startup state. This method is thread-safe.
  7058. :return: None
  7059. """
  7060. self.report_usage("on_file_new")
  7061. # Remove everything from memory
  7062. App.log.debug("on_file_new()")
  7063. if self.call_source != 'app':
  7064. self.editor2object(cleanup=True)
  7065. # ## EDITOR section
  7066. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  7067. self.exc_editor = FlatCAMExcEditor(self)
  7068. self.grb_editor = FlatCAMGrbEditor(self)
  7069. # Clear pool
  7070. self.clear_pool()
  7071. for obj in self.collection.get_list():
  7072. # delete shapes left drawn from mark shape_collections, if any
  7073. if isinstance(obj, FlatCAMGerber):
  7074. try:
  7075. obj.mark_shapes.enabled = False
  7076. obj.mark_shapes.clear(update=True)
  7077. except AttributeError:
  7078. pass
  7079. # also delete annotation shapes, if any
  7080. elif isinstance(obj, FlatCAMCNCjob):
  7081. try:
  7082. obj.annotation.enabled = False
  7083. obj.annotation.clear(update=True)
  7084. except AttributeError:
  7085. pass
  7086. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7087. self.init_tcl()
  7088. self.delete_selection_shape()
  7089. self.collection.delete_all()
  7090. self.setup_component_editor()
  7091. # Clear project filename
  7092. self.project_filename = None
  7093. # Load the application defaults
  7094. self.load_defaults(filename='current_defaults')
  7095. # Re-fresh project options
  7096. self.on_options_app2project()
  7097. # Init Tools
  7098. self.init_tools()
  7099. if cli is None:
  7100. # Close any Tabs opened in the Plot Tab Area section
  7101. for index in range(self.ui.plot_tab_area.count()):
  7102. self.ui.plot_tab_area.closeTab(index)
  7103. # for whatever reason previous command does not close the last tab so I do it manually
  7104. self.ui.plot_tab_area.closeTab(0)
  7105. # # And then add again the Plot Area
  7106. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  7107. self.ui.plot_tab_area.protectTab(0)
  7108. # take the focus of the Notebook on Project Tab.
  7109. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7110. self.set_ui_title(name=_("New Project - Not saved"))
  7111. def obj_properties(self):
  7112. self.report_usage("obj_properties()")
  7113. self.properties_tool.run(toggle=False)
  7114. def on_project_context_save(self):
  7115. obj = self.collection.get_active()
  7116. if type(obj) == FlatCAMGeometry:
  7117. self.on_file_exportdxf()
  7118. elif type(obj) == FlatCAMExcellon:
  7119. self.on_file_saveexcellon()
  7120. elif type(obj) == FlatCAMCNCjob:
  7121. obj.on_exportgcode_button_click()
  7122. elif type(obj) == FlatCAMGerber:
  7123. self.on_file_savegerber()
  7124. def obj_move(self):
  7125. self.report_usage("obj_move()")
  7126. self.move_tool.run(toggle=False)
  7127. def on_fileopengerber(self, checked=None, name=None):
  7128. """
  7129. File menu callback for opening a Gerber.
  7130. :return: None
  7131. """
  7132. self.report_usage("on_fileopengerber")
  7133. App.log.debug("on_fileopengerber()")
  7134. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  7135. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  7136. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  7137. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  7138. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  7139. "*.mil);;" \
  7140. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  7141. "Allegro Files (*.art);;" \
  7142. "Mentor Files (*.pho *.gdo);;" \
  7143. "All Files (*.*)"
  7144. if name is None:
  7145. try:
  7146. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  7147. directory=self.get_last_folder(),
  7148. filter=_filter_)
  7149. except TypeError:
  7150. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  7151. filenames = [str(filename) for filename in filenames]
  7152. else:
  7153. filenames = [name]
  7154. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7155. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7156. _("Opening Gerber file.")),
  7157. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7158. color=QtGui.QColor("gray"))
  7159. if len(filenames) == 0:
  7160. self.inform.emit('[WARNING_NOTCL] %s' %
  7161. _("Open Gerber cancelled."))
  7162. else:
  7163. for filename in filenames:
  7164. if filename != '':
  7165. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  7166. def on_fileopenexcellon(self, checked=None, name=None):
  7167. """
  7168. File menu callback for opening an Excellon file.
  7169. :return: None
  7170. """
  7171. self.report_usage("on_fileopenexcellon")
  7172. App.log.debug("on_fileopenexcellon()")
  7173. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  7174. "All Files (*.*)"
  7175. if name is None:
  7176. try:
  7177. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  7178. directory=self.get_last_folder(),
  7179. filter=_filter_)
  7180. except TypeError:
  7181. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  7182. filenames = [str(filename) for filename in filenames]
  7183. else:
  7184. filenames = [str(name)]
  7185. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7186. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7187. _("Opening Excellon file.")),
  7188. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7189. color=QtGui.QColor("gray"))
  7190. if len(filenames) == 0:
  7191. self.inform.emit('[WARNING_NOTCL]%s' %
  7192. _(" Open Excellon cancelled."))
  7193. else:
  7194. for filename in filenames:
  7195. if filename != '':
  7196. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  7197. def on_fileopengcode(self, checked=None, name=None):
  7198. """
  7199. File menu call back for opening gcode.
  7200. :return: None
  7201. """
  7202. self.report_usage("on_fileopengcode")
  7203. App.log.debug("on_fileopengcode()")
  7204. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  7205. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  7206. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  7207. "All Files (*.*)"
  7208. if name is None:
  7209. try:
  7210. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  7211. directory=self.get_last_folder(),
  7212. filter=_filter_)
  7213. except TypeError:
  7214. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  7215. filenames = [str(filename) for filename in filenames]
  7216. else:
  7217. filenames = [name]
  7218. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7219. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7220. _("Opening G-Code file.")),
  7221. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7222. color=QtGui.QColor("gray"))
  7223. if len(filenames) == 0:
  7224. self.inform.emit('[WARNING_NOTCL] %s' %
  7225. _("Open G-Code cancelled."))
  7226. else:
  7227. for filename in filenames:
  7228. if filename != '':
  7229. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename]})
  7230. def on_file_openproject(self, checked=None):
  7231. """
  7232. File menu callback for opening a project.
  7233. :return: None
  7234. """
  7235. self.report_usage("on_file_openproject")
  7236. App.log.debug("on_file_openproject()")
  7237. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  7238. try:
  7239. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  7240. directory=self.get_last_folder(), filter=_filter_)
  7241. except TypeError:
  7242. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  7243. # The Qt methods above will return a QString which can cause problems later.
  7244. # So far json.dump() will fail to serialize it.
  7245. # TODO: Improve the serialization methods and remove this fix.
  7246. filename = str(filename)
  7247. if filename == "":
  7248. self.inform.emit('[WARNING_NOTCL] %s' %
  7249. _("Open Project cancelled."))
  7250. else:
  7251. # self.worker_task.emit({'fcn': self.open_project,
  7252. # 'params': [filename]})
  7253. # The above was failing because open_project() is not
  7254. # thread safe. The new_project()
  7255. self.open_project(filename)
  7256. def on_file_openconfig(self, checked=None):
  7257. """
  7258. File menu callback for opening a config file.
  7259. :return: None
  7260. """
  7261. self.report_usage("on_file_openconfig")
  7262. App.log.debug("on_file_openconfig()")
  7263. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  7264. try:
  7265. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7266. directory=self.data_path, filter=_filter_)
  7267. except TypeError:
  7268. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7269. filter=_filter_)
  7270. if filename == "":
  7271. self.inform.emit('[WARNING_NOTCL] %s' %
  7272. _("Open Config cancelled."))
  7273. else:
  7274. self.open_config_file(filename)
  7275. def on_file_exportsvg(self):
  7276. """
  7277. Callback for menu item File->Export SVG.
  7278. :return: None
  7279. """
  7280. self.report_usage("on_file_exportsvg")
  7281. App.log.debug("on_file_exportsvg()")
  7282. obj = self.collection.get_active()
  7283. if obj is None:
  7284. self.inform.emit('[WARNING_NOTCL] %s' %
  7285. _("No object selected."))
  7286. msg = _("Please Select a Geometry object to export")
  7287. msgbox = QtWidgets.QMessageBox()
  7288. msgbox.setInformativeText(msg)
  7289. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7290. msgbox.setDefaultButton(bt_ok)
  7291. msgbox.exec_()
  7292. return
  7293. # Check for more compatible types and add as required
  7294. if (not isinstance(obj, FlatCAMGeometry)
  7295. and not isinstance(obj, FlatCAMGerber)
  7296. and not isinstance(obj, FlatCAMCNCjob)
  7297. and not isinstance(obj, FlatCAMExcellon)):
  7298. msg = '[ERROR_NOTCL] %s' % \
  7299. _("Only Geometry, Gerber and CNCJob objects can be used.")
  7300. msgbox = QtWidgets.QMessageBox()
  7301. msgbox.setInformativeText(msg)
  7302. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7303. msgbox.setDefaultButton(bt_ok)
  7304. msgbox.exec_()
  7305. return
  7306. name = obj.options["name"]
  7307. _filter = "SVG File (*.svg);;All Files (*.*)"
  7308. try:
  7309. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7310. caption=_("Export SVG"),
  7311. directory=self.get_last_save_folder() + '/' + str(name),
  7312. filter=_filter)
  7313. except TypeError:
  7314. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  7315. filename = str(filename)
  7316. if filename == "":
  7317. self.inform.emit('[WARNING_NOTCL]%s' %
  7318. _(" Export SVG cancelled."))
  7319. return
  7320. else:
  7321. self.export_svg(name, filename)
  7322. if self.defaults["global_open_style"] is False:
  7323. self.file_opened.emit("SVG", filename)
  7324. self.file_saved.emit("SVG", filename)
  7325. def on_file_exportpng(self):
  7326. self.report_usage("on_file_exportpng")
  7327. App.log.debug("on_file_exportpng()")
  7328. self.date = str(datetime.today()).rpartition('.')[0]
  7329. self.date = ''.join(c for c in self.date if c not in ':-')
  7330. self.date = self.date.replace(' ', '_')
  7331. image = _screenshot()
  7332. data = np.asarray(image)
  7333. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  7334. self.inform.emit('[[WARNING_NOTCL]] %s' %
  7335. _('Data must be a 3D array with last dimension 3 or 4'))
  7336. return
  7337. filter_ = "PNG File (*.png);;All Files (*.*)"
  7338. try:
  7339. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7340. caption=_("Export PNG Image"),
  7341. directory=self.get_last_save_folder() + '/png_' + self.date,
  7342. filter=filter_)
  7343. except TypeError:
  7344. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  7345. filename = str(filename)
  7346. if filename == "":
  7347. self.inform.emit(_("Export PNG cancelled."))
  7348. return
  7349. else:
  7350. write_png(filename, data)
  7351. if self.defaults["global_open_style"] is False:
  7352. self.file_opened.emit("png", filename)
  7353. self.file_saved.emit("png", filename)
  7354. def on_file_savegerber(self):
  7355. """
  7356. Callback for menu item in Project context menu.
  7357. :return: None
  7358. """
  7359. self.report_usage("on_file_savegerber")
  7360. App.log.debug("on_file_savegerber()")
  7361. obj = self.collection.get_active()
  7362. if obj is None:
  7363. self.inform.emit('[WARNING_NOTCL] %s' %
  7364. _("No object selected. Please select an Gerber object to export."))
  7365. return
  7366. # Check for more compatible types and add as required
  7367. if not isinstance(obj, FlatCAMGerber):
  7368. self.inform.emit('[ERROR_NOTCL] %s' %
  7369. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7370. return
  7371. name = self.collection.get_active().options["name"]
  7372. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  7373. try:
  7374. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7375. caption="Save Gerber source file",
  7376. directory=self.get_last_save_folder() + '/' + name,
  7377. filter=_filter)
  7378. except TypeError:
  7379. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  7380. filename = str(filename)
  7381. if filename == "":
  7382. self.inform.emit('[WARNING_NOTCL] %s' %
  7383. _("Save Gerber source file cancelled."))
  7384. return
  7385. else:
  7386. self.save_source_file(name, filename)
  7387. if self.defaults["global_open_style"] is False:
  7388. self.file_opened.emit("Gerber", filename)
  7389. self.file_saved.emit("Gerber", filename)
  7390. def on_file_saveexcellon(self):
  7391. """
  7392. Callback for menu item in project context menu.
  7393. :return: None
  7394. """
  7395. self.report_usage("on_file_saveexcellon")
  7396. App.log.debug("on_file_saveexcellon()")
  7397. obj = self.collection.get_active()
  7398. if obj is None:
  7399. self.inform.emit('[WARNING_NOTCL] %s' %
  7400. _("No object selected. Please select an Excellon object to export."))
  7401. return
  7402. # Check for more compatible types and add as required
  7403. if not isinstance(obj, FlatCAMExcellon):
  7404. self.inform.emit('[ERROR_NOTCL] %s' %
  7405. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7406. return
  7407. name = self.collection.get_active().options["name"]
  7408. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7409. try:
  7410. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7411. caption=_("Save Excellon source file"),
  7412. directory=self.get_last_save_folder() + '/' + name,
  7413. filter=_filter)
  7414. except TypeError:
  7415. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  7416. filename = str(filename)
  7417. if filename == "":
  7418. self.inform.emit('[WARNING_NOTCL] %s' %
  7419. _("Saving Excellon source file cancelled."))
  7420. return
  7421. else:
  7422. self.save_source_file(name, filename)
  7423. if self.defaults["global_open_style"] is False:
  7424. self.file_opened.emit("Excellon", filename)
  7425. self.file_saved.emit("Excellon", filename)
  7426. def on_file_exportexcellon(self):
  7427. """
  7428. Callback for menu item File->Export->Excellon.
  7429. :return: None
  7430. """
  7431. self.report_usage("on_file_exportexcellon")
  7432. App.log.debug("on_file_exportexcellon()")
  7433. obj = self.collection.get_active()
  7434. if obj is None:
  7435. self.inform.emit('[WARNING_NOTCL] %s' %
  7436. _("No object selected. Please Select an Excellon object to export."))
  7437. return
  7438. # Check for more compatible types and add as required
  7439. if not isinstance(obj, FlatCAMExcellon):
  7440. self.inform.emit('[ERROR_NOTCL] %s' %
  7441. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7442. return
  7443. name = self.collection.get_active().options["name"]
  7444. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7445. try:
  7446. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7447. caption=_("Export Excellon"),
  7448. directory=self.get_last_save_folder() + '/' + name,
  7449. filter=_filter)
  7450. except TypeError:
  7451. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  7452. filename = str(filename)
  7453. if filename == "":
  7454. self.inform.emit('[WARNING_NOTCL] %s' %
  7455. _("Export Excellon cancelled."))
  7456. return
  7457. else:
  7458. self.export_excellon(name, filename)
  7459. if self.defaults["global_open_style"] is False:
  7460. self.file_opened.emit("Excellon", filename)
  7461. self.file_saved.emit("Excellon", filename)
  7462. def on_file_exportgerber(self):
  7463. """
  7464. Callback for menu item File->Export->Gerber.
  7465. :return: None
  7466. """
  7467. self.report_usage("on_file_exportgerber")
  7468. App.log.debug("on_file_exportgerber()")
  7469. obj = self.collection.get_active()
  7470. if obj is None:
  7471. self.inform.emit('[WARNING_NOTCL] %s' %
  7472. _("No object selected. Please Select an Gerber object to export."))
  7473. return
  7474. # Check for more compatible types and add as required
  7475. if not isinstance(obj, FlatCAMGerber):
  7476. self.inform.emit('[ERROR_NOTCL] %s' %
  7477. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7478. return
  7479. name = self.collection.get_active().options["name"]
  7480. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  7481. try:
  7482. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7483. caption=_("Export Gerber"),
  7484. directory=self.get_last_save_folder() + '/' + name,
  7485. filter=_filter_)
  7486. except TypeError:
  7487. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  7488. filename = str(filename)
  7489. if filename == "":
  7490. self.inform.emit('[WARNING_NOTCL] %s' %
  7491. _("Export Gerber cancelled."))
  7492. return
  7493. else:
  7494. self.export_gerber(name, filename)
  7495. if self.defaults["global_open_style"] is False:
  7496. self.file_opened.emit("Gerber", filename)
  7497. self.file_saved.emit("Gerber", filename)
  7498. def on_file_exportdxf(self):
  7499. """
  7500. Callback for menu item File->Export DXF.
  7501. :return: None
  7502. """
  7503. self.report_usage("on_file_exportdxf")
  7504. App.log.debug("on_file_exportdxf()")
  7505. obj = self.collection.get_active()
  7506. if obj is None:
  7507. self.inform.emit('[WARNING_NOTCL] %s' %
  7508. _("No object selected."))
  7509. msg = _("Please Select a Geometry object to export")
  7510. msgbox = QtWidgets.QMessageBox()
  7511. msgbox.setInformativeText(msg)
  7512. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7513. msgbox.setDefaultButton(bt_ok)
  7514. msgbox.exec_()
  7515. return
  7516. # Check for more compatible types and add as required
  7517. if not isinstance(obj, FlatCAMGeometry):
  7518. msg = '[ERROR_NOTCL] %s' % \
  7519. _("Only Geometry objects can be used.")
  7520. msgbox = QtWidgets.QMessageBox()
  7521. msgbox.setInformativeText(msg)
  7522. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7523. msgbox.setDefaultButton(bt_ok)
  7524. msgbox.exec_()
  7525. return
  7526. name = self.collection.get_active().options["name"]
  7527. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7528. try:
  7529. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7530. caption=_("Export DXF"),
  7531. directory=self.get_last_save_folder() + '/' + name,
  7532. filter=_filter_)
  7533. except TypeError:
  7534. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  7535. filter=_filter_)
  7536. filename = str(filename)
  7537. if filename == "":
  7538. self.inform.emit('[WARNING_NOTCL] %s' %
  7539. _("Export DXF cancelled."))
  7540. return
  7541. else:
  7542. self.export_dxf(name, filename)
  7543. if self.defaults["global_open_style"] is False:
  7544. self.file_opened.emit("DXF", filename)
  7545. self.file_saved.emit("DXF", filename)
  7546. def on_file_importsvg(self, type_of_obj):
  7547. """
  7548. Callback for menu item File->Import SVG.
  7549. :param type_of_obj: to import the SVG as Geometry or as Gerber
  7550. :type type_of_obj: str
  7551. :return: None
  7552. """
  7553. self.report_usage("on_file_importsvg")
  7554. App.log.debug("on_file_importsvg()")
  7555. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  7556. try:
  7557. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7558. directory=self.get_last_folder(), filter=_filter_)
  7559. except TypeError:
  7560. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7561. filter=_filter_)
  7562. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7563. type_of_obj = "geometry"
  7564. filenames = [str(filename) for filename in filenames]
  7565. if len(filenames) == 0:
  7566. self.inform.emit('[WARNING_NOTCL] %s' %
  7567. _("Open SVG cancelled."))
  7568. else:
  7569. for filename in filenames:
  7570. if filename != '':
  7571. self.worker_task.emit({'fcn': self.import_svg,
  7572. 'params': [filename, type_of_obj]})
  7573. def on_file_importdxf(self, type_of_obj):
  7574. """
  7575. Callback for menu item File->Import DXF.
  7576. :param type_of_obj: to import the DXF as Geometry or as Gerber
  7577. :type type_of_obj: str
  7578. :return: None
  7579. """
  7580. self.report_usage("on_file_importdxf")
  7581. App.log.debug("on_file_importdxf()")
  7582. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7583. try:
  7584. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7585. directory=self.get_last_folder(),
  7586. filter=_filter_)
  7587. except TypeError:
  7588. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7589. filter=_filter_)
  7590. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7591. type_of_obj = "geometry"
  7592. filenames = [str(filename) for filename in filenames]
  7593. if len(filenames) == 0:
  7594. self.inform.emit('[WARNING_NOTCL] %s' %
  7595. _("Open DXF cancelled."))
  7596. else:
  7597. for filename in filenames:
  7598. if filename != '':
  7599. self.worker_task.emit({'fcn': self.import_dxf,
  7600. 'params': [filename, type_of_obj]})
  7601. # ###############################################################################################################
  7602. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  7603. # ###############################################################################################################
  7604. def init_code_editor(self, name):
  7605. # Signals section
  7606. # Disconnect the old signals
  7607. try:
  7608. self.ui.buttonOpen.clicked.disconnect()
  7609. except TypeError:
  7610. pass
  7611. try:
  7612. self.ui.buttonSave.clicked.disconnect()
  7613. except TypeError:
  7614. pass
  7615. # add the tab if it was closed
  7616. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, '%s' % name)
  7617. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  7618. # delete the absolute and relative position and messages in the infobar
  7619. self.ui.position_label.setText("")
  7620. self.ui.rel_position_label.setText("")
  7621. # first clear previous text in text editor (if any)
  7622. self.ui.code_editor.clear()
  7623. self.ui.code_editor.setReadOnly(False)
  7624. self.toggle_codeeditor = True
  7625. self.ui.code_editor.completer_enable = False
  7626. self.ui.buttonRun.hide()
  7627. # make sure to keep a reference to the code editor
  7628. self.reference_code_editor = self.ui.code_editor
  7629. # Switch plot_area to CNCJob tab
  7630. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  7631. def on_view_source(self):
  7632. self.inform.emit('%s' %
  7633. _("Viewing the source code of the selected object."))
  7634. self.proc_container.view.set_busy(_("Loading..."))
  7635. try:
  7636. obj = self.collection.get_active()
  7637. except Exception as e:
  7638. log.debug("App.on_view_source() --> %s" % str(e))
  7639. self.inform.emit('[WARNING_NOTCL] %s' %
  7640. _("Select an Gerber or Excellon file to view it's source file."))
  7641. return 'fail'
  7642. if obj.kind == 'gerber':
  7643. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  7644. elif obj.kind == 'excellon':
  7645. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  7646. elif obj.kind == 'cncjob':
  7647. "GCode Files (*.NC);;All Files (*.*)"
  7648. else:
  7649. flt = "All Files (*.*)"
  7650. self.init_code_editor(name=_("Source Editor"))
  7651. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  7652. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  7653. # then append the text from GCode to the text editor
  7654. if obj.kind == 'cncjob':
  7655. try:
  7656. file = obj.export_gcode(
  7657. preamble=self.defaults["cncjob_prepend"],
  7658. postamble=self.defaults["cncjob_append"],
  7659. to_file=True)
  7660. if file == 'fail':
  7661. return 'fail'
  7662. except AttributeError:
  7663. self.inform.emit('[WARNING_NOTCL] %s' %
  7664. _("There is no selected object for which to see it's source file code."))
  7665. return 'fail'
  7666. else:
  7667. try:
  7668. file = StringIO(obj.source_file)
  7669. except AttributeError:
  7670. self.inform.emit('[WARNING_NOTCL] %s' %
  7671. _("There is no selected object for which to see it's source file code."))
  7672. return 'fail'
  7673. self.ui.cncjob_frame.hide()
  7674. try:
  7675. for line in file:
  7676. QtWidgets.QApplication.processEvents()
  7677. proc_line = str(line).strip('\n')
  7678. self.ui.code_editor.append(proc_line)
  7679. except Exception as e:
  7680. log.debug('App.on_view_source() -->%s' % str(e))
  7681. self.inform.emit('[ERROR] %s: %s' %
  7682. (_('Failed to load the source code for the selected object'), str(e)))
  7683. return
  7684. self.handleTextChanged()
  7685. self.ui.cncjob_frame.show()
  7686. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7687. self.proc_container.view.set_idle()
  7688. # self.ui.show()
  7689. def on_toggle_code_editor(self):
  7690. self.report_usage("on_toggle_code_editor()")
  7691. if self.toggle_codeeditor is False:
  7692. self.init_code_editor(name=_("Code Editor"))
  7693. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  7694. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  7695. else:
  7696. for idx in range(self.ui.plot_tab_area.count()):
  7697. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  7698. self.ui.plot_tab_area.closeTab(idx)
  7699. break
  7700. self.toggle_codeeditor = False
  7701. def on_filenewscript(self, silent=False):
  7702. """
  7703. Will create a new script file and open it in the Code Editor
  7704. :param silent: if True will not display status messages
  7705. :return: None
  7706. """
  7707. if silent is False:
  7708. self.inform.emit('[success] %s' %
  7709. _("New TCL script file created in Code Editor."))
  7710. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  7711. self.init_code_editor(name=_("Script Editor"))
  7712. self.ui.code_editor.completer_enable = True
  7713. self.ui.code_editor.append(_(
  7714. "#\n"
  7715. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  7716. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  7717. "#\n\n"
  7718. "# FlatCAM commands list:\n"
  7719. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, ClearCopper,\n"
  7720. "# Cncjob, Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, GetNames,\n"
  7721. "# GetSys, ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillDrills,\n"
  7722. "# MillSlots, Mirror, New, NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"
  7723. "# Options, Paint, Panelize, Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, SubtractPoly,\n"
  7724. "# SubtractRectangle, Version, WriteGCode\n"
  7725. "#\n\n"
  7726. ))
  7727. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  7728. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  7729. self.ui.buttonRun.show()
  7730. try:
  7731. self.ui.buttonRun.clicked.disconnect(self.handleRunCode)
  7732. except TypeError:
  7733. pass
  7734. self.ui.buttonRun.clicked.connect(self.handleRunCode)
  7735. self.handleTextChanged()
  7736. self.ui.code_editor.show()
  7737. def on_fileopenscript(self, name=None, silent=False):
  7738. """
  7739. Will open a Tcl script file into the Code Editor
  7740. :param silent: if True will not display status messages
  7741. :param name: name of a Tcl script file to open
  7742. :return:
  7743. """
  7744. if name:
  7745. filename = name
  7746. else:
  7747. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7748. try:
  7749. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  7750. directory=self.get_last_folder(), filter=_filter_)
  7751. except TypeError:
  7752. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  7753. # The Qt methods above will return a QString which can cause problems later.
  7754. # So far json.dump() will fail to serialize it.
  7755. # TODO: Improve the serialization methods and remove this fix.
  7756. filename = str(filename)
  7757. if filename == "":
  7758. if silent is False:
  7759. self.inform.emit('[WARNING_NOTCL] %s' %
  7760. _("Open TCL script cancelled."))
  7761. else:
  7762. self.on_filenewscript()
  7763. try:
  7764. with open(filename, "r") as opened_script:
  7765. try:
  7766. for line in opened_script:
  7767. proc_line = str(line).strip('\n')
  7768. self.ui.code_editor.append(proc_line)
  7769. except Exception as e:
  7770. log.debug('App.on_fileopenscript() -->%s' % str(e))
  7771. if silent is False:
  7772. self.inform.emit('[ERROR] %s %s' %
  7773. ('App.on_fileopenscript() -->', str(e)))
  7774. return
  7775. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7776. self.handleTextChanged()
  7777. if silent is False:
  7778. self.inform.emit('[success] %s' %
  7779. _("TCL script file opened in Code Editor."))
  7780. # self.ui.show()
  7781. except Exception as e:
  7782. log.debug("App.on_fileopenscript() -> %s" % str(e))
  7783. def on_filerunscript(self, name=None, silent=False):
  7784. """
  7785. File menu callback for loading and running a TCL script.
  7786. :param silent: if True will not display status messages
  7787. :param name: name of a Tcl script file to be run by FlatCAM
  7788. :return: None
  7789. """
  7790. self.report_usage("on_filerunscript")
  7791. App.log.debug("on_file_runscript()")
  7792. if name:
  7793. filename = name
  7794. if self.cmd_line_headless != 1:
  7795. self.splash.showMessage('%s: %ssec\n%s' %
  7796. (_("Canvas initialization started.\n"
  7797. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7798. _("Executing FlatCAMScript file.")
  7799. ),
  7800. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7801. color=QtGui.QColor("gray"))
  7802. else:
  7803. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7804. try:
  7805. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  7806. directory=self.get_last_folder(), filter=_filter_)
  7807. except TypeError:
  7808. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  7809. # The Qt methods above will return a QString which can cause problems later.
  7810. # So far json.dump() will fail to serialize it.
  7811. # TODO: Improve the serialization methods and remove this fix.
  7812. filename = str(filename)
  7813. if filename == "":
  7814. if silent is False:
  7815. self.inform.emit('[WARNING_NOTCL] %s' %
  7816. _("Run TCL script cancelled."))
  7817. else:
  7818. if self.cmd_line_headless != 1:
  7819. if self.ui.shell_dock.isHidden():
  7820. self.ui.shell_dock.show()
  7821. try:
  7822. with open(filename, "r") as tcl_script:
  7823. cmd_line_shellfile_content = tcl_script.read()
  7824. if self.cmd_line_headless != 1:
  7825. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  7826. else:
  7827. self.shell._sysShell.exec_command(cmd_line_shellfile_content, no_echo=True)
  7828. if silent is False:
  7829. self.inform.emit('[success] %s' %
  7830. _("TCL script file opened in Code Editor and executed."))
  7831. except Exception as e:
  7832. log.debug("App.on_filerunscript() -> %s" % str(e))
  7833. sys.exit(2)
  7834. def on_file_saveproject(self, silent=False):
  7835. """
  7836. Callback for menu item File->Save Project. Saves the project to
  7837. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7838. if set to None. The project is saved by calling ``self.save_project()``.
  7839. :param silent: if True will not display status messages
  7840. :return: None
  7841. """
  7842. self.report_usage("on_file_saveproject")
  7843. if self.project_filename is None:
  7844. self.on_file_saveprojectas()
  7845. else:
  7846. self.worker_task.emit({'fcn': self.save_project,
  7847. 'params': [self.project_filename, silent]})
  7848. if self.defaults["global_open_style"] is False:
  7849. self.file_opened.emit("project", self.project_filename)
  7850. self.file_saved.emit("project", self.project_filename)
  7851. self.set_ui_title(name=self.project_filename)
  7852. self.should_we_save = False
  7853. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7854. """
  7855. Callback for menu item File->Save Project As... Opens a file
  7856. chooser and saves the project to the given file via
  7857. ``self.save_project()``.
  7858. :param make_copy if to be create a copy of the project; boolean
  7859. :param use_thread: if to be run in a separate thread; boolean
  7860. :param quit_action: if to be followed by quiting the application; boolean
  7861. :return: None
  7862. """
  7863. self.report_usage("on_file_saveprojectas")
  7864. self.date = str(datetime.today()).rpartition('.')[0]
  7865. self.date = ''.join(c for c in self.date if c not in ':-')
  7866. self.date = self.date.replace(' ', '_')
  7867. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  7868. try:
  7869. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7870. caption=_("Save Project As ..."),
  7871. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  7872. filter=filter_)
  7873. except TypeError:
  7874. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  7875. filename = str(filename)
  7876. if filename == '':
  7877. self.inform.emit('[WARNING_NOTCL] %s' %
  7878. _("Save Project cancelled."))
  7879. return
  7880. try:
  7881. f = open(filename, 'r')
  7882. f.close()
  7883. except IOError:
  7884. pass
  7885. if use_thread is True:
  7886. self.worker_task.emit({'fcn': self.save_project,
  7887. 'params': [filename, quit_action]})
  7888. else:
  7889. self.save_project(filename, quit_action)
  7890. # self.save_project(filename)
  7891. if self.defaults["global_open_style"] is False:
  7892. self.file_opened.emit("project", filename)
  7893. self.file_saved.emit("project", filename)
  7894. if not make_copy:
  7895. self.project_filename = filename
  7896. self.set_ui_title(name=self.project_filename)
  7897. self.should_we_save = False
  7898. def export_svg(self, obj_name, filename, scale_factor=0.00):
  7899. """
  7900. Exports a Geometry Object to an SVG file.
  7901. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7902. :param filename: Path to the SVG file to save to.
  7903. :param scale_factor: factor by which to change/scale the thickness of the features
  7904. :return:
  7905. """
  7906. self.report_usage("export_svg()")
  7907. if filename is None:
  7908. filename = self.defaults["global_last_save_folder"]
  7909. self.log.debug("export_svg()")
  7910. try:
  7911. obj = self.collection.get_by_name(str(obj_name))
  7912. except:
  7913. # TODO: The return behavior has not been established... should raise exception?
  7914. return "Could not retrieve object: %s" % obj_name
  7915. with self.proc_container.new(_("Exporting SVG")) as proc:
  7916. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7917. # Determine bounding area for svg export
  7918. bounds = obj.bounds()
  7919. size = obj.size()
  7920. # Convert everything to strings for use in the xml doc
  7921. svgwidth = str(size[0])
  7922. svgheight = str(size[1])
  7923. minx = str(bounds[0])
  7924. miny = str(bounds[1] - size[1])
  7925. uom = obj.units.lower()
  7926. # Add a SVG Header and footer to the svg output from shapely
  7927. # The transform flips the Y Axis so that everything renders
  7928. # properly within svg apps such as inkscape
  7929. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7930. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7931. svg_header += 'width="' + svgwidth + uom + '" '
  7932. svg_header += 'height="' + svgheight + uom + '" '
  7933. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7934. svg_header += '<g transform="scale(1,-1)">'
  7935. svg_footer = '</g> </svg>'
  7936. svg_elem = svg_header + exported_svg + svg_footer
  7937. # Parse the xml through a xml parser just to add line feeds
  7938. # and to make it look more pretty for the output
  7939. svgcode = parse_xml_string(svg_elem)
  7940. try:
  7941. with open(filename, 'w') as fp:
  7942. fp.write(svgcode.toprettyxml())
  7943. except PermissionError:
  7944. self.inform.emit('[WARNING] %s' %
  7945. _("Permission denied, saving not possible.\n"
  7946. "Most likely another app is holding the file open and not accessible."))
  7947. return 'fail'
  7948. if self.defaults["global_open_style"] is False:
  7949. self.file_opened.emit("SVG", filename)
  7950. self.file_saved.emit("SVG", filename)
  7951. self.inform.emit('[success] %s: %s' %
  7952. (_("SVG file exported to"), filename))
  7953. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  7954. """
  7955. Exports a Geometry Object to an SVG file in negative.
  7956. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7957. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  7958. :param filename: Path to the SVG file to save to.
  7959. :param boundary: thickness of a black border to surround all the features
  7960. :param scale_factor: factor by which to change/scale the thickness of the features
  7961. :param use_thread: if to be run in a separate thread; boolean
  7962. :return:
  7963. """
  7964. self.report_usage("export_negative()")
  7965. if filename is None:
  7966. filename = self.defaults["global_last_save_folder"]
  7967. self.log.debug("export_svg() negative")
  7968. try:
  7969. obj = self.collection.get_by_name(str(obj_name))
  7970. except:
  7971. # TODO: The return behavior has not been established... should raise exception?
  7972. return "Could not retrieve object: %s" % obj_name
  7973. try:
  7974. box = self.collection.get_by_name(str(box_name))
  7975. except:
  7976. # TODO: The return behavior has not been established... should raise exception?
  7977. return "Could not retrieve object: %s" % box_name
  7978. if box is None:
  7979. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  7980. (_("No object Box. Using instead"), obj))
  7981. box = obj
  7982. def make_negative_film():
  7983. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7984. # Determine bounding area for svg export
  7985. bounds = box.bounds()
  7986. size = box.size()
  7987. uom = obj.units.lower()
  7988. # Convert everything to strings for use in the xml doc
  7989. svgwidth = str(size[0] + (2 * boundary))
  7990. svgheight = str(size[1] + (2 * boundary))
  7991. minx = str(bounds[0] - boundary)
  7992. miny = str(bounds[1] + boundary + size[1])
  7993. miny_rect = str(bounds[1] - boundary)
  7994. # Add a SVG Header and footer to the svg output from shapely
  7995. # The transform flips the Y Axis so that everything renders
  7996. # properly within svg apps such as inkscape
  7997. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7998. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7999. svg_header += 'width="' + svgwidth + uom + '" '
  8000. svg_header += 'height="' + svgheight + uom + '" '
  8001. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  8002. svg_header += '>'
  8003. svg_header += '<g transform="scale(1,-1)">'
  8004. svg_footer = '</g> </svg>'
  8005. # Change the attributes of the exported SVG
  8006. # We don't need stroke-width - wrong, we do when we have lines with certain width
  8007. # We set opacity to maximum
  8008. # We set the color to WHITE
  8009. root = ET.fromstring(exported_svg)
  8010. for child in root:
  8011. child.set('fill', '#FFFFFF')
  8012. child.set('opacity', '1.0')
  8013. child.set('stroke', '#FFFFFF')
  8014. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  8015. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  8016. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  8017. first_svg_elem_tag = 'rect'
  8018. first_svg_elem_attribs = {
  8019. 'x': minx,
  8020. 'y': miny_rect,
  8021. 'width': svgwidth,
  8022. 'height': svgheight,
  8023. 'id': 'neg_rect',
  8024. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  8025. }
  8026. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  8027. exported_svg = ET.tostring(root)
  8028. svg_elem = svg_header + str(exported_svg) + svg_footer
  8029. # Parse the xml through a xml parser just to add line feeds
  8030. # and to make it look more pretty for the output
  8031. doc = parse_xml_string(svg_elem)
  8032. try:
  8033. with open(filename, 'w') as fp:
  8034. fp.write(doc.toprettyxml())
  8035. except PermissionError:
  8036. self.inform.emit('[WARNING] %s' %
  8037. _("Permission denied, saving not possible.\n"
  8038. "Most likely another app is holding the file open and not accessible."))
  8039. return 'fail'
  8040. if self.defaults["global_open_style"] is False:
  8041. self.file_opened.emit("SVG", filename)
  8042. self.file_saved.emit("SVG", filename)
  8043. self.inform.emit('[success] %s: %s' %
  8044. (_("SVG file exported to"), filename))
  8045. if use_thread is True:
  8046. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  8047. def job_thread_film(app_obj):
  8048. try:
  8049. make_negative_film()
  8050. except Exception as e:
  8051. proc.done()
  8052. return
  8053. proc.done()
  8054. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  8055. else:
  8056. make_negative_film()
  8057. def export_svg_positive(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  8058. """
  8059. Exports a Geometry Object to an SVG file in positive black.
  8060. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8061. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  8062. :param filename: Path to the SVG file to save to.
  8063. :param scale_factor: factor by which to change/scale the thickness of the features
  8064. :param use_thread: if to be run in a separate thread; boolean
  8065. :return:
  8066. """
  8067. self.report_usage("export_svg_positive()")
  8068. if filename is None:
  8069. filename = self.defaults["global_last_save_folder"]
  8070. self.log.debug("export_svg() black")
  8071. try:
  8072. obj = self.collection.get_by_name(str(obj_name))
  8073. except:
  8074. # TODO: The return behavior has not been established... should raise exception?
  8075. return "Could not retrieve object: %s" % obj_name
  8076. try:
  8077. box = self.collection.get_by_name(str(box_name))
  8078. except:
  8079. # TODO: The return behavior has not been established... should raise exception?
  8080. return "Could not retrieve object: %s" % box_name
  8081. if box is None:
  8082. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  8083. (_("No object Box. Using instead"), obj))
  8084. box = obj
  8085. def make_positive_film():
  8086. exported_svg = obj.export_svg(scale_factor=scale_factor)
  8087. self.progress.emit(40)
  8088. # Change the attributes of the exported SVG
  8089. # We don't need stroke-width
  8090. # We set opacity to maximum
  8091. # We set the colour to WHITE
  8092. root = ET.fromstring(exported_svg)
  8093. for child in root:
  8094. child.set('fill', str(self.defaults['tools_film_color']))
  8095. child.set('opacity', '1.0')
  8096. child.set('stroke', str(self.defaults['tools_film_color']))
  8097. exported_svg = ET.tostring(root)
  8098. # Determine bounding area for svg export
  8099. bounds = box.bounds()
  8100. size = box.size()
  8101. # This contain the measure units
  8102. uom = obj.units.lower()
  8103. # Define a boundary around SVG of about 1.0mm (~39mils)
  8104. if uom in "mm":
  8105. boundary = 1.0
  8106. else:
  8107. boundary = 0.0393701
  8108. self.progress.emit(80)
  8109. # Convert everything to strings for use in the xml doc
  8110. svgwidth = str(size[0] + (2 * boundary))
  8111. svgheight = str(size[1] + (2 * boundary))
  8112. minx = str(bounds[0] - boundary)
  8113. miny = str(bounds[1] + boundary + size[1])
  8114. self.log.debug(minx)
  8115. self.log.debug(miny)
  8116. # Add a SVG Header and footer to the svg output from shapely
  8117. # The transform flips the Y Axis so that everything renders
  8118. # properly within svg apps such as inkscape
  8119. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8120. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8121. svg_header += 'width="' + svgwidth + uom + '" '
  8122. svg_header += 'height="' + svgheight + uom + '" '
  8123. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  8124. svg_header += '>'
  8125. svg_header += '<g transform="scale(1,-1)">'
  8126. svg_footer = '</g> </svg>'
  8127. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  8128. self.progress.emit(90)
  8129. # Parse the xml through a xml parser just to add line feeds
  8130. # and to make it look more pretty for the output
  8131. doc = parse_xml_string(svg_elem)
  8132. try:
  8133. with open(filename, 'w') as fp:
  8134. fp.write(doc.toprettyxml())
  8135. except PermissionError:
  8136. self.inform.emit('[WARNING] %s' %
  8137. _("Permission denied, saving not possible.\n"
  8138. "Most likely another app is holding the file open and not accessible."))
  8139. return 'fail'
  8140. self.progress.emit(100)
  8141. if self.defaults["global_open_style"] is False:
  8142. self.file_opened.emit("SVG", filename)
  8143. self.file_saved.emit("SVG", filename)
  8144. self.inform.emit('[success] %s: %s' %
  8145. (_("SVG file exported to"), filename))
  8146. if use_thread is True:
  8147. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  8148. def job_thread_film(app_obj):
  8149. try:
  8150. make_positive_film()
  8151. except Exception as e:
  8152. proc.done()
  8153. return
  8154. proc.done()
  8155. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  8156. else:
  8157. make_positive_film()
  8158. def save_source_file(self, obj_name, filename, use_thread=True):
  8159. """
  8160. Exports a FlatCAM Object to an Gerber/Excellon file.
  8161. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8162. :param filename: Path to the Gerber file to save to.
  8163. :param use_thread: if to be run in a separate thread
  8164. :return:
  8165. """
  8166. self.report_usage("save source file()")
  8167. if filename is None:
  8168. filename = self.defaults["global_last_save_folder"]
  8169. self.log.debug("save source file()")
  8170. obj = self.collection.get_by_name(obj_name)
  8171. file_string = StringIO(obj.source_file)
  8172. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8173. try:
  8174. with open(filename, 'w') as file:
  8175. file.writelines('G04*\n')
  8176. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8177. (obj.kind.upper(), str(self.version), str(self.version_date)))
  8178. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8179. file.writelines('G04 Created on : %s*\n' % time_string)
  8180. for line in file_string:
  8181. file.writelines(line)
  8182. except PermissionError:
  8183. self.inform.emit('[WARNING] %s' %
  8184. _("Permission denied, saving not possible.\n"
  8185. "Most likely another app is holding the file open and not accessible."))
  8186. return 'fail'
  8187. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  8188. """
  8189. Exports a Excellon Object to an Excellon file.
  8190. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  8191. :param filename: Path to the Excellon file to save to.
  8192. :param use_thread: if to be run in a separate thread
  8193. :return:
  8194. """
  8195. self.report_usage("export_excellon()")
  8196. if filename is None:
  8197. filename = self.defaults["global_last_save_folder"]
  8198. self.log.debug("export_excellon()")
  8199. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  8200. self.defaults["excellon_exp_decimals"]
  8201. )
  8202. units = ''
  8203. if local_use is None:
  8204. try:
  8205. obj = self.collection.get_by_name(str(obj_name))
  8206. except:
  8207. # TODO: The return behavior has not been established... should raise exception?
  8208. return "Could not retrieve object: %s" % obj_name
  8209. else:
  8210. obj = local_use
  8211. # updated units
  8212. eunits = self.defaults["excellon_exp_units"]
  8213. ewhole = self.defaults["excellon_exp_integer"]
  8214. efract = self.defaults["excellon_exp_decimals"]
  8215. ezeros = self.defaults["excellon_exp_zeros"]
  8216. eformat = self.defaults["excellon_exp_format"]
  8217. slot_type = self.defaults["excellon_exp_slot_type"]
  8218. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8219. if fc_units == 'MM':
  8220. factor = 1 if eunits == 'METRIC' else 0.03937
  8221. else:
  8222. factor = 25.4 if eunits == 'METRIC' else 1
  8223. def make_excellon():
  8224. try:
  8225. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8226. header = 'M48\n'
  8227. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  8228. (str(self.version), str(self.version_date))
  8229. header += ';Filename: %s' % str(obj_name) + '\n'
  8230. header += ';Created on : %s' % time_str + '\n'
  8231. if eformat == 'dec':
  8232. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  8233. header += eunits + '\n'
  8234. for tool in obj.tools:
  8235. if eunits == 'METRIC':
  8236. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8237. tool=str(tool),
  8238. dec=2)
  8239. else:
  8240. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8241. tool=str(tool),
  8242. dec=4)
  8243. else:
  8244. if ezeros == 'LZ':
  8245. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8246. form='ndec', e_zeros='LZ', factor=factor,
  8247. slot_type=slot_type)
  8248. header += '%s,%s\n' % (eunits, 'LZ')
  8249. header += format_exc
  8250. for tool in obj.tools:
  8251. if eunits == 'METRIC':
  8252. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8253. tool=str(tool),
  8254. dec=2)
  8255. else:
  8256. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8257. tool=str(tool),
  8258. dec=4)
  8259. else:
  8260. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8261. form='ndec', e_zeros='TZ', factor=factor,
  8262. slot_type=slot_type)
  8263. header += '%s,%s\n' % (eunits, 'TZ')
  8264. header += format_exc
  8265. for tool in obj.tools:
  8266. if eunits == 'METRIC':
  8267. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8268. tool=str(tool),
  8269. dec=2)
  8270. else:
  8271. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8272. tool=str(tool),
  8273. dec=4)
  8274. header += '%\n'
  8275. footer = 'M30\n'
  8276. exported_excellon = header
  8277. exported_excellon += excellon_code
  8278. exported_excellon += footer
  8279. if local_use is None:
  8280. try:
  8281. with open(filename, 'w') as fp:
  8282. fp.write(exported_excellon)
  8283. except PermissionError:
  8284. self.inform.emit('[WARNING] %s' %
  8285. _("Permission denied, saving not possible.\n"
  8286. "Most likely another app is holding the file open and not accessible."))
  8287. return 'fail'
  8288. if self.defaults["global_open_style"] is False:
  8289. self.file_opened.emit("Excellon", filename)
  8290. self.file_saved.emit("Excellon", filename)
  8291. self.inform.emit('[success] %s: %s' %
  8292. (_("Excellon file exported to"), filename))
  8293. else:
  8294. return exported_excellon
  8295. except Exception as e:
  8296. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  8297. return 'fail'
  8298. if use_thread is True:
  8299. with self.proc_container.new(_("Exporting Excellon")) as proc:
  8300. def job_thread_exc(app_obj):
  8301. ret = make_excellon()
  8302. if ret == 'fail':
  8303. self.inform.emit('[ERROR_NOTCL] %s' %
  8304. _('Could not export Excellon file.'))
  8305. return
  8306. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8307. else:
  8308. ret = make_excellon()
  8309. if ret == 'fail':
  8310. self.inform.emit('[ERROR_NOTCL] %s' %
  8311. _('Could not export Excellon file.'))
  8312. return 'fail'
  8313. if local_use is not None:
  8314. return ret
  8315. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  8316. """
  8317. Exports a Gerber Object to an Gerber file.
  8318. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  8319. :param filename: Path to the Gerber file to save to.
  8320. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8321. When not None, the value will be the actual Gerber object for which to create the Gerber code
  8322. :param use_thread: if to be run in a separate thread
  8323. :return:
  8324. """
  8325. self.report_usage("export_gerber()")
  8326. if filename is None:
  8327. filename = self.defaults["global_last_save_folder"]
  8328. self.log.debug("export_gerber()")
  8329. if local_use is None:
  8330. try:
  8331. obj = self.collection.get_by_name(str(obj_name))
  8332. except:
  8333. # TODO: The return behavior has not been established... should raise exception?
  8334. return "Could not retrieve object: %s" % obj_name
  8335. else:
  8336. obj = local_use
  8337. # updated units
  8338. gunits = self.defaults["gerber_exp_units"]
  8339. gwhole = self.defaults["gerber_exp_integer"]
  8340. gfract = self.defaults["gerber_exp_decimals"]
  8341. gzeros = self.defaults["gerber_exp_zeros"]
  8342. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8343. if fc_units == 'MM':
  8344. factor = 1 if gunits == 'MM' else 0.03937
  8345. else:
  8346. factor = 25.4 if gunits == 'MM' else 1
  8347. def make_gerber():
  8348. try:
  8349. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8350. header = 'G04*\n'
  8351. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  8352. (str(self.version), str(self.version_date))
  8353. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  8354. header += 'G04 Created on : %s*' % time_str + '\n'
  8355. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  8356. header += "%MO{units}*%\n".format(units=gunits)
  8357. for apid in obj.apertures:
  8358. if obj.apertures[apid]['type'] == 'C':
  8359. header += "%ADD{apid}{type},{size}*%\n".format(
  8360. apid=str(apid),
  8361. type='C',
  8362. size=(factor * obj.apertures[apid]['size'])
  8363. )
  8364. elif obj.apertures[apid]['type'] == 'R':
  8365. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8366. apid=str(apid),
  8367. type='R',
  8368. width=(factor * obj.apertures[apid]['width']),
  8369. height=(factor * obj.apertures[apid]['height'])
  8370. )
  8371. elif obj.apertures[apid]['type'] == 'O':
  8372. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8373. apid=str(apid),
  8374. type='O',
  8375. width=(factor * obj.apertures[apid]['width']),
  8376. height=(factor * obj.apertures[apid]['height'])
  8377. )
  8378. header += '\n'
  8379. # obsolete units but some software may need it
  8380. if gunits == 'IN':
  8381. header += 'G70*\n'
  8382. else:
  8383. header += 'G71*\n'
  8384. # Absolute Mode
  8385. header += 'G90*\n'
  8386. header += 'G01*\n'
  8387. # positive polarity
  8388. header += '%LPD*%\n'
  8389. footer = 'M02*\n'
  8390. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8391. exported_gerber = header
  8392. exported_gerber += gerber_code
  8393. exported_gerber += footer
  8394. if local_use is None:
  8395. try:
  8396. with open(filename, 'w') as fp:
  8397. fp.write(exported_gerber)
  8398. except PermissionError:
  8399. self.inform.emit('[WARNING] %s' %
  8400. _("Permission denied, saving not possible.\n"
  8401. "Most likely another app is holding the file open and not accessible."))
  8402. return 'fail'
  8403. if self.defaults["global_open_style"] is False:
  8404. self.file_opened.emit("Gerber", filename)
  8405. self.file_saved.emit("Gerber", filename)
  8406. self.inform.emit('[success] %s: %s' %
  8407. (_("Gerber file exported to"), filename))
  8408. else:
  8409. return exported_gerber
  8410. except Exception as e:
  8411. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8412. return 'fail'
  8413. if use_thread is True:
  8414. with self.proc_container.new(_("Exporting Gerber")) as proc:
  8415. def job_thread_grb(app_obj):
  8416. ret = make_gerber()
  8417. if ret == 'fail':
  8418. self.inform.emit('[ERROR_NOTCL] %s' %
  8419. _('Could not export Gerber file.'))
  8420. return
  8421. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8422. else:
  8423. ret = make_gerber()
  8424. if ret == 'fail':
  8425. self.inform.emit('[ERROR_NOTCL] %s' %
  8426. _('Could not export Gerber file.'))
  8427. return 'fail'
  8428. if local_use is not None:
  8429. return ret
  8430. def export_dxf(self, obj_name, filename, use_thread=True):
  8431. """
  8432. Exports a Geometry Object to an DXF file.
  8433. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8434. :param filename: Path to the DXF file to save to.
  8435. :param use_thread: if to be run in a separate thread
  8436. :return:
  8437. """
  8438. self.report_usage("export_dxf()")
  8439. if filename is None:
  8440. filename = self.defaults["global_last_save_folder"]
  8441. self.log.debug("export_dxf()")
  8442. format_exc = ''
  8443. units = ''
  8444. try:
  8445. obj = self.collection.get_by_name(str(obj_name))
  8446. except:
  8447. # TODO: The return behavior has not been established... should raise exception?
  8448. return "Could not retrieve object: %s" % obj_name
  8449. # updated units
  8450. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8451. if units == 'IN' or units == 'INCH':
  8452. units = 'INCH'
  8453. elif units == 'MM' or units == 'METIRC':
  8454. units ='METRIC'
  8455. def make_dxf():
  8456. try:
  8457. dxf_code = obj.export_dxf()
  8458. dxf_code.saveas(filename)
  8459. if self.defaults["global_open_style"] is False:
  8460. self.file_opened.emit("DXF", filename)
  8461. self.file_saved.emit("DXF", filename)
  8462. self.inform.emit('[success] %s: %s' %
  8463. (_("DXF file exported to"), filename))
  8464. except:
  8465. return 'fail'
  8466. if use_thread is True:
  8467. with self.proc_container.new(_("Exporting DXF")) as proc:
  8468. def job_thread_exc(app_obj):
  8469. ret = make_dxf()
  8470. if ret == 'fail':
  8471. app_obj.inform.emit('[WARNING_NOTCL] %s' %
  8472. _('Could not export DXF file.'))
  8473. return
  8474. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8475. else:
  8476. ret = make_dxf()
  8477. if ret == 'fail':
  8478. self.inform.emit('[WARNING_NOTCL] %s' %
  8479. _('Could not export DXF file.'))
  8480. return
  8481. def import_svg(self, filename, geo_type='geometry', outname=None):
  8482. """
  8483. Adds a new Geometry Object to the projects and populates
  8484. it with shapes extracted from the SVG file.
  8485. :param filename: Path to the SVG file.
  8486. :param outname:
  8487. :return:
  8488. """
  8489. self.report_usage("import_svg()")
  8490. obj_type = ""
  8491. if geo_type is None or geo_type == "geometry":
  8492. obj_type = "geometry"
  8493. elif geo_type == "gerber":
  8494. obj_type = geo_type
  8495. else:
  8496. self.inform.emit('[ERROR_NOTCL] %s' %
  8497. _("Not supported type is picked as parameter. "
  8498. "Only Geometry and Gerber are supported"))
  8499. return
  8500. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8501. def obj_init(geo_obj, app_obj):
  8502. geo_obj.import_svg(filename, obj_type, units=units)
  8503. geo_obj.multigeo = False
  8504. with self.proc_container.new(_("Importing SVG")) as proc:
  8505. # Object name
  8506. name = outname or filename.split('/')[-1].split('\\')[-1]
  8507. self.new_object(obj_type, name, obj_init, autoselected=False)
  8508. self.progress.emit(20)
  8509. # Register recent file
  8510. self.file_opened.emit("svg", filename)
  8511. # GUI feedback
  8512. self.inform.emit('[success] %s: %s' %
  8513. (_("Opened"), filename))
  8514. self.progress.emit(100)
  8515. def import_dxf(self, filename, geo_type='geometry', outname=None):
  8516. """
  8517. Adds a new Geometry Object to the projects and populates
  8518. it with shapes extracted from the DXF file.
  8519. :param filename: Path to the DXF file.
  8520. :param outname:
  8521. :type putname: str
  8522. :return:
  8523. """
  8524. self.report_usage("import_dxf()")
  8525. obj_type = ""
  8526. if geo_type is None or geo_type == "geometry":
  8527. obj_type = "geometry"
  8528. elif geo_type == "gerber":
  8529. obj_type = geo_type
  8530. else:
  8531. self.inform.emit('[ERROR_NOTCL] %s' %
  8532. _("Not supported type is picked as parameter. "
  8533. "Only Geometry and Gerber are supported"))
  8534. return
  8535. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8536. def obj_init(geo_obj, app_obj):
  8537. geo_obj.import_dxf(filename, obj_type, units=units)
  8538. geo_obj.multigeo = False
  8539. with self.proc_container.new(_("Importing DXF")) as proc:
  8540. # Object name
  8541. name = outname or filename.split('/')[-1].split('\\')[-1]
  8542. self.new_object(obj_type, name, obj_init, autoselected=False)
  8543. self.progress.emit(20)
  8544. # Register recent file
  8545. self.file_opened.emit("dxf", filename)
  8546. # GUI feedback
  8547. self.inform.emit('[success] %s: %s' %
  8548. (_("Opened"), filename))
  8549. self.progress.emit(100)
  8550. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  8551. """
  8552. Adds a new Geometry Object to the projects and populates
  8553. it with shapes extracted from the SVG file.
  8554. :param filename: Path to the SVG file.
  8555. :param o_type: type of FlatCAM objeect
  8556. :param dpi: dot per inch
  8557. :param mode: black or color
  8558. :param mask: dictate the level of detail
  8559. :param outname: name for the resulting file
  8560. :return:
  8561. """
  8562. self.report_usage("import_image()")
  8563. if o_type is None or o_type == "geometry":
  8564. obj_type = "geometry"
  8565. elif o_type == "gerber":
  8566. obj_type = o_type
  8567. else:
  8568. self.inform.emit('[ERROR_NOTCL] %s' %
  8569. _("Not supported type is picked as parameter. "
  8570. "Only Geometry and Gerber are supported"))
  8571. return
  8572. def obj_init(geo_obj, app_obj):
  8573. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  8574. geo_obj.multigeo = False
  8575. with self.proc_container.new(_("Importing Image")) as proc:
  8576. # Object name
  8577. name = outname or filename.split('/')[-1].split('\\')[-1]
  8578. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  8579. self.new_object(obj_type, name, obj_init)
  8580. self.progress.emit(20)
  8581. # Register recent file
  8582. self.file_opened.emit("image", filename)
  8583. # GUI feedback
  8584. self.inform.emit('[success] %s: %s' %
  8585. (_("Opened"), filename))
  8586. self.progress.emit(100)
  8587. def open_gerber(self, filename, outname=None):
  8588. """
  8589. Opens a Gerber file, parses it and creates a new object for
  8590. it in the program. Thread-safe.
  8591. :param outname: Name of the resulting object. None causes the
  8592. name to be that of the file.
  8593. :param filename: Gerber file filename
  8594. :type filename: str
  8595. :param follow: If true, the parser will not create polygons, just lines
  8596. following the gerber path.
  8597. :type follow: bool
  8598. :return: None
  8599. """
  8600. # How the object should be initialized
  8601. def obj_init(gerber_obj, app_obj):
  8602. assert isinstance(gerber_obj, FlatCAMGerber), \
  8603. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  8604. # Opening the file happens here
  8605. self.progress.emit(30)
  8606. try:
  8607. gerber_obj.parse_file(filename)
  8608. except IOError:
  8609. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8610. (_("Failed to open file"), filename))
  8611. app_obj.progress.emit(0)
  8612. return "fail"
  8613. except ParseError as err:
  8614. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' %
  8615. (_("Failed to parse file"), filename, str(err)))
  8616. app_obj.progress.emit(0)
  8617. self.log.error(str(err))
  8618. return "fail"
  8619. except Exception as e:
  8620. log.debug("App.open_gerber() --> %s" % str(e))
  8621. msg = '[ERROR] %s' % \
  8622. _("An internal error has occurred. See shell.\n")
  8623. msg += traceback.format_exc()
  8624. app_obj.inform.emit(msg)
  8625. return "fail"
  8626. if gerber_obj.is_empty():
  8627. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  8628. # self.collection.set_active(gerber_obj.options["name"])
  8629. # self.collection.delete_active()
  8630. self.inform.emit('[ERROR_NOTCL] %s' %
  8631. _("Object is not Gerber file or empty. Aborting object creation."))
  8632. return "fail"
  8633. # Further parsing
  8634. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  8635. App.log.debug("open_gerber()")
  8636. with self.proc_container.new(_("Opening Gerber")) as proc:
  8637. self.progress.emit(10)
  8638. # Object name
  8639. name = outname or filename.split('/')[-1].split('\\')[-1]
  8640. # # ## Object creation # ##
  8641. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  8642. if ret == 'fail':
  8643. self.inform.emit('[ERROR_NOTCL]%s' %
  8644. _(' Open Gerber failed. Probable not a Gerber file.'))
  8645. return
  8646. # Register recent file
  8647. self.file_opened.emit("gerber", filename)
  8648. self.progress.emit(100)
  8649. # GUI feedback
  8650. self.inform.emit('[success] %s: %s' %
  8651. (_("Opened"), filename))
  8652. def open_excellon(self, filename, outname=None, plot=True):
  8653. """
  8654. Opens an Excellon file, parses it and creates a new object for
  8655. it in the program. Thread-safe.
  8656. :param outname: Name of the resulting object. None causes the
  8657. name to be that of the file.
  8658. :param filename: Excellon file filename
  8659. :type filename: str
  8660. :return: None
  8661. """
  8662. App.log.debug("open_excellon()")
  8663. # How the object should be initialized
  8664. def obj_init(excellon_obj, app_obj):
  8665. # self.progress.emit(20)
  8666. try:
  8667. ret = excellon_obj.parse_file(filename=filename)
  8668. if ret == "fail":
  8669. log.debug("Excellon parsing failed.")
  8670. self.inform.emit('[ERROR_NOTCL] %s' %
  8671. _("This is not Excellon file."))
  8672. return "fail"
  8673. except IOError:
  8674. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8675. (_("Cannot open file"), filename))
  8676. log.debug("Could not open Excellon object.")
  8677. self.progress.emit(0) # TODO: self and app_bjj mixed
  8678. return "fail"
  8679. except:
  8680. msg = '[ERROR_NOTCL] %s' % \
  8681. _("An internal error has occurred. See shell.\n")
  8682. msg += traceback.format_exc()
  8683. app_obj.inform.emit(msg)
  8684. return "fail"
  8685. ret = excellon_obj.create_geometry()
  8686. if ret == 'fail':
  8687. log.debug("Could not create geometry for Excellon object.")
  8688. return "fail"
  8689. for tool in excellon_obj.tools:
  8690. if excellon_obj.tools[tool]['solid_geometry']:
  8691. return
  8692. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8693. (_("No geometry found in file"), filename))
  8694. return "fail"
  8695. with self.proc_container.new(_("Opening Excellon.")):
  8696. # Object name
  8697. name = outname or filename.split('/')[-1].split('\\')[-1]
  8698. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8699. if ret_val == 'fail':
  8700. self.inform.emit('[ERROR_NOTCL] %s' %
  8701. _('Open Excellon file failed. Probable not an Excellon file.'))
  8702. return
  8703. # Register recent file
  8704. self.file_opened.emit("excellon", filename)
  8705. # GUI feedback
  8706. self.inform.emit('[success] %s: %s' %
  8707. (_("Opened"), filename))
  8708. def open_gcode(self, filename, outname=None, plot=True):
  8709. """
  8710. Opens a G-gcode file, parses it and creates a new object for
  8711. it in the program. Thread-safe.
  8712. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8713. :param filename: G-code file filename
  8714. :type filename: str
  8715. :return: None
  8716. """
  8717. App.log.debug("open_gcode()")
  8718. # How the object should be initialized
  8719. def obj_init(job_obj, app_obj_):
  8720. """
  8721. :param job_obj: the resulting object
  8722. :type app_obj_: App
  8723. """
  8724. assert isinstance(app_obj_, App), \
  8725. "Initializer expected App, got %s" % type(app_obj_)
  8726. self.progress.emit(10)
  8727. try:
  8728. f = open(filename)
  8729. gcode = f.read()
  8730. f.close()
  8731. except IOError:
  8732. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  8733. (_("Failed to open"), filename))
  8734. self.progress.emit(0)
  8735. return "fail"
  8736. job_obj.gcode = gcode
  8737. self.progress.emit(20)
  8738. ret = job_obj.gcode_parse()
  8739. if ret == "fail":
  8740. self.inform.emit('[ERROR_NOTCL] %s' %
  8741. _("This is not GCODE"))
  8742. return "fail"
  8743. self.progress.emit(60)
  8744. job_obj.create_geometry()
  8745. with self.proc_container.new(_("Opening G-Code.")):
  8746. # Object name
  8747. name = outname or filename.split('/')[-1].split('\\')[-1]
  8748. # New object creation and file processing
  8749. ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8750. if ret == 'fail':
  8751. self.inform.emit('[ERROR_NOTCL] %s' %
  8752. _("Failed to create CNCJob Object. Probable not a GCode file.\n "
  8753. "Attempting to create a FlatCAM CNCJob Object from "
  8754. "G-Code file failed during processing"))
  8755. return "fail"
  8756. # Register recent file
  8757. self.file_opened.emit("cncjob", filename)
  8758. # GUI feedback
  8759. self.inform.emit('[success] %s: %s' %
  8760. (_("Opened"), filename))
  8761. self.progress.emit(100)
  8762. def open_config_file(self, filename, run_from_arg=None):
  8763. """
  8764. Loads a config file from the specified file.
  8765. :param filename: Name of the file from which to load.
  8766. :type filename: str
  8767. :return: None
  8768. """
  8769. App.log.debug("Opening config file: " + filename)
  8770. if run_from_arg:
  8771. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8772. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8773. _("Opening FlatCAM Config file.")),
  8774. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8775. color=QtGui.QColor("gray"))
  8776. # add the tab if it was closed
  8777. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  8778. # first clear previous text in text editor (if any)
  8779. self.ui.code_editor.clear()
  8780. # Switch plot_area to CNCJob tab
  8781. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  8782. try:
  8783. if filename:
  8784. f = QtCore.QFile(filename)
  8785. if f.open(QtCore.QIODevice.ReadOnly):
  8786. stream = QtCore.QTextStream(f)
  8787. gcode_edited = stream.readAll()
  8788. self.ui.code_editor.setPlainText(gcode_edited)
  8789. f.close()
  8790. except IOError:
  8791. App.log.error("Failed to open config file: %s" % filename)
  8792. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8793. (_("Failed to open config file"), filename))
  8794. return
  8795. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  8796. """
  8797. Loads a project from the specified file.
  8798. 1) Loads and parses file
  8799. 2) Registers the file as recently opened.
  8800. 3) Calls on_file_new()
  8801. 4) Updates options
  8802. 5) Calls new_object() with the object's from_dict() as init method.
  8803. 6) Calls plot_all() if plot=True
  8804. :param filename: Name of the file from which to load.
  8805. :type filename: str
  8806. :param run_from_arg: True if run for arguments
  8807. :param plot: If True plot all objects in the project
  8808. :param cli: run from command line
  8809. :return: None
  8810. """
  8811. App.log.debug("Opening project: " + filename)
  8812. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8813. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8814. if cli is None:
  8815. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8816. if run_from_arg:
  8817. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8818. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8819. _("Opening FlatCAM Project file.")),
  8820. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8821. color=QtGui.QColor("gray"))
  8822. # Open and parse an uncompressed Project file
  8823. try:
  8824. f = open(filename, 'r')
  8825. except IOError:
  8826. App.log.error("Failed to open project file: %s" % filename)
  8827. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8828. (_("Failed to open project file"), filename))
  8829. return
  8830. try:
  8831. d = json.load(f, object_hook=dict2obj)
  8832. except Exception as e:
  8833. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8834. (filename, str(e)))
  8835. f.close()
  8836. # Open and parse a compressed Project file
  8837. try:
  8838. with lzma.open(filename) as f:
  8839. file_content = f.read().decode('utf-8')
  8840. d = json.loads(file_content, object_hook=dict2obj)
  8841. except Exception as e:
  8842. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8843. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8844. (_("Failed to open project file"), filename))
  8845. return
  8846. # Clear the current project
  8847. # # NOT THREAD SAFE # ##
  8848. if run_from_arg is True:
  8849. pass
  8850. elif cli is True:
  8851. self.delete_selection_shape()
  8852. else:
  8853. self.on_file_new()
  8854. # Project options
  8855. self.options.update(d['options'])
  8856. self.project_filename = filename
  8857. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8858. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8859. if cli is None:
  8860. self.set_screen_units(self.options["units"])
  8861. # Re create objects
  8862. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8863. for obj in d['objs']:
  8864. def obj_init(obj_inst, app_inst):
  8865. obj_inst.from_dict(obj)
  8866. App.log.debug("Recreating from opened project an %s object: %s" %
  8867. (obj['kind'].capitalize(), obj['options']['name']))
  8868. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8869. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8870. if cli is None:
  8871. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8872. obj['kind'].upper(),
  8873. obj['options']['name']
  8874. )
  8875. )
  8876. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  8877. self.inform.emit('[success] %s: %s' %
  8878. (_("Project loaded from"), filename))
  8879. self.should_we_save = False
  8880. self.file_opened.emit("project", filename)
  8881. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8882. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8883. if cli is None:
  8884. self.set_ui_title(name=self.project_filename)
  8885. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8886. def propagate_defaults(self, silent=False):
  8887. """
  8888. This method is used to set default values in classes. It's
  8889. an alternative to project options but allows the use
  8890. of values invisible to the user.
  8891. :return: None
  8892. """
  8893. if silent is False:
  8894. self.log.debug("propagate_defaults()")
  8895. # Which objects to update the given parameters.
  8896. routes = {
  8897. "global_zdownrate": CNCjob,
  8898. "excellon_zeros": Excellon,
  8899. "excellon_format_upper_in": Excellon,
  8900. "excellon_format_lower_in": Excellon,
  8901. "excellon_format_upper_mm": Excellon,
  8902. "excellon_format_lower_mm": Excellon,
  8903. "excellon_units": Excellon,
  8904. "gerber_use_buffer_for_union": Gerber,
  8905. "geometry_multidepth": Geometry
  8906. }
  8907. for param in routes:
  8908. if param in routes[param].defaults:
  8909. try:
  8910. routes[param].defaults[param] = self.defaults[param]
  8911. if silent is False:
  8912. self.log.debug(" " + param + " OK")
  8913. except KeyError:
  8914. if silent is False:
  8915. self.log.debug(" ERROR: " + param + " not in defaults.")
  8916. else:
  8917. # Try extracting the name:
  8918. # classname_param here is param in the object
  8919. if param.find(routes[param].__name__.lower() + "_") == 0:
  8920. p = param[len(routes[param].__name__) + 1:]
  8921. if p in routes[param].defaults:
  8922. routes[param].defaults[p] = self.defaults[param]
  8923. if silent is False:
  8924. self.log.debug(" " + param + " OK!")
  8925. def plot_all(self, zoom=True):
  8926. """
  8927. Re-generates all plots from all objects.
  8928. :return: None
  8929. """
  8930. self.log.debug("Plot_all()")
  8931. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  8932. for obj in self.collection.get_list():
  8933. def worker_task(obj):
  8934. with self.proc_container.new("Plotting"):
  8935. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8936. if zoom:
  8937. self.object_plotted.emit(obj)
  8938. # Send to worker
  8939. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  8940. def register_folder(self, filename):
  8941. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8942. def register_save_folder(self, filename):
  8943. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8944. def set_progress_bar(self, percentage, text=""):
  8945. self.ui.progress_bar.setValue(int(percentage))
  8946. def setup_shell(self):
  8947. """
  8948. Creates shell functions. Runs once at startup.
  8949. :return: None
  8950. """
  8951. self.log.debug("setup_shell()")
  8952. def shelp(p=None):
  8953. if not p:
  8954. return _("Available commands:\n") + \
  8955. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  8956. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  8957. if p not in commands:
  8958. return "Unknown command: %s" % p
  8959. return commands[p]["help"]
  8960. # --- Migrated to new architecture ---
  8961. # def options(name):
  8962. # ops = self.collection.get_by_name(str(name)).options
  8963. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  8964. def h(*args):
  8965. """
  8966. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  8967. and standalone parameters into list.
  8968. """
  8969. kwa = {}
  8970. a = []
  8971. n = len(args)
  8972. name = None
  8973. for i in range(n):
  8974. match = re.search(r'^-([a-zA-Z].*)', args[i])
  8975. if match:
  8976. assert name is None
  8977. name = match.group(1)
  8978. continue
  8979. if name is None:
  8980. a.append(args[i])
  8981. else:
  8982. kwa[name] = args[i]
  8983. name = None
  8984. return a, kwa
  8985. @contextmanager
  8986. def wait_signal(signal, timeout=10000):
  8987. """
  8988. Block loop until signal emitted, timeout (ms) elapses
  8989. or unhandled exception happens in a thread.
  8990. :param timeout: time after which the loop is exited
  8991. :param signal: Signal to wait for.
  8992. """
  8993. loop = QtCore.QEventLoop()
  8994. # Normal termination
  8995. signal.connect(loop.quit)
  8996. # Termination by exception in thread
  8997. self.thread_exception.connect(loop.quit)
  8998. status = {'timed_out': False}
  8999. def report_quit():
  9000. status['timed_out'] = True
  9001. loop.quit()
  9002. yield
  9003. # Temporarily change how exceptions are managed.
  9004. oeh = sys.excepthook
  9005. ex = []
  9006. def except_hook(type_, value, traceback_):
  9007. ex.append(value)
  9008. oeh(type_, value, traceback_)
  9009. sys.excepthook = except_hook
  9010. # Terminate on timeout
  9011. if timeout is not None:
  9012. QtCore.QTimer.singleShot(timeout, report_quit)
  9013. # # ## Block ## ##
  9014. loop.exec_()
  9015. # Restore exception management
  9016. sys.excepthook = oeh
  9017. if ex:
  9018. self.raiseTclError(str(ex[0]))
  9019. if status['timed_out']:
  9020. raise Exception('Timed out!')
  9021. def make_docs():
  9022. output = ''
  9023. import collections
  9024. od = collections.OrderedDict(sorted(commands.items()))
  9025. for cmd_, val in od.items():
  9026. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  9027. t = val['help']
  9028. usage_i = t.find('>')
  9029. if usage_i < 0:
  9030. expl = t
  9031. output += expl + '\n\n'
  9032. continue
  9033. expl = t[:usage_i - 1]
  9034. output += expl + '\n\n'
  9035. end_usage_i = t[usage_i:].find('\n')
  9036. if end_usage_i < 0:
  9037. end_usage_i = len(t[usage_i:])
  9038. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  9039. else:
  9040. extras = t[usage_i+end_usage_i+1:]
  9041. parts = [s.strip() for s in extras.split('\n')]
  9042. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  9043. for p in parts:
  9044. output += ' ' + p + '\n\n'
  9045. return output
  9046. '''
  9047. Howto implement TCL shell commands:
  9048. All parameters passed to command should be possible to set as None and test it afterwards.
  9049. This is because we need to see error caused in tcl,
  9050. if None value as default parameter is not allowed TCL will return empty error.
  9051. Use:
  9052. def mycommand(name=None,...):
  9053. Test it like this:
  9054. if name is None:
  9055. self.raise_tcl_error('Argument name is missing.')
  9056. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  9057. otherwise we will miss it and processing will silently continue.
  9058. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  9059. which is catched in exec_command and displayed in TCL shell console with red background.
  9060. Error in console is displayed with TCL trace.
  9061. This behavior works only within main thread,
  9062. errors with promissed tasks can be catched and detected only with log.
  9063. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  9064. TCL shell.
  9065. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  9066. '''
  9067. commands = {
  9068. 'help': {
  9069. 'fcn': shelp,
  9070. 'help': _("Shows list of commands.")
  9071. },
  9072. }
  9073. # Import/overwrite tcl commands as objects of TclCommand descendants
  9074. # This modifies the variable 'commands'.
  9075. tclCommands.register_all_commands(self, commands)
  9076. # Add commands to the tcl interpreter
  9077. for cmd in commands:
  9078. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  9079. # Make the tcl puts function return instead of print to stdout
  9080. self.tcl.eval('''
  9081. rename puts original_puts
  9082. proc puts {args} {
  9083. if {[llength $args] == 1} {
  9084. return "[lindex $args 0]"
  9085. } else {
  9086. eval original_puts $args
  9087. }
  9088. }
  9089. ''')
  9090. def setup_recent_items(self):
  9091. # TODO: Move this to constructor
  9092. icons = {
  9093. "gerber": "share/flatcam_icon16.png",
  9094. "excellon": "share/drill16.png",
  9095. 'geometry': "share/geometry16.png",
  9096. "cncjob": "share/cnc16.png",
  9097. "project": "share/project16.png",
  9098. "svg": "share/geometry16.png",
  9099. "dxf": "share/dxf16.png",
  9100. "pdf": "share/pdf32.png",
  9101. "image": "share/image16.png"
  9102. }
  9103. openers = {
  9104. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  9105. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  9106. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  9107. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  9108. 'project': self.open_project,
  9109. 'svg': self.import_svg,
  9110. 'dxf': self.import_dxf,
  9111. 'image': self.import_image,
  9112. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  9113. }
  9114. # Open recent file for files
  9115. try:
  9116. f = open(self.data_path + '/recent.json')
  9117. except IOError:
  9118. App.log.error("Failed to load recent item list.")
  9119. self.inform.emit('[ERROR_NOTCL] %s' %
  9120. _("Failed to load recent item list."))
  9121. return
  9122. try:
  9123. self.recent = json.load(f)
  9124. except json.scanner.JSONDecodeError:
  9125. App.log.error("Failed to parse recent item list.")
  9126. self.inform.emit('[ERROR_NOTCL] %s' %
  9127. _("Failed to parse recent item list."))
  9128. f.close()
  9129. return
  9130. f.close()
  9131. # Open recent file for projects
  9132. try:
  9133. fp = open(self.data_path + '/recent_projects.json')
  9134. except IOError:
  9135. App.log.error("Failed to load recent project item list.")
  9136. self.inform.emit('[ERROR_NOTCL] %s' %
  9137. _("Failed to load recent projects item list."))
  9138. return
  9139. try:
  9140. self.recent_projects = json.load(fp)
  9141. except json.scanner.JSONDecodeError:
  9142. App.log.error("Failed to parse recent project item list.")
  9143. self.inform.emit('[ERROR_NOTCL] %s' %
  9144. _("Failed to parse recent project item list."))
  9145. fp.close()
  9146. return
  9147. fp.close()
  9148. # Closure needed to create callbacks in a loop.
  9149. # Otherwise late binding occurs.
  9150. def make_callback(func, fname):
  9151. def opener():
  9152. func(fname)
  9153. return opener
  9154. def reset_recent_files():
  9155. # Reset menu
  9156. self.ui.recent.clear()
  9157. self.recent = []
  9158. try:
  9159. f = open(self.data_path + '/recent.json', 'w')
  9160. except IOError:
  9161. App.log.error("Failed to open recent items file for writing.")
  9162. return
  9163. json.dump(self.recent, f)
  9164. def reset_recent_projects():
  9165. # Reset menu
  9166. self.ui.recent_projects.clear()
  9167. self.recent_projects = []
  9168. try:
  9169. fp = open(self.data_path + '/recent_projects.json', 'w')
  9170. except IOError:
  9171. App.log.error("Failed to open recent projects items file for writing.")
  9172. return
  9173. json.dump(self.recent, fp)
  9174. # Reset menu
  9175. self.ui.recent.clear()
  9176. self.ui.recent_projects.clear()
  9177. # Create menu items for projects
  9178. for recent in self.recent_projects:
  9179. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9180. if recent['kind'] == 'project':
  9181. try:
  9182. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9183. # Attach callback
  9184. o = make_callback(openers[recent["kind"]], recent['filename'])
  9185. action.triggered.connect(o)
  9186. self.ui.recent_projects.addAction(action)
  9187. except KeyError:
  9188. App.log.error("Unsupported file type: %s" % recent["kind"])
  9189. # Last action in Recent Files menu is one that Clear the content
  9190. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  9191. clear_action_proj.triggered.connect(reset_recent_projects)
  9192. self.ui.recent_projects.addSeparator()
  9193. self.ui.recent_projects.addAction(clear_action_proj)
  9194. # Create menu items for files
  9195. for recent in self.recent:
  9196. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9197. if recent['kind'] != 'project':
  9198. try:
  9199. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9200. # Attach callback
  9201. o = make_callback(openers[recent["kind"]], recent['filename'])
  9202. action.triggered.connect(o)
  9203. self.ui.recent.addAction(action)
  9204. except KeyError:
  9205. App.log.error("Unsupported file type: %s" % recent["kind"])
  9206. # Last action in Recent Files menu is one that Clear the content
  9207. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  9208. clear_action.triggered.connect(reset_recent_files)
  9209. self.ui.recent.addSeparator()
  9210. self.ui.recent.addAction(clear_action)
  9211. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  9212. # self.ui.menufilerecent.set_submenu(recent_menu)
  9213. # recent_menu.show_all()
  9214. # self.ui.recent.show()
  9215. self.log.debug("Recent items list has been populated.")
  9216. def setup_component_editor(self):
  9217. # label = QtWidgets.QLabel("Choose an item from Project")
  9218. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  9219. sel_title = QtWidgets.QTextEdit(
  9220. _('<b>Shortcut Key List</b>'))
  9221. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  9222. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  9223. settings = QSettings("Open Source", "FlatCAM")
  9224. if settings.contains("notebook_font_size"):
  9225. fsize = settings.value('notebook_font_size', type=int)
  9226. else:
  9227. fsize = 12
  9228. tsize = fsize + int(fsize / 2)
  9229. # selected_text = (_('''
  9230. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  9231. #
  9232. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  9233. # The normal flow when working in FlatCAM is the following:</span></p>
  9234. #
  9235. # <ol>
  9236. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  9237. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  9238. # even dragging and dropping the files on the GUI.<br />
  9239. # <br />
  9240. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  9241. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  9242. # &nbsp;</li>
  9243. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  9244. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  9245. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  9246. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  9247. # <br />
  9248. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  9249. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  9250. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  9251. # it even if it was out of focus.<br />
  9252. # <br />
  9253. # You can change the parameters in this screen and the flow direction is like this:<br />
  9254. # <br />
  9255. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  9256. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  9257. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  9258. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  9259. # </ol>
  9260. #
  9261. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  9262. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  9263. # <strong>F3</strong>.</span></p>
  9264. #
  9265. # ''').format(fsize=fsize, tsize=tsize))
  9266. selected_text = '''
  9267. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  9268. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  9269. {s1}</span></p>
  9270. <ol>
  9271. <li><span style="font-size:{fsize}px">{s2}<br />
  9272. <br />
  9273. {s3}</span><br />
  9274. &nbsp;</li>
  9275. <li><span style="font-size:{fsize}px">{s4}<br />
  9276. &nbsp;</li>
  9277. <br />
  9278. <li><span style="font-size:{fsize}px">{s5}<br />
  9279. &nbsp;</li>
  9280. <br />
  9281. <li><span style="font-size:{fsize}px">{s6}<br />
  9282. <br />
  9283. {s7}</span></li>
  9284. </ol>
  9285. <p><span style="font-size:{fsize}px">{s8}</span></p>
  9286. '''.format(
  9287. title=_("Selected Tab - Choose an Item from Project Tab"),
  9288. subtitle=_("Details"),
  9289. s1=_("The normal flow when working in FlatCAM is the following:"),
  9290. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  9291. "using either the toolbars, key shortcuts or even dragging and dropping the "
  9292. "files on the GUI."),
  9293. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  9294. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  9295. "actions offered within the app."),
  9296. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  9297. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  9298. "SELECTED TAB will be updated with the object properties according to its kind: "
  9299. "Gerber, Excellon, Geometry or CNCJob object."),
  9300. s5=_("If the selection of the object is done on the canvas by single click instead, "
  9301. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  9302. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  9303. "the SELECTED TAB and populate it even if it was out of focus."),
  9304. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  9305. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  9306. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  9307. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  9308. "(again, done in SELECTED TAB) --> Save GCode."),
  9309. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  9310. "or through its own key shortcut: <b>F3</b>."),
  9311. tsize=tsize,
  9312. fsize=fsize
  9313. )
  9314. sel_title.setText(selected_text)
  9315. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  9316. self.ui.selected_scroll_area.setWidget(sel_title)
  9317. def setup_obj_classes(self):
  9318. """
  9319. Sets up application specifics on the FlatCAMObj class.
  9320. :return: None
  9321. """
  9322. FlatCAMObj.app = self
  9323. ObjectCollection.app = self
  9324. Gerber.app = self
  9325. Excellon.app = self
  9326. Geometry.app = self
  9327. CNCjob.app = self
  9328. FCProcess.app = self
  9329. FCProcessContainer.app = self
  9330. def version_check(self):
  9331. """
  9332. Checks for the latest version of the program. Alerts the
  9333. user if theirs is outdated. This method is meant to be run
  9334. in a separate thread.
  9335. :return: None
  9336. """
  9337. self.log.debug("version_check()")
  9338. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  9339. full_url = App.version_url + \
  9340. "?s=" + str(self.defaults['global_serial']) + \
  9341. "&v=" + str(self.version) + \
  9342. "&os=" + str(self.os) + \
  9343. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  9344. else:
  9345. # no_stats dict; just so it won't break things on website
  9346. no_ststs_dict = {}
  9347. no_ststs_dict["global_ststs"] = {}
  9348. full_url = App.version_url + \
  9349. "?s=" + str(self.defaults['global_serial']) + \
  9350. "&v=" + str(self.version) + \
  9351. "&os=" + str(self.os) + \
  9352. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  9353. App.log.debug("Checking for updates @ %s" % full_url)
  9354. # ## Get the data
  9355. try:
  9356. f = urllib.request.urlopen(full_url)
  9357. except:
  9358. # App.log.warning("Failed checking for latest version. Could not connect.")
  9359. self.log.warning("Failed checking for latest version. Could not connect.")
  9360. self.inform.emit('[WARNING_NOTCL] %s' %
  9361. _("Failed checking for latest version. Could not connect."))
  9362. return
  9363. try:
  9364. data = json.load(f)
  9365. except Exception as e:
  9366. App.log.error("Could not parse information about latest version.")
  9367. self.inform.emit('[ERROR_NOTCL] %s' %
  9368. _("Could not parse information about latest version."))
  9369. App.log.debug("json.load(): %s" % str(e))
  9370. f.close()
  9371. return
  9372. f.close()
  9373. # ## Latest version?
  9374. if self.version >= data["version"]:
  9375. App.log.debug("FlatCAM is up to date!")
  9376. self.inform.emit('[success] %s' %
  9377. _("FlatCAM is up to date!"))
  9378. return
  9379. App.log.debug("Newer version available.")
  9380. self.message.emit(
  9381. _("Newer Version Available"),
  9382. _("There is a newer version of FlatCAM available for download:\n\n") +
  9383. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  9384. _("info")
  9385. )
  9386. def on_plotcanvas_setup(self, container=None):
  9387. """
  9388. This is doing the setup for the plot area (VisPy canvas)
  9389. :param container: widget where to install the canvas
  9390. :return: None
  9391. """
  9392. if container:
  9393. plot_container = container
  9394. else:
  9395. plot_container = self.ui.right_layout
  9396. if self.is_legacy is False:
  9397. self.plotcanvas = PlotCanvas(plot_container, self)
  9398. else:
  9399. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  9400. # So it can receive key presses
  9401. self.plotcanvas.native.setFocus()
  9402. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  9403. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  9404. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  9405. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_double_click_over_plot)
  9406. # Keys over plot enabled
  9407. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  9408. if self.defaults['global_cursor_type'] == 'small':
  9409. self.app_cursor = self.plotcanvas.new_cursor()
  9410. else:
  9411. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  9412. if self.ui.grid_snap_btn.isChecked():
  9413. self.app_cursor.enabled = True
  9414. else:
  9415. self.app_cursor.enabled = False
  9416. if self.is_legacy is False:
  9417. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  9418. else:
  9419. # will use the default Matplotlib axes
  9420. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  9421. def on_zoom_fit(self, event):
  9422. """
  9423. Callback for zoom-out request. This can be either from the corresponding
  9424. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  9425. with axes limits from the geometry bounds of all objects.
  9426. :param event: Ignored.
  9427. :return: None
  9428. """
  9429. if self.is_legacy is False:
  9430. self.plotcanvas.fit_view()
  9431. else:
  9432. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  9433. width = xmax - xmin
  9434. height = ymax - ymin
  9435. xmin -= 0.05 * width
  9436. xmax += 0.05 * width
  9437. ymin -= 0.05 * height
  9438. ymax += 0.05 * height
  9439. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  9440. def on_zoom_in(self):
  9441. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  9442. def on_zoom_out(self):
  9443. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  9444. def disable_all_plots(self):
  9445. self.report_usage("disable_all_plots()")
  9446. self.disable_plots(self.collection.get_list())
  9447. self.inform.emit('[success] %s' %
  9448. _("All plots disabled."))
  9449. def disable_other_plots(self):
  9450. self.report_usage("disable_other_plots()")
  9451. self.disable_plots(self.collection.get_non_selected())
  9452. self.inform.emit('[success] %s' %
  9453. _("All non selected plots disabled."))
  9454. def enable_all_plots(self):
  9455. self.report_usage("enable_all_plots()")
  9456. self.enable_plots(self.collection.get_list())
  9457. self.inform.emit('[success] %s' %
  9458. _("All plots enabled."))
  9459. def on_enable_sel_plots(self):
  9460. log.debug("App.on_enable_sel_plot()")
  9461. object_list = self.collection.get_selected()
  9462. self.enable_plots(objects=object_list)
  9463. self.inform.emit('[success] %s' %
  9464. _("Selected plots enabled..."))
  9465. def on_disable_sel_plots(self):
  9466. log.debug("App.on_disable_sel_plot()")
  9467. # self.inform.emit(_("Disabling plots ..."))
  9468. object_list = self.collection.get_selected()
  9469. self.disable_plots(objects=object_list)
  9470. self.inform.emit('[success] %s' %
  9471. _("Selected plots disabled..."))
  9472. def enable_plots(self, objects):
  9473. """
  9474. Disables plots
  9475. :param objects: list of Objects to be enabled
  9476. :return:
  9477. """
  9478. log.debug("Enabling plots ...")
  9479. # self.inform.emit(_("Working ..."))
  9480. for obj in objects:
  9481. if obj.options['plot'] is False:
  9482. obj.options.set_change_callback(lambda x: None)
  9483. obj.options['plot'] = True
  9484. obj.options.set_change_callback(obj.on_options_change)
  9485. def worker_task(objects):
  9486. with self.proc_container.new(_("Enabling plots ...")):
  9487. for obj in objects:
  9488. # obj.options['plot'] = True
  9489. if isinstance(obj, FlatCAMCNCjob):
  9490. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  9491. else:
  9492. obj.plot(visible=True)
  9493. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9494. # self.plots_updated.emit()
  9495. def disable_plots(self, objects):
  9496. """
  9497. Disables plots
  9498. :param objects: list of Objects to be disabled
  9499. :return:
  9500. """
  9501. # if no objects selected then do nothing
  9502. if not self.collection.get_selected():
  9503. return
  9504. log.debug("Disabling plots ...")
  9505. # self.inform.emit(_("Working ..."))
  9506. for obj in objects:
  9507. if obj.options['plot'] is True:
  9508. obj.options.set_change_callback(lambda x: None)
  9509. obj.options['plot'] = False
  9510. obj.options.set_change_callback(obj.on_options_change)
  9511. try:
  9512. self.delete_selection_shape()
  9513. except Exception as e:
  9514. log.debug("App.disable_plots() --> %s" % str(e))
  9515. # self.plots_updated.emit()
  9516. def worker_task(objects):
  9517. with self.proc_container.new(_("Disabling plots ...")):
  9518. for obj in objects:
  9519. # obj.options['plot'] = True
  9520. if isinstance(obj, FlatCAMCNCjob):
  9521. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  9522. else:
  9523. obj.plot(visible=False)
  9524. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9525. def toggle_plots(self, objects):
  9526. """
  9527. Toggle plots visibility
  9528. :param objects: list of Objects for which to be toggled the visibility
  9529. :return:
  9530. """
  9531. # if no objects selected then do nothing
  9532. if not self.collection.get_selected():
  9533. return
  9534. log.debug("Toggling plots ...")
  9535. self.inform.emit(_("Working ..."))
  9536. for obj in objects:
  9537. if obj.options['plot'] is False:
  9538. obj.options['plot'] = True
  9539. else:
  9540. obj.options['plot'] = False
  9541. self.plots_updated.emit()
  9542. def clear_plots(self):
  9543. objects = self.collection.get_list()
  9544. for obj in objects:
  9545. obj.clear(obj == objects[-1])
  9546. # Clear pool to free memory
  9547. self.clear_pool()
  9548. def generate_cnc_job(self, objects):
  9549. self.report_usage("generate_cnc_job()")
  9550. # for obj in objects:
  9551. # obj.generatecncjob()
  9552. for obj in objects:
  9553. obj.on_generatecnc_button_click()
  9554. def save_project(self, filename, quit_action=False, silent=False):
  9555. """
  9556. Saves the current project to the specified file.
  9557. :param filename: Name of the file in which to save.
  9558. :type filename: str
  9559. :param quit_action: if the project saving will be followed by an app quit; boolean
  9560. :param silent: if True will not display status messages
  9561. :return: None
  9562. """
  9563. self.log.debug("save_project()")
  9564. self.save_in_progress = True
  9565. with self.proc_container.new(_("Saving FlatCAM Project")):
  9566. # Capture the latest changes
  9567. # Current object
  9568. try:
  9569. self.collection.get_active().read_form()
  9570. except:
  9571. self.log.debug("There was no active object")
  9572. pass
  9573. # Project options
  9574. self.options_read_form()
  9575. # Serialize the whole project
  9576. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  9577. "options": self.options,
  9578. "version": self.version}
  9579. if self.defaults["global_save_compressed"] is True:
  9580. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  9581. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  9582. # # Write
  9583. f.write(g)
  9584. self.inform.emit('[success] %s: %s' %
  9585. (_("Project saved to"), filename))
  9586. else:
  9587. # Open file
  9588. try:
  9589. f = open(filename, 'w')
  9590. except IOError:
  9591. App.log.error("Failed to open file for saving: %s", filename)
  9592. return
  9593. # Write
  9594. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  9595. f.close()
  9596. # verification of the saved project
  9597. # Open and parse
  9598. try:
  9599. saved_f = open(filename, 'r')
  9600. except IOError:
  9601. if silent is False:
  9602. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9603. (_("Failed to verify project file"), filename, _("Retry to save it."))
  9604. )
  9605. return
  9606. try:
  9607. saved_d = json.load(saved_f, object_hook=dict2obj)
  9608. except:
  9609. if silent is False:
  9610. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9611. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9612. )
  9613. f.close()
  9614. return
  9615. saved_f.close()
  9616. if silent is False:
  9617. if 'version' in saved_d:
  9618. self.inform.emit('[success] %s: %s' %
  9619. (_("Project saved to"), filename))
  9620. else:
  9621. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9622. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9623. )
  9624. settings = QSettings("Open Source", "FlatCAM")
  9625. lock_state = self.ui.lock_action.isChecked()
  9626. settings.setValue('toolbar_lock', lock_state)
  9627. # This will write the setting to the platform specific storage.
  9628. del settings
  9629. # if quit:
  9630. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  9631. # t.start()
  9632. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  9633. def start_delayed_quit(self, delay, filename, should_quit=None):
  9634. """
  9635. :param delay: period of checking if project file size is more than zero; in seconds
  9636. :param filename: the name of the project file to be checked periodically for size more than zero
  9637. :param should_quit: if the task finished will be followed by an app quit; boolean
  9638. :return:
  9639. """
  9640. to_quit = should_quit
  9641. self.save_timer = QtCore.QTimer()
  9642. self.save_timer.setInterval(delay)
  9643. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  9644. self.save_timer.start()
  9645. def check_project_file_size(self, filename, should_quit=None):
  9646. """
  9647. :param filename: the name of the project file to be checked periodically for size more than zero
  9648. :param should_quit: will quit the app if True; boolean
  9649. :return:
  9650. """
  9651. try:
  9652. if os.stat(filename).st_size > 0:
  9653. self.save_in_progress = False
  9654. self.save_timer.stop()
  9655. if should_quit:
  9656. self.app_quit.emit()
  9657. except Exception as e:
  9658. traceback.print_exc()
  9659. def on_options_app2project(self):
  9660. """
  9661. Callback for Options->Transfer Options->App=>Project. Copies options
  9662. from application defaults to project defaults.
  9663. :return: None
  9664. """
  9665. self.report_usage("on_options_app2project")
  9666. self.defaults_read_form()
  9667. self.options.update(self.defaults)
  9668. self.options_write_form()
  9669. def on_options_project2app(self):
  9670. """
  9671. Callback for Options->Transfer Options->Project=>App. Copies options
  9672. from project defaults to application defaults.
  9673. :return: None
  9674. """
  9675. self.report_usage("on_options_project2app")
  9676. self.options_read_form()
  9677. self.defaults.update(self.options)
  9678. self.defaults_write_form()
  9679. def on_options_project2object(self):
  9680. """
  9681. Callback for Options->Transfer Options->Project=>Object. Copies options
  9682. from project defaults to the currently selected object.
  9683. :return: None
  9684. """
  9685. self.report_usage("on_options_project2object")
  9686. self.options_read_form()
  9687. obj = self.collection.get_active()
  9688. if obj is None:
  9689. self.inform.emit('[WARNING_NOTCL] %s' %
  9690. _("No object selected."))
  9691. return
  9692. for option in self.options:
  9693. if option.find(obj.kind + "_") == 0:
  9694. oname = option[len(obj.kind) + 1:]
  9695. obj.options[oname] = self.options[option]
  9696. obj.to_form() # Update UI
  9697. def on_options_object2project(self):
  9698. """
  9699. Callback for Options->Transfer Options->Object=>Project. Copies options
  9700. from the currently selected object to project defaults.
  9701. :return: None
  9702. """
  9703. self.report_usage("on_options_object2project")
  9704. obj = self.collection.get_active()
  9705. if obj is None:
  9706. self.inform.emit('[WARNING_NOTCL] %s' %
  9707. _("No object selected."))
  9708. return
  9709. obj.read_form()
  9710. for option in obj.options:
  9711. if option in ['name']: # TODO: Handle this better...
  9712. continue
  9713. self.options[obj.kind + "_" + option] = obj.options[option]
  9714. self.options_write_form()
  9715. def on_options_object2app(self):
  9716. """
  9717. Callback for Options->Transfer Options->Object=>App. Copies options
  9718. from the currently selected object to application defaults.
  9719. :return: None
  9720. """
  9721. self.report_usage("on_options_object2app")
  9722. obj = self.collection.get_active()
  9723. if obj is None:
  9724. self.inform.emit('[WARNING_NOTCL] %s' %
  9725. _("No object selected."))
  9726. return
  9727. obj.read_form()
  9728. for option in obj.options:
  9729. if option in ['name']: # TODO: Handle this better...
  9730. continue
  9731. self.defaults[obj.kind + "_" + option] = obj.options[option]
  9732. self.defaults_write_form()
  9733. def on_options_app2object(self):
  9734. """
  9735. Callback for Options->Transfer Options->App=>Object. Copies options
  9736. from application defaults to the currently selected object.
  9737. :return: None
  9738. """
  9739. self.report_usage("on_options_app2object")
  9740. self.defaults_read_form()
  9741. obj = self.collection.get_active()
  9742. if obj is None:
  9743. self.inform.emit('[WARNING_NOTCL] %s' %
  9744. _("No object selected."))
  9745. return
  9746. for option in self.defaults:
  9747. if option.find(obj.kind + "_") == 0:
  9748. oname = option[len(obj.kind) + 1:]
  9749. obj.options[oname] = self.defaults[option]
  9750. obj.to_form() # Update UI
  9751. class ArgsThread(QtCore.QObject):
  9752. open_signal = pyqtSignal(list)
  9753. start = pyqtSignal()
  9754. if sys.platform == 'win32':
  9755. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  9756. else:
  9757. address = ('/tmp/testipc', 'AF_UNIX')
  9758. def __init__(self):
  9759. super(ArgsThread, self).__init__()
  9760. self.start.connect(self.run)
  9761. def my_loop(self, address):
  9762. try:
  9763. listener = Listener(*address)
  9764. while True:
  9765. conn = listener.accept()
  9766. self.serve(conn)
  9767. except socket.error as e:
  9768. conn = Client(*address)
  9769. conn.send(sys.argv)
  9770. conn.send('close')
  9771. # close the current instance only if there are args
  9772. if len(sys.argv) > 1:
  9773. sys.exit()
  9774. def serve(self, conn):
  9775. while True:
  9776. msg = conn.recv()
  9777. if msg == 'close':
  9778. break
  9779. self.open_signal.emit(msg)
  9780. conn.close()
  9781. # the decorator is a must; without it this technique will not work unless the start signal is connected
  9782. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  9783. @pyqtSlot()
  9784. def run(self):
  9785. self.my_loop(self.address)
  9786. class GracefulException(Exception):
  9787. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  9788. def __init__(self):
  9789. super().__init__()
  9790. def __str__(self):
  9791. return ('\n\n%s' % _("The user requested a graceful exit of the current task."))
  9792. # end of file