FlatCAMApp.py 527 KB

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