FlatCAMApp.py 461 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377
  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 winreg
  21. import tkinter as tk
  22. from PyQt5 import QtPrintSupport
  23. from contextlib import contextmanager
  24. import gc
  25. from xml.dom.minidom import parseString as parse_xml_string
  26. from multiprocessing.connection import Listener, Client
  27. from multiprocessing import Pool
  28. import socket
  29. from array import array
  30. # #######################################
  31. # # Imports part of FlatCAM ##
  32. # #######################################
  33. from ObjectCollection import *
  34. from FlatCAMObj import *
  35. from flatcamGUI.PlotCanvas 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. fcTranslate.apply_language('strings')
  53. if '_' not in builtins.__dict__:
  54. _ = gettext.gettext
  55. # ########################################
  56. # # App ###
  57. # ########################################
  58. class App(QtCore.QObject):
  59. """
  60. The main application class. The constructor starts the GUI.
  61. """
  62. # Get Cmd Line Options
  63. cmd_line_shellfile = ''
  64. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  65. try:
  66. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  67. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  68. except getopt.GetoptError:
  69. print(cmd_line_help)
  70. sys.exit(2)
  71. for opt, arg in cmd_line_options:
  72. if opt == '-h':
  73. print(cmd_line_help)
  74. sys.exit()
  75. elif opt == '--shellfile':
  76. cmd_line_shellfile = arg
  77. # ## Logging ###
  78. log = logging.getLogger('base')
  79. log.setLevel(logging.DEBUG)
  80. # log.setLevel(logging.WARNING)
  81. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  82. handler = logging.StreamHandler()
  83. handler.setFormatter(formatter)
  84. log.addHandler(handler)
  85. # ##########################################################################
  86. # ################## Version and VERSION DATE ##############################
  87. # ##########################################################################
  88. version = 8.97
  89. version_date = "2019/09/15"
  90. beta = True
  91. # current date now
  92. date = str(datetime.today()).rpartition('.')[0]
  93. date = ''.join(c for c in date if c not in ':-')
  94. date = date.replace(' ', '_')
  95. # URL for update checks and statistics
  96. version_url = "http://flatcam.org/version"
  97. # App URL
  98. app_url = "http://flatcam.org"
  99. # Manual URL
  100. manual_url = "http://flatcam.org/manual/index.html"
  101. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  102. # this variable will hold the project status
  103. # if True it will mean that the project was modified and not saved
  104. should_we_save = False
  105. # flag is True if saving action has been triggered
  106. save_in_progress = False
  107. # ###########################################################################
  108. # ############################# Signals ################################
  109. # ###########################################################################
  110. # Inform the user
  111. # Handled by:
  112. # * App.info() --> Print on the status bar
  113. inform = QtCore.pyqtSignal(str)
  114. app_quit = QtCore.pyqtSignal()
  115. # General purpose background task
  116. worker_task = QtCore.pyqtSignal(dict)
  117. # File opened
  118. # Handled by:
  119. # * register_folder()
  120. # * register_recent()
  121. # Note: Setting the parameters to unicode does not seem
  122. # to have an effect. Then are received as Qstring
  123. # anyway.
  124. # File type and filename
  125. file_opened = QtCore.pyqtSignal(str, str)
  126. # File type and filename
  127. file_saved = QtCore.pyqtSignal(str, str)
  128. # Percentage of progress
  129. progress = QtCore.pyqtSignal(int)
  130. plots_updated = QtCore.pyqtSignal()
  131. # Emitted by new_object() and passes the new object as argument, plot flag.
  132. # on_object_created() adds the object to the collection, plots on appropriate flag
  133. # and emits new_object_available.
  134. object_created = QtCore.pyqtSignal(object, bool, bool)
  135. # Emitted when a object has been changed (like scaled, mirrored)
  136. object_changed = QtCore.pyqtSignal(object)
  137. # Emitted after object has been plotted.
  138. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  139. object_plotted = QtCore.pyqtSignal(object)
  140. # Emitted when a new object has been added or deleted from/to the collection
  141. object_status_changed = QtCore.pyqtSignal(object, str)
  142. message = QtCore.pyqtSignal(str, str, str)
  143. # Emmited when shell command is finished(one command only)
  144. shell_command_finished = QtCore.pyqtSignal(object)
  145. # Emitted when multiprocess pool has been recreated
  146. pool_recreated = QtCore.pyqtSignal(object)
  147. # Emitted when an unhandled exception happens
  148. # in the worker task.
  149. thread_exception = QtCore.pyqtSignal(object)
  150. # used to signal that there are arguments for the app
  151. args_at_startup = QtCore.pyqtSignal(list)
  152. # a reusable signal to replot a list of objects
  153. # should be disconnected after use so it can be reused
  154. replot_signal = pyqtSignal(list)
  155. def __init__(self, user_defaults=True, post_gui=None):
  156. """
  157. Starts the application.
  158. :return: app
  159. :rtype: App
  160. """
  161. App.log.info("FlatCAM Starting...")
  162. self.main_thread = QtWidgets.QApplication.instance().thread()
  163. # ############################################################################
  164. # # ################# OS-specific ############################################
  165. # ############################################################################
  166. portable = False
  167. # Folder for user settings.
  168. if sys.platform == 'win32':
  169. # #########################################################################
  170. # Setup the listening thread for another instance launching with args #####
  171. # #########################################################################
  172. # make sure the thread is stored by using a self. otherwise it's garbage collected
  173. self.th = QtCore.QThread()
  174. self.th.start(priority=QtCore.QThread.LowestPriority)
  175. self.new_launch = ArgsThread()
  176. self.new_launch.open_signal[list].connect(self.on_startup_args)
  177. self.new_launch.moveToThread(self.th)
  178. self.new_launch.start.emit()
  179. from win32com.shell import shell, shellcon
  180. if platform.architecture()[0] == '32bit':
  181. App.log.debug("Win32!")
  182. else:
  183. App.log.debug("Win64!")
  184. # #########################################################################
  185. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  186. # #########################################################################
  187. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  188. try:
  189. with open(config_file, 'r') as f:
  190. try:
  191. for line in f:
  192. param = str(line).rpartition('=')
  193. if param[0] == 'portable':
  194. try:
  195. portable = eval(param[2])
  196. except NameError:
  197. portable = False
  198. except Exception as e:
  199. log.debug('App.__init__() -->%s' % str(e))
  200. return
  201. except FileNotFoundError:
  202. pass
  203. if portable is False:
  204. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  205. else:
  206. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  207. self.os = 'windows'
  208. else: # Linux/Unix/MacOS
  209. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  210. self.os = 'unix'
  211. # ##########################################################################
  212. # ################## Setup folders and files ###############################
  213. # ##########################################################################
  214. if not os.path.exists(self.data_path):
  215. os.makedirs(self.data_path)
  216. App.log.debug('Created data folder: ' + self.data_path)
  217. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  218. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  219. self.postprocessorpaths = os.path.join(self.data_path, 'postprocessors')
  220. if not os.path.exists(self.postprocessorpaths):
  221. os.makedirs(self.postprocessorpaths)
  222. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  223. # create current_defaults.FlatConfig file if there is none
  224. try:
  225. f = open(self.data_path + '/current_defaults.FlatConfig')
  226. f.close()
  227. except IOError:
  228. App.log.debug('Creating empty current_defaults.FlatConfig')
  229. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  230. json.dump({}, f)
  231. f.close()
  232. # create factory_defaults.FlatConfig file if there is none
  233. try:
  234. f = open(self.data_path + '/factory_defaults.FlatConfig')
  235. f.close()
  236. except IOError:
  237. App.log.debug('Creating empty factory_defaults.FlatConfig')
  238. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  239. json.dump({}, f)
  240. f.close()
  241. try:
  242. f = open(self.data_path + '/recent.json')
  243. f.close()
  244. except IOError:
  245. App.log.debug('Creating empty recent.json')
  246. f = open(self.data_path + '/recent.json', 'w')
  247. json.dump([], f)
  248. f.close()
  249. try:
  250. fp = open(self.data_path + '/recent_projects.json')
  251. fp.close()
  252. except IOError:
  253. App.log.debug('Creating empty recent_projects.json')
  254. fp = open(self.data_path + '/recent_projects.json', 'w')
  255. json.dump([], fp)
  256. fp.close()
  257. # Application directory. CHDIR to it. Otherwise, trying to load
  258. # GUI icons will fail as their path is relative.
  259. # This will fail under cx_freeze ...
  260. self.app_home = os.path.dirname(os.path.realpath(__file__))
  261. App.log.debug("Application path is " + self.app_home)
  262. App.log.debug("Started in " + os.getcwd())
  263. # cx_freeze workaround
  264. if os.path.isfile(self.app_home):
  265. self.app_home = os.path.dirname(self.app_home)
  266. os.chdir(self.app_home)
  267. # #############################################################################
  268. # ##################### CREATE MULTIPROCESSING POOL ###########################
  269. # #############################################################################
  270. self.pool = Pool()
  271. # #############################################################################
  272. # ##################### Initialize GUI ########################################
  273. # #############################################################################
  274. # FlatCAM colors used in plotting
  275. self.FC_light_green = '#BBF268BF'
  276. self.FC_dark_green = '#006E20BF'
  277. self.FC_light_blue = '#a5a5ffbf'
  278. self.FC_dark_blue = '#0000ffbf'
  279. QtCore.QObject.__init__(self)
  280. self.ui = FlatCAMGUI(self.version, self.beta, self)
  281. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  282. self.ui.final_save.connect(self.final_save)
  283. # #############################################################################
  284. # ############################## Data #########################################
  285. # #############################################################################
  286. self.recent = []
  287. self.recent_projects = []
  288. self.clipboard = QtWidgets.QApplication.clipboard()
  289. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  290. self.project_filename = None
  291. self.toggle_units_ignore = False
  292. # self.defaults_form = PreferencesUI()
  293. # when adding entries here read the comments in the method found bellow named:
  294. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  295. self.defaults_form_fields = {
  296. # General App
  297. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  298. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  299. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  300. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  301. "global_shell_at_startup": self.ui.general_defaults_form.general_app_group.shell_startup_cb,
  302. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  303. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  304. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  305. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  306. "global_project_at_startup": self.ui.general_defaults_form.general_app_group.project_startup_cb,
  307. "global_project_autohide": self.ui.general_defaults_form.general_app_group.project_autohide_cb,
  308. "global_toggle_tooltips": self.ui.general_defaults_form.general_app_group.toggle_tooltips_cb,
  309. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  310. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  311. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  312. "global_delete_confirmation": self.ui.general_defaults_form.general_app_group.delete_conf_cb,
  313. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  314. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  315. # General GUI Preferences
  316. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  317. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  318. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  319. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  320. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  321. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  322. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  323. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  324. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  325. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  326. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  327. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  328. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  329. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  330. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  331. # General GUI Settings
  332. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  333. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  334. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  335. # Gerber General
  336. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  337. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  338. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  339. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  340. "gerber_buffering": self.ui.gerber_defaults_form.gerber_gen_group.buffering_radio,
  341. # Gerber Options
  342. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  343. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  344. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  345. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  346. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  347. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  348. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  349. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  350. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  351. # Gerber Advanced Options
  352. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  353. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  354. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  355. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  356. # Gerber Export
  357. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  358. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  359. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  360. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  361. # Gerber Editor
  362. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  363. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  364. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  365. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  366. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  367. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  368. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  369. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  370. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  371. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  372. "gerber_editor_circ_angle":
  373. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  374. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  375. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  376. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  377. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  378. # Excellon General
  379. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  380. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  381. "excellon_format_upper_in":
  382. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  383. "excellon_format_lower_in":
  384. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  385. "excellon_format_upper_mm":
  386. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  387. "excellon_format_lower_mm":
  388. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  389. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  390. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  391. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  392. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  393. # Excellon Options
  394. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  395. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  396. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  397. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  398. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_opt_group.spindledir_radio,
  399. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  400. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  401. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  402. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  403. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  404. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  405. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  406. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  407. # Excellon Advanced Options
  408. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  409. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  410. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  411. "excellon_endz": self.ui.excellon_defaults_form.excellon_adv_opt_group.eendz_entry,
  412. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  413. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  414. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  415. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  416. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  417. # Excellon Export
  418. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  419. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  420. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  421. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  422. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  423. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  424. # Excellon Editor
  425. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  426. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  427. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  428. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  429. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  430. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  431. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  432. "excellon_editor_circ_angle":
  433. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  434. # Excellon Slots
  435. "excellon_editor_slot_direction":
  436. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  437. "excellon_editor_slot_angle":
  438. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  439. "excellon_editor_slot_length":
  440. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  441. # Excellon Slots
  442. "excellon_editor_slot_array_size":
  443. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  444. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  445. "excellon_editor_slot_lin_pitch":
  446. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  447. "excellon_editor_slot_lin_angle":
  448. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  449. "excellon_editor_slot_circ_dir":
  450. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  451. "excellon_editor_slot_circ_angle":
  452. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  453. # Geometry General
  454. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  455. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  456. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  457. # Geometry Options
  458. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  459. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  460. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  461. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  462. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  463. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_opt_group.spindledir_radio,
  464. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  465. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  466. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  467. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  468. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  469. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  470. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  471. # Geometry Advanced Options
  472. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  473. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  474. "geometry_endz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gendz_entry,
  475. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  476. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  477. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  478. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  479. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  480. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  481. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  482. # Geometry Editor
  483. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  484. # CNCJob General
  485. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  486. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  487. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  488. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontsize_sp,
  489. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry,
  490. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  491. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  492. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  493. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  494. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  495. # CNC Job Options
  496. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  497. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  498. # CNC Job Advanced Options
  499. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  500. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  501. # NCC Tool
  502. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  503. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  504. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  505. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  506. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  507. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  508. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  509. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  510. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  511. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  512. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  513. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  514. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  515. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  516. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  517. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  518. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  519. # CutOut Tool
  520. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  521. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  522. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  523. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  524. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  525. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  526. # Paint Area Tool
  527. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  528. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  529. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  530. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  531. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  532. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  533. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  534. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  535. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  536. # 2-sided Tool
  537. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  538. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  539. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  540. # Film Tool
  541. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  542. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  543. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  544. # Panelize Tool
  545. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  546. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  547. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  548. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  549. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  550. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  551. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  552. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  553. # Calculators Tool
  554. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  555. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  556. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  557. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  558. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  559. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  560. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  561. # Transformations Tool
  562. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  563. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  564. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  565. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  566. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  567. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  568. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  569. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  570. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  571. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  572. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  573. # SolderPaste Dispensing Tool
  574. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  575. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  576. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  577. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  578. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  579. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  580. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  581. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  582. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  583. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  584. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  585. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  586. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  587. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  588. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  589. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  590. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  591. # file associations
  592. "fa_excellon": self.ui.fa_defaults_form.fa_excellon_group.exc_list_text,
  593. "fa_gcode": self.ui.fa_defaults_form.fa_gcode_group.gco_list_text,
  594. # "fa_geometry": self.ui.fa_defaults_form.fa_geometry_group.close_paths_cb,
  595. "fa_gerber": self.ui.fa_defaults_form.fa_gerber_group.grb_list_text,
  596. }
  597. # ############################
  598. # ### LOAD POSTPROCESSORS ####
  599. # ############################
  600. self.postprocessors = load_postprocessors(self)
  601. for name in list(self.postprocessors.keys()):
  602. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  603. if name.partition('_')[0] == 'Paste':
  604. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  605. continue
  606. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  607. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  608. if name == 'hpgl':
  609. continue
  610. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  611. # ############################
  612. # ### LOAD LANGUAGES ####
  613. # ############################
  614. self.languages = fcTranslate.load_languages()
  615. for name in sorted(self.languages.values()):
  616. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  617. self.defaults = LoudDict()
  618. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  619. self.defaults.update({
  620. # Global APP Preferences
  621. "first_run": True,
  622. "units": "IN",
  623. "global_serial": 0,
  624. "global_stats": {},
  625. "global_tabs_detachable": True,
  626. "global_app_level": 'b',
  627. "global_portable": False,
  628. "global_language": 'English',
  629. "global_version_check": True,
  630. "global_send_stats": True,
  631. "global_pan_button": '2',
  632. "global_mselect_key": 'Control',
  633. "global_project_at_startup": False,
  634. "global_project_autohide": True,
  635. "global_toggle_tooltips": True,
  636. "global_worker_number": 2,
  637. "global_tolerance": 0.01,
  638. "global_open_style": True,
  639. "global_delete_confirmation": True,
  640. "global_compression_level": 3,
  641. "global_save_compressed": True,
  642. # Global GUI Preferences
  643. "global_gridx": 0.0393701,
  644. "global_gridy": 0.0393701,
  645. "global_snap_max": 0.001968504,
  646. "global_workspace": False,
  647. "global_workspaceT": "A4P",
  648. "global_grid_context_menu": {
  649. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  650. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  651. },
  652. "global_plot_fill": '#BBF268BF',
  653. "global_plot_line": '#006E20BF',
  654. "global_sel_fill": '#a5a5ffbf',
  655. "global_sel_line": '#0000ffbf',
  656. "global_alt_sel_fill": '#BBF268BF',
  657. "global_alt_sel_line": '#006E20BF',
  658. "global_draw_color": '#FF0000',
  659. "global_sel_draw_color": '#0000FF',
  660. "global_proj_item_color": '#000000',
  661. "global_proj_item_dis_color": '#b7b7cb',
  662. "global_toolbar_view": 511,
  663. "global_background_timeout": 300000, # Default value is 5 minutes
  664. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  665. # (python trace only for unknown errors),
  666. # 1 = show trace(show trace always),
  667. # 2 = (For the future).
  668. # Persistence
  669. "global_last_folder": None,
  670. "global_last_save_folder": None,
  671. # Default window geometry
  672. "global_def_win_x": 100,
  673. "global_def_win_y": 100,
  674. "global_def_win_w": 1024,
  675. "global_def_win_h": 650,
  676. "global_def_notebook_width": 1,
  677. # Constants...
  678. "global_defaults_save_period_ms": 20000, # Time between default saves.
  679. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  680. "global_shell_at_startup": False, # Show the shell at startup.
  681. "global_recent_limit": 10, # Max. items in recent list.
  682. "fit_key": 'V',
  683. "zoom_out_key": '-',
  684. "zoom_in_key": '=',
  685. "grid_toggle_key": 'G',
  686. "global_zoom_ratio": 1.5,
  687. "global_point_clipboard_format": "(%.4f, %.4f)",
  688. "global_zdownrate": None,
  689. # General GUI Settings
  690. "global_hover": False,
  691. "global_selection_shape": True,
  692. "global_layout": "compact",
  693. # Gerber General
  694. "gerber_plot": True,
  695. "gerber_solid": True,
  696. "gerber_multicolored": False,
  697. "gerber_circle_steps": 128,
  698. "gerber_use_buffer_for_union": True,
  699. "gerber_buffering": "full",
  700. # Gerber Options
  701. "gerber_isotooldia": 0.00787402,
  702. "gerber_isopasses": 1,
  703. "gerber_isooverlap": 0.00393701,
  704. "gerber_milling_type": "cl",
  705. "gerber_combine_passes": False,
  706. "gerber_noncoppermargin": 0.00393701,
  707. "gerber_noncopperrounded": False,
  708. "gerber_bboxmargin": 0.00393701,
  709. "gerber_bboxrounded": False,
  710. # Gerber Advanced Options
  711. "gerber_aperture_display": False,
  712. "gerber_aperture_scale_factor": 1.0,
  713. "gerber_aperture_buffer_factor": 0.0,
  714. "gerber_follow": False,
  715. # Gerber Export
  716. "gerber_exp_units": 'IN',
  717. "gerber_exp_integer": 2,
  718. "gerber_exp_decimals": 4,
  719. "gerber_exp_zeros": 'L',
  720. # Gerber Editor
  721. "gerber_editor_sel_limit": 30,
  722. "gerber_editor_newcode": 10,
  723. "gerber_editor_newsize": 0.8,
  724. "gerber_editor_newtype": 'C',
  725. "gerber_editor_newdim": "0.5, 0.5",
  726. "gerber_editor_array_size": 5,
  727. "gerber_editor_lin_axis": 'X',
  728. "gerber_editor_lin_pitch": 1,
  729. "gerber_editor_lin_angle": 0.0,
  730. "gerber_editor_circ_dir": 'CW',
  731. "gerber_editor_circ_angle": 0.0,
  732. "gerber_editor_scale_f": 1.0,
  733. "gerber_editor_buff_f": 0.1,
  734. "gerber_editor_ma_low": 0.0,
  735. "gerber_editor_ma_high": 1.0,
  736. # Excellon General
  737. "excellon_plot": True,
  738. "excellon_solid": True,
  739. "excellon_format_upper_in": 2,
  740. "excellon_format_lower_in": 4,
  741. "excellon_format_upper_mm": 3,
  742. "excellon_format_lower_mm": 3,
  743. "excellon_zeros": "L",
  744. "excellon_units": "INCH",
  745. "excellon_optimization_type": 'B',
  746. "excellon_search_time": 3,
  747. # Excellon Options
  748. "excellon_drillz": -0.0590551,
  749. "excellon_travelz": 0.0787402,
  750. "excellon_feedrate": 3.14961,
  751. "excellon_spindlespeed": None,
  752. "excellon_spindledir": 'CW',
  753. "excellon_dwell": False,
  754. "excellon_dwelltime": 1,
  755. "excellon_toolchange": False,
  756. "excellon_toolchangez": 0.5,
  757. "excellon_ppname_e": 'default',
  758. "excellon_tooldia": 0.0314961,
  759. "excellon_slot_tooldia": 0.0708661,
  760. "excellon_gcode_type": "drills",
  761. # Excellon Advanced Options
  762. "excellon_offset": 0.0,
  763. "excellon_toolchangexy": "0.0, 0.0",
  764. "excellon_startz": None,
  765. "excellon_endz": 0.5,
  766. "excellon_feedrate_rapid": 31.4961,
  767. "excellon_z_pdepth": -0.02,
  768. "excellon_feedrate_probe": 3.14961,
  769. "excellon_f_plunge": False,
  770. "excellon_f_retract": False,
  771. # Excellon Export
  772. "excellon_exp_units": 'INCH',
  773. "excellon_exp_format": 'ndec',
  774. "excellon_exp_integer": 2,
  775. "excellon_exp_decimals": 4,
  776. "excellon_exp_zeros": 'LZ',
  777. "excellon_exp_slot_type": 'routing',
  778. # Excellon Editor
  779. "excellon_editor_sel_limit": 30,
  780. "excellon_editor_newdia": 0.039,
  781. "excellon_editor_array_size": 5,
  782. "excellon_editor_lin_dir": 'X',
  783. "excellon_editor_lin_pitch": 0.1,
  784. "excellon_editor_lin_angle": 0.0,
  785. "excellon_editor_circ_dir": 'CW',
  786. "excellon_editor_circ_angle": 12,
  787. # Excellon Slots
  788. "excellon_editor_slot_direction": 'X',
  789. "excellon_editor_slot_angle": 0.0,
  790. "excellon_editor_slot_length": 5.0,
  791. # Excellon Slot Array
  792. "excellon_editor_slot_array_size": 5,
  793. "excellon_editor_slot_lin_dir": 'X',
  794. "excellon_editor_slot_lin_pitch": 0.1,
  795. "excellon_editor_slot_lin_angle": 0.0,
  796. "excellon_editor_slot_circ_dir": 'CW',
  797. "excellon_editor_slot_circ_angle": 0.0,
  798. # Geometry General
  799. "geometry_plot": True,
  800. "geometry_circle_steps": 128,
  801. "geometry_cnctooldia": "0.0944882",
  802. # Geometry Options
  803. "geometry_cutz": -0.0944882,
  804. "geometry_vtipdia": 0.1,
  805. "geometry_vtipangle": 30,
  806. "geometry_multidepth": False,
  807. "geometry_depthperpass": 0.0314961,
  808. "geometry_travelz": 0.0787402,
  809. "geometry_toolchange": False,
  810. "geometry_toolchangez": 0.5,
  811. "geometry_feedrate": 3.14961,
  812. "geometry_feedrate_z": 3.14961,
  813. "geometry_spindlespeed": None,
  814. "geometry_spindledir": 'CW',
  815. "geometry_dwell": False,
  816. "geometry_dwelltime": 1,
  817. "geometry_ppname_g": 'default',
  818. # Geometry Advanced Options
  819. "geometry_toolchangexy": "0.0, 0.0",
  820. "geometry_startz": None,
  821. "geometry_endz": 0.5,
  822. "geometry_feedrate_rapid": 3.14961,
  823. "geometry_extracut": False,
  824. "geometry_z_pdepth": -0.02,
  825. "geometry_f_plunge": False,
  826. "geometry_feedrate_probe": 3.14961,
  827. "geometry_segx": 0.0,
  828. "geometry_segy": 0.0,
  829. # Geometry Editor
  830. "geometry_editor_sel_limit": 30,
  831. # CNC Job General
  832. "cncjob_plot": True,
  833. "cncjob_plot_kind": 'all',
  834. "cncjob_annotation": True,
  835. "cncjob_annotation_fontsize": 9,
  836. "cncjob_annotation_fontcolor": '#990000',
  837. "cncjob_tooldia": 0.0393701,
  838. "cncjob_coords_type": "G90",
  839. "cncjob_coords_decimals": 4,
  840. "cncjob_fr_decimals": 2,
  841. "cncjob_steps_per_circle": 128,
  842. # CNC Job Options
  843. "cncjob_prepend": "",
  844. "cncjob_append": "",
  845. # CNC Job Advanced Options
  846. "cncjob_toolchange_macro": "",
  847. "cncjob_toolchange_macro_enable": False,
  848. "tools_ncctools": "0.0393701, 0.019685",
  849. "tools_nccorder": 'rev',
  850. "tools_nccoverlap": 0.015748,
  851. "tools_nccmargin": 0.0393701,
  852. "tools_nccmethod": "seed",
  853. "tools_nccconnect": True,
  854. "tools_ncccontour": True,
  855. "tools_nccrest": False,
  856. "tools_ncc_offset_choice": False,
  857. "tools_ncc_offset_value": 0.0000,
  858. "tools_nccref": 'itself',
  859. "tools_ncc_plotting": 'normal',
  860. "tools_nccmilling_type": 'cl',
  861. "tools_ncctool_type": 'V',
  862. "tools_ncccutz": -0.001968504,
  863. "tools_ncctipdia": 0.00393701,
  864. "tools_ncctipangle": 30,
  865. "tools_cutouttooldia": 0.0944882,
  866. "tools_cutoutkind": "single",
  867. "tools_cutoutmargin": 0.00393701,
  868. "tools_cutoutgapsize": 0.15748,
  869. "tools_gaps_ff": "4",
  870. "tools_cutout_convexshape": False,
  871. "tools_painttooldia": 0.023622,
  872. "tools_paintorder": 'rev',
  873. "tools_paintoverlap": 0.015748,
  874. "tools_paintmargin": 0.0,
  875. "tools_paintmethod": "seed",
  876. "tools_selectmethod": "single",
  877. "tools_pathconnect": True,
  878. "tools_paintcontour": True,
  879. "tools_paint_plotting": 'normal',
  880. "tools_2sided_mirror_axis": "X",
  881. "tools_2sided_axis_loc": "point",
  882. "tools_2sided_drilldia": 0.0393701,
  883. "tools_film_type": 'neg',
  884. "tools_film_boundary": 0.0393701,
  885. "tools_film_scale": 0,
  886. "tools_panelize_spacing_columns": 0,
  887. "tools_panelize_spacing_rows": 0,
  888. "tools_panelize_columns": 1,
  889. "tools_panelize_rows": 1,
  890. "tools_panelize_constrain": False,
  891. "tools_panelize_constrainx": 0.0,
  892. "tools_panelize_constrainy": 0.0,
  893. "tools_panelize_panel_type": 'gerber',
  894. "tools_calc_vshape_tip_dia": 0.007874,
  895. "tools_calc_vshape_tip_angle": 30,
  896. "tools_calc_vshape_cut_z": 0.000787,
  897. "tools_calc_electro_length": 10.0,
  898. "tools_calc_electro_width": 10.0,
  899. "tools_calc_electro_cdensity": 13.0,
  900. "tools_calc_electro_growth": 10.0,
  901. "tools_transform_rotate": 90,
  902. "tools_transform_skew_x": 0.0,
  903. "tools_transform_skew_y": 0.0,
  904. "tools_transform_scale_x": 1.0,
  905. "tools_transform_scale_y": 1.0,
  906. "tools_transform_scale_link": True,
  907. "tools_transform_scale_reference": True,
  908. "tools_transform_offset_x": 0.0,
  909. "tools_transform_offset_y": 0.0,
  910. "tools_transform_mirror_reference": False,
  911. "tools_transform_mirror_point": (0, 0),
  912. "tools_solderpaste_tools": "0.0393701, 0.011811",
  913. "tools_solderpaste_new": 0.011811,
  914. "tools_solderpaste_z_start": 0.00019685039,
  915. "tools_solderpaste_z_dispense": 0.00393701,
  916. "tools_solderpaste_z_stop": 0.00019685039,
  917. "tools_solderpaste_z_travel": 0.00393701,
  918. "tools_solderpaste_z_toolchange": 0.0393701,
  919. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  920. "tools_solderpaste_frxy": 3.0,
  921. "tools_solderpaste_frz": 3.0,
  922. "tools_solderpaste_frz_dispense": 0.0393701,
  923. "tools_solderpaste_speedfwd": 20,
  924. "tools_solderpaste_dwellfwd": 1,
  925. "tools_solderpaste_speedrev": 10,
  926. "tools_solderpaste_dwellrev": 1,
  927. "tools_solderpaste_pp": 'Paste_1',
  928. "tools_sub_close_paths": True,
  929. # file associations
  930. "fa_excellon": ".drl, .xln, .drd, .tap, .exc, .ncd",
  931. "fa_gcode": ".nc, .ncc, .tap, .gcode, .cnc, .ecs, .fnc, .dnc, .ncg, .gc, .fan, .fgc, .din, .xpi,"
  932. " .hnc, .h, .i, .ncp, .min, .gcd, .rol, .mpr, .ply, .out, .eia, .plt, .sbp, .mpf",
  933. "fa_gerber": ".gbr, .ger, .gtl, .gbl, .gts, .gbs, .gtp, .gbp, .gto, .gbo, .gm1, .gml, .gm3, .gko, .cmp, "
  934. ".sol, .stc, .sts, .plc, .pls, .crc, .crs, .tsm, .bsm, .ly2, .ly15, .dim, .mil, .grb, .top, "
  935. ".bot, .smt, .smb, .sst, .ssb, .spt, .spb, .pho, .gdo, .art, .gbd",
  936. })
  937. # ############################################################
  938. # ############### Load defaults from file ####################
  939. # ############################################################
  940. if user_defaults:
  941. self.load_defaults(filename='current_defaults')
  942. # #############################################################
  943. # ############## APPLY APP LANGUAGE ###########################
  944. # #############################################################
  945. ret_val = fcTranslate.apply_language('strings')
  946. if ret_val == "no language":
  947. self.inform.emit('[ERROR] %s' %
  948. _("Could not find the Language files. The App strings are missing."))
  949. log.debug("Could not find the Language files. The App strings are missing.")
  950. else:
  951. # make the current language the current selection on the language combobox
  952. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  953. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  954. # ##############################################################
  955. # ################# CREATE UNIQUE SERIAL NUMBER ################
  956. # ##############################################################
  957. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  958. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  959. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  960. self.save_defaults(silent=True)
  961. self.propagate_defaults(silent=True)
  962. self.restore_main_win_geom()
  963. def auto_save_defaults():
  964. try:
  965. self.save_defaults(silent=True)
  966. self.propagate_defaults(silent=True)
  967. finally:
  968. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  969. # the following lines activates automatic defaults save
  970. # if user_defaults:
  971. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  972. # self.options_form = PreferencesUI()
  973. self.options_form_fields = {
  974. "units": self.ui.general_options_form.general_app_group.units_radio,
  975. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  976. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  977. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  978. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  979. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  980. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  981. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  982. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  983. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  984. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  985. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  986. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  987. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  988. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  989. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  990. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  991. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  992. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  993. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  994. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  995. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  996. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  997. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  998. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  999. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  1000. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  1001. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  1002. "excellon_spindledir": self.ui.excellon_options_form.excellon_opt_group.spindledir_radio,
  1003. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  1004. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  1005. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  1006. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  1007. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  1008. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  1009. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1010. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  1011. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  1012. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  1013. "excellon_endz": self.ui.excellon_options_form.excellon_adv_opt_group.eendz_entry,
  1014. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  1015. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  1016. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  1017. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  1018. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  1019. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  1020. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  1021. "geometry_spindledir": self.ui.geometry_options_form.geometry_opt_group.spindledir_radio,
  1022. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  1023. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  1024. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  1025. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  1026. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  1027. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  1028. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  1029. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  1030. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  1031. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1032. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  1033. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  1034. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  1035. "geometry_endz": self.ui.geometry_options_form.geometry_adv_opt_group.gendz_entry,
  1036. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  1037. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  1038. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  1039. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  1040. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  1041. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  1042. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  1043. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  1044. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  1045. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  1046. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  1047. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  1048. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  1049. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  1050. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  1051. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  1052. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  1053. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  1054. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  1055. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  1056. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  1057. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  1058. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  1059. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  1060. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  1061. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  1062. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  1063. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  1064. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  1065. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  1066. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  1067. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  1068. }
  1069. for name in list(self.postprocessors.keys()):
  1070. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1071. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1072. self.options = LoudDict()
  1073. self.options.set_change_callback(self.on_options_dict_change)
  1074. self.options.update({
  1075. "units": "IN",
  1076. "global_gridx": 1.0,
  1077. "global_gridy": 1.0,
  1078. "global_snap_max": 0.05,
  1079. "global_background_timeout": 300000, # Default value is 5 minutes
  1080. "global_verbose_error_level": 0, # Shell verbosity:
  1081. # 0 = default(python trace only for unknown errors),
  1082. # 1 = show trace(show trace allways), 2 = (For the future).
  1083. "gerber_plot": True,
  1084. "gerber_solid": True,
  1085. "gerber_multicolored": False,
  1086. "gerber_isotooldia": 0.016,
  1087. "gerber_isopasses": 1,
  1088. "gerber_isooverlap": 0.15,
  1089. "gerber_combine_passes": True,
  1090. "gerber_noncoppermargin": 0.0,
  1091. "gerber_noncopperrounded": False,
  1092. "gerber_bboxmargin": 0.0,
  1093. "gerber_bboxrounded": False,
  1094. "excellon_plot": True,
  1095. "excellon_solid": False,
  1096. "excellon_format_upper_in": 2,
  1097. "excellon_format_lower_in": 4,
  1098. "excellon_format_upper_mm": 3,
  1099. "excellon_format_lower_mm": 3,
  1100. "excellon_units": 'INCH',
  1101. "excellon_optimization_type": 'B',
  1102. "excellon_search_time": 3,
  1103. "excellon_zeros": "L",
  1104. "excellon_drillz": -0.1,
  1105. "excellon_travelz": 0.1,
  1106. "excellon_feedrate": 3.0,
  1107. "excellon_feedrate_rapid": 3.0,
  1108. "excellon_spindlespeed": None,
  1109. "excellon_spindledir": 'CW',
  1110. "excellon_dwell": True,
  1111. "excellon_dwelltime": 1000,
  1112. "excellon_toolchange": False,
  1113. "excellon_toolchangez": 1.0,
  1114. "excellon_toolchangexy": "0.0, 0.0",
  1115. "excellon_tooldia": 0.016,
  1116. "excellon_ppname_e": 'default',
  1117. "excellon_f_plunge": False,
  1118. "excellon_startz": None,
  1119. "excellon_endz": 2.0,
  1120. "geometry_plot": True,
  1121. "geometry_segx": 0.0,
  1122. "geometry_segy": 0.0,
  1123. "geometry_cutz": -0.002,
  1124. "geometry_vtipdia": 0.1,
  1125. "geometry_vtipangle": 30,
  1126. "geometry_travelz": 0.1,
  1127. "geometry_feedrate": 3.0,
  1128. "geometry_feedrate_z": 3.0,
  1129. "geometry_feedrate_rapid": 3.0,
  1130. "geometry_spindlespeed": None,
  1131. "geometry_spindledir": 'CW',
  1132. "geometry_dwell": True,
  1133. "geometry_dwelltime": 1000,
  1134. "geometry_cnctooldia": 0.016,
  1135. "geometry_toolchange": False,
  1136. "geometry_toolchangez": 2.0,
  1137. "geometry_toolchangexy": "0.0, 0.0",
  1138. "geometry_startz": None,
  1139. "geometry_endz": 2.0,
  1140. "geometry_ppname_g": "default",
  1141. "geometry_f_plunge": False,
  1142. "geometry_depthperpass": 0.002,
  1143. "geometry_multidepth": False,
  1144. "geometry_extracut": False,
  1145. "cncjob_plot": True,
  1146. "cncjob_tooldia": 0.016,
  1147. "cncjob_prepend": "",
  1148. "cncjob_append": "",
  1149. "tools_ncctools": "1.0, 0.5",
  1150. "tools_nccoverlap": 0.4,
  1151. "tools_nccmargin": 1,
  1152. "tools_cutouttooldia": 0.07,
  1153. "tools_cutoutmargin": 0.1,
  1154. "tools_cutoutgapsize": 0.15,
  1155. "tools_gaps_ff": "8",
  1156. "tools_painttooldia": 0.07,
  1157. "tools_paintoverlap": 0.15,
  1158. "tools_paintmargin": 0.0,
  1159. "tools_paintmethod": "seed",
  1160. "tools_selectmethod": "single",
  1161. "tools_pathconnect": True,
  1162. "tools_paintcontour": True,
  1163. "tools_2sided_mirror_axis": "X",
  1164. "tools_2sided_axis_loc": 'point',
  1165. "tools_2sided_drilldia": 1,
  1166. "tools_film_type": 'neg',
  1167. "tools_film_boundary": 1,
  1168. "tools_film_scale": 0,
  1169. "tools_panelize_spacing_columns": 0,
  1170. "tools_panelize_spacing_rows": 0,
  1171. "tools_panelize_columns": 1,
  1172. "tools_panelize_rows": 1,
  1173. "tools_panelize_constrain": False,
  1174. "tools_panelize_constrainx": 0.0,
  1175. "tools_panelize_constrainy": 0.0
  1176. })
  1177. self.options.update(self.defaults) # Copy app defaults to project options
  1178. self.gen_form = None
  1179. self.ger_form = None
  1180. self.exc_form = None
  1181. self.geo_form = None
  1182. self.cnc_form = None
  1183. self.tools_form = None
  1184. self.fa_form = None
  1185. self.on_options_combo_change(0) # Will show the initial form
  1186. # ################################
  1187. # ### Initialize the color box's color in Preferences -> Global -> Color
  1188. # Init Plot Colors
  1189. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  1190. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  1191. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  1192. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  1193. int(self.defaults['global_plot_fill'][7:9], 16))
  1194. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  1195. int(self.defaults['global_plot_fill'][7:9], 16))
  1196. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  1197. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  1198. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  1199. # Init Left-Right Selection colors
  1200. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  1201. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  1202. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  1203. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1204. int(self.defaults['global_sel_fill'][7:9], 16))
  1205. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1206. int(self.defaults['global_sel_fill'][7:9], 16))
  1207. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1208. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1209. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  1210. # Init Right-Left Selection colors
  1211. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1212. self.defaults['global_alt_sel_fill'])
  1213. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1214. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  1215. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1216. int(self.defaults['global_sel_fill'][7:9], 16))
  1217. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1218. int(self.defaults['global_sel_fill'][7:9], 16))
  1219. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1220. self.defaults['global_alt_sel_line'])
  1221. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1222. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  1223. # Init Draw color and Selection Draw Color
  1224. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1225. self.defaults['global_draw_color'])
  1226. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1227. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1228. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1229. self.defaults['global_sel_draw_color'])
  1230. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1231. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1232. # Init Project Items color
  1233. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1234. self.defaults['global_proj_item_color'])
  1235. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1236. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1237. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1238. self.defaults['global_proj_item_dis_color'])
  1239. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1240. "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1241. # Init the Annotation CNC Job color
  1242. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.set_value(
  1243. self.defaults['cncjob_annotation_fontcolor'])
  1244. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  1245. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  1246. # ### End of Data ####
  1247. # ###############################################
  1248. # ############# SETUP Plot Area #################
  1249. # ###############################################
  1250. start_plot_time = time.time() # debug
  1251. self.plotcanvas = None
  1252. self.app_cursor = None
  1253. self.hover_shapes = None
  1254. self.on_plotcanvas_setup()
  1255. end_plot_time = time.time()
  1256. self.log.debug("Finished Canvas initialization in %s seconds." % (str(end_plot_time - start_plot_time)))
  1257. self.ui.splitter.setStretchFactor(1, 2)
  1258. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  1259. # depending on from where those tools are called different actions can be done
  1260. self.call_source = 'app'
  1261. # ##############################################
  1262. # ######### SETUP OBJECT COLLECTION ############
  1263. # ##############################################
  1264. self.collection = ObjectCollection(self)
  1265. self.ui.project_tab_layout.addWidget(self.collection.view)
  1266. # ### Adjust tabs width ## ##
  1267. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1268. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1269. self.collection.view.setMinimumWidth(290)
  1270. self.log.debug("Finished creating Object Collection.")
  1271. # ###############################################
  1272. # ############# Worker SETUP ####################
  1273. # ###############################################
  1274. if self.defaults["global_worker_number"]:
  1275. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1276. else:
  1277. self.workers = WorkerStack(workers_number=2)
  1278. self.worker_task.connect(self.workers.add_task)
  1279. self.log.debug("Finished creating Workers crew.")
  1280. # ################################################
  1281. # ############### Signal handling ################
  1282. # ################################################
  1283. # ############# Custom signals ##################
  1284. # signal for displaying messages in status bar
  1285. self.inform.connect(self.info)
  1286. # signal to be called when the app is quiting
  1287. self.app_quit.connect(self.quit_application)
  1288. self.message.connect(self.message_dialog)
  1289. self.progress.connect(self.set_progress_bar)
  1290. # signals that are emitted when object state changes
  1291. self.object_created.connect(self.on_object_created)
  1292. self.object_changed.connect(self.on_object_changed)
  1293. self.object_plotted.connect(self.on_object_plotted)
  1294. self.plots_updated.connect(self.on_plots_updated)
  1295. # signals emitted when file state change
  1296. self.file_opened.connect(self.register_recent)
  1297. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1298. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1299. # ############# Standard signals ###################
  1300. # ### Menu
  1301. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1302. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1303. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1304. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1305. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1306. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1307. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1308. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1309. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1310. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1311. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1312. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1313. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1314. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1315. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1316. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1317. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1318. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1319. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1320. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1321. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1322. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1323. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1324. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1325. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1326. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1327. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1328. self.ui.menufile_exit.triggered.connect(self.final_save)
  1329. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1330. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1331. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1332. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1333. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1334. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1335. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1336. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1337. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1338. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1339. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1340. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1341. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1342. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1343. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1344. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1345. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1346. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1347. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1348. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1349. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1350. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1351. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1352. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1353. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1354. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1355. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1356. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1357. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1358. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1359. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1360. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1361. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1362. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1363. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1364. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1365. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1366. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1367. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1368. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1369. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1370. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1371. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1372. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1373. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1374. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1375. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1376. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1377. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1378. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1379. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1380. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1381. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1382. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1383. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1384. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1385. # ToolBar signals
  1386. self.connect_toolbar_signals()
  1387. # Notebook signals
  1388. # make the right click on the notebook tab connect to a function
  1389. self.ui.notebook.setupContextMenu()
  1390. self.ui.notebook.addContextMenu(
  1391. _("Detachable Tabs"), self.on_notebook_tab_rmb_click,
  1392. initial_checked=self.defaults["global_tabs_detachable"])
  1393. # activate initial state
  1394. self.on_notebook_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1395. # Context Menu
  1396. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1397. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1398. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1399. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1400. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1401. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1402. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1403. self.ui.clearplot.triggered.connect(self.clear_plots)
  1404. self.ui.replot.triggered.connect(self.plot_all)
  1405. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1406. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1407. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1408. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1409. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1410. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1411. # Preferences Plot Area TAB
  1412. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1413. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1414. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1415. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1416. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1417. # ##############################
  1418. # ### GUI PREFERENCES SIGNALS ##
  1419. # ##############################
  1420. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1421. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1422. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1423. )
  1424. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1425. lambda: self.on_toggle_units(no_pref=False))
  1426. # ###############################################################
  1427. # ################### GUI COLORS SIGNALS ########################
  1428. # ###############################################################
  1429. # Setting plot colors signals
  1430. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1431. self.on_pf_color_entry)
  1432. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1433. self.on_pf_color_button)
  1434. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1435. self.on_pf_color_spinner)
  1436. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1437. self.on_pf_color_slider)
  1438. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1439. self.on_pl_color_entry)
  1440. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1441. self.on_pl_color_button)
  1442. # Setting selection (left - right) colors signals
  1443. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1444. self.on_sf_color_entry)
  1445. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1446. self.on_sf_color_button)
  1447. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1448. self.on_sf_color_spinner)
  1449. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1450. self.on_sf_color_slider)
  1451. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1452. self.on_sl_color_entry)
  1453. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1454. self.on_sl_color_button)
  1455. # Setting selection (right - left) colors signals
  1456. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1457. self.on_alt_sf_color_entry)
  1458. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1459. self.on_alt_sf_color_button)
  1460. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1461. self.on_alt_sf_color_spinner)
  1462. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1463. self.on_alt_sf_color_slider)
  1464. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1465. self.on_alt_sl_color_entry)
  1466. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1467. self.on_alt_sl_color_button)
  1468. # Setting Editor Draw colors signals
  1469. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1470. self.on_draw_color_entry)
  1471. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1472. self.on_draw_color_button)
  1473. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1474. self.on_sel_draw_color_entry)
  1475. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1476. self.on_sel_draw_color_button)
  1477. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1478. self.on_proj_color_entry)
  1479. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1480. self.on_proj_color_button)
  1481. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1482. self.on_proj_color_dis_entry)
  1483. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1484. self.on_proj_color_dis_button)
  1485. # ########## workspace setting signals ###########
  1486. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1487. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1488. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1489. # ########## CNC Job related signals #############
  1490. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1491. self.on_cnc_custom_parameters)
  1492. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.editingFinished.connect(
  1493. self.on_annotation_fontcolor_entry)
  1494. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.clicked.connect(
  1495. self.on_annotation_fontcolor_button)
  1496. # ########## Modify G-CODE Plot Area TAB ###########
  1497. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1498. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1499. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1500. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1501. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1502. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1503. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1504. # portability changed signal
  1505. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1506. # Object list
  1507. self.collection.view.activated.connect(self.on_row_activated)
  1508. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1509. self.ui.general_defaults_form.general_app_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1510. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1511. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1512. self.on_excellon_defaults_button)
  1513. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1514. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1515. self.on_excellon_options_button)
  1516. # when there are arguments at application startup this get launched
  1517. self.args_at_startup[list].connect(lambda: self.on_startup_args())
  1518. # connect the 'Apply' buttons from the Preferences/File Associations
  1519. self.ui.fa_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1520. lambda: self.on_register_files(obj_type='excellon'))
  1521. self.ui.fa_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1522. lambda: self.on_register_files(obj_type='gcode'))
  1523. self.ui.fa_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1524. lambda: self.on_register_files(obj_type='gerber'))
  1525. # connect the abort_all_tasks related slots to the related signals
  1526. self.proc_container.idle_flag.connect(self.app_is_idle)
  1527. # #####################################################################################
  1528. # ########### FINISHED CONNECTING SIGNALS #############################################
  1529. # #####################################################################################
  1530. self.log.debug("Finished connecting Signals.")
  1531. # #####################################################################################
  1532. # ########################## Other setups #############################################
  1533. # #####################################################################################
  1534. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1535. self.tool_tab_locked = False
  1536. # decide if to show or hide the Notebook side of the screen at startup
  1537. if self.defaults["global_project_at_startup"] is True:
  1538. self.ui.splitter.setSizes([1, 1])
  1539. else:
  1540. self.ui.splitter.setSizes([0, 1])
  1541. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1542. self.setup_obj_classes()
  1543. self.setup_recent_items()
  1544. self.setup_component_editor()
  1545. # #####################################################################################
  1546. # ######################### Auto-complete KEYWORDS ####################################
  1547. # #####################################################################################
  1548. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1549. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1550. 'delete', 'drillcncjob', 'export_gcode', 'export_svg', 'ext', 'exteriors', 'follow',
  1551. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1552. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1553. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1554. 'mirror', 'ncc',
  1555. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1556. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'paint',
  1557. 'pan', 'panel', 'panelize', 'plot', 'save', 'save_project', 'save_sys', 'scale',
  1558. 'set_active', 'set_sys', 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1559. 'version', 'write_gcode'
  1560. ]
  1561. self.ordinary_keywords = ['all', 'angle_x', 'angle_y', 'axis', 'axisoffset', 'box', 'center_x', 'center_y',
  1562. 'columns', 'combine', 'connect', 'contour', 'depthperpass', 'dia', 'diatol', 'dist',
  1563. 'drilled_dias', 'drillz',
  1564. 'endz', 'extracut', 'factor', 'False', 'false', 'feedrate', 'feedrate_rapid',
  1565. 'filename', 'follow', 'gaps', 'gapsize', 'grid', 'gridoffset', 'gridoffsetx',
  1566. 'gridoffsety', 'gridx', 'gridy', 'has_offset', 'holes', 'margin', 'method',
  1567. 'milled_dias',
  1568. 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order', 'outname',
  1569. 'overlap', 'passes', 'postamble', 'ppname_e', 'ppname_g', 'preamble', 'radius', 'ref',
  1570. 'rest', 'rows', 'scale_factor', 'spacing_columns', 'spacing_rows', 'spindlespeed',
  1571. 'toolchange', 'toolchangez', 'tooldia', 'tools', 'travelz', 'True', 'true', 'type',
  1572. 'use_threads', 'value', 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1573. ]
  1574. self.tcl_keywords = [
  1575. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1576. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1577. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1578. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1579. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1580. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1581. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1582. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1583. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1584. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1585. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1586. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1587. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1588. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1589. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1590. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1591. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1592. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1593. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1594. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1595. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1596. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1597. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1598. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1599. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1600. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1601. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1602. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1603. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1604. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1605. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1606. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1607. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1608. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1609. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1610. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1611. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1612. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1613. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1614. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1615. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1616. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1617. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1618. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1619. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1620. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1621. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1622. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1623. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1624. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1625. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1626. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1627. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1628. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1629. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1630. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1631. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1632. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1633. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1634. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1635. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1636. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1637. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1638. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1639. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1640. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1641. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1642. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1643. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1644. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1645. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1646. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1647. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1648. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1649. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1650. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1651. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1652. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1653. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1654. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1655. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1656. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1657. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1658. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1659. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1660. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1661. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1662. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1663. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1664. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1665. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1666. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1667. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1668. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1669. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1670. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1671. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1672. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1673. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1674. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1675. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1676. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1677. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1678. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1679. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1680. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1681. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1682. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1683. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1684. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1685. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1686. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1687. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1688. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1689. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1690. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1691. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1692. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1693. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1694. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1695. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1696. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1697. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1698. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1699. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1700. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1701. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1702. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1703. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1704. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1705. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1706. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1707. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1708. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1709. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1710. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1711. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1712. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1713. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1714. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1715. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1716. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1717. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1718. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1719. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1720. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1721. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1722. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1723. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1724. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1725. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1726. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1727. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1728. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1729. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1730. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1731. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1732. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1733. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1734. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1735. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1736. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1737. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1738. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1739. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1740. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1741. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1742. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1743. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1744. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1745. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1746. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1747. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1748. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1749. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1750. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1751. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1752. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1753. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1754. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1755. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1756. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1757. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1758. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1759. ]
  1760. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords + self.tcl_keywords
  1761. # ####################################################################################
  1762. # ####################### Shell SETUP ################################################
  1763. # ####################################################################################
  1764. self.shell = FCShell(self, version=self.version)
  1765. self.shell._edit.set_model_data(self.myKeywords)
  1766. self.ui.code_editor.set_model_data(self.myKeywords)
  1767. self.shell.setWindowIcon(self.ui.app_icon)
  1768. self.shell.setWindowTitle("FlatCAM Shell")
  1769. self.shell.resize(*self.defaults["global_shell_shape"])
  1770. self.shell.append_output("FlatCAM %s - " % self.version)
  1771. self.shell.append_output(_("Open Source Software - Type help to get started\n\n"))
  1772. self.init_tcl()
  1773. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1774. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1775. self.ui.shell_dock.setWidget(self.shell)
  1776. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1777. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1778. QtWidgets.QDockWidget.DockWidgetFloatable |
  1779. QtWidgets.QDockWidget.DockWidgetClosable)
  1780. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1781. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1782. if self.defaults["global_shell_at_startup"]:
  1783. self.ui.shell_dock.show()
  1784. else:
  1785. self.ui.shell_dock.hide()
  1786. # ##################################################################################
  1787. # ###################### Tools and Plugins #########################################
  1788. # ##################################################################################
  1789. self.dblsidedtool = None
  1790. self.measurement_tool = None
  1791. self.panelize_tool = None
  1792. self.film_tool = None
  1793. self.paste_tool = None
  1794. self.calculator_tool = None
  1795. self.sub_tool = None
  1796. self.move_tool = None
  1797. self.cutout_tool = None
  1798. self.ncclear_tool = None
  1799. self.paint_tool = None
  1800. self.transform_tool = None
  1801. self.properties_tool = None
  1802. self.pdf_tool = None
  1803. self.image_tool = None
  1804. self.pcb_wizard_tool = None
  1805. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1806. self.install_tools()
  1807. # ### System Font Parsing ###
  1808. # self.f_parse = ParseFont(self)
  1809. # self.parse_system_fonts()
  1810. # #####################################################################################
  1811. # ########################## START-UP ARGUMENTS #######################################
  1812. # #####################################################################################
  1813. # test if the program was started with a script as parameter
  1814. if self.cmd_line_shellfile:
  1815. try:
  1816. with open(self.cmd_line_shellfile, "r") as myfile:
  1817. cmd_line_shellfile_text = myfile.read()
  1818. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1819. except Exception as ext:
  1820. print("ERROR: ", ext)
  1821. sys.exit(2)
  1822. # #####################################################################################
  1823. # ######################## Check for updates ##########################################
  1824. # #####################################################################################
  1825. # Separate thread (Not worker)
  1826. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1827. if (self.beta is False or self.beta is None) and \
  1828. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1829. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1830. self.thr2 = QtCore.QThread()
  1831. self.worker_task.emit({'fcn': self.version_check,
  1832. 'params': []})
  1833. self.thr2.start(QtCore.QThread.LowPriority)
  1834. # #####################################################################################
  1835. # ###################### Variables for global usage ###################################
  1836. # #####################################################################################
  1837. # register files with FlatCAM; it works only for Windows for now
  1838. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1839. self.on_register_files()
  1840. # coordinates for relative position display
  1841. self.rel_point1 = (0, 0)
  1842. self.rel_point2 = (0, 0)
  1843. # variable to store coordinates
  1844. self.pos = (0, 0)
  1845. self.pos_jump = (0, 0)
  1846. # variable to store mouse coordinates
  1847. self.mouse = [0, 0]
  1848. # decide if we have a double click or single click
  1849. self.doubleclick = False
  1850. # variable to store if a command is active (then the var is not None) and which one it is
  1851. self.command_active = None
  1852. # variable to store the status of moving selection action
  1853. # None value means that it's not an selection action
  1854. # True value = a selection from left to right
  1855. # False value = a selection from right to left
  1856. self.selection_type = None
  1857. # List to store the objects that are currently loaded in FlatCAM
  1858. # This list is updated on each object creation or object delete
  1859. self.all_objects_list = []
  1860. # List to store the objects that are selected
  1861. self.sel_objects_list = []
  1862. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1863. self.key_modifiers = None
  1864. # Variable to hold the status of the axis
  1865. self.toggle_axis = True
  1866. # Variable to store the status of the fullscreen event
  1867. self.toggle_fscreen = False
  1868. # Variable to store the status of the code editor
  1869. self.toggle_codeeditor = False
  1870. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1871. self.click_noproject = False
  1872. self.cursor = None
  1873. # Variable to store the GCODE that was edited
  1874. self.gcode_edited = ""
  1875. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  1876. self.preferences_changed_flag = False
  1877. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3',
  1878. 'gko', 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15',
  1879. 'dim', 'mil', 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo',
  1880. 'art', 'gbd', 'gb0', 'gb1', 'gb2', 'gb3', 'g4', 'gb5', 'gb6', 'gb7', 'gb8', 'gb9'
  1881. ]
  1882. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc', 'ncd']
  1883. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1884. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1885. 'mpf'
  1886. ]
  1887. self.svg_list = ['svg']
  1888. self.dxf_list = ['dxf']
  1889. self.pdf_list = ['pdf']
  1890. self.prj_list = ['flatprj']
  1891. self.conf_list = ['flatconfig']
  1892. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1893. # flag for polygons not cleared
  1894. self.poly_not_cleared = False
  1895. # VisPy visuals
  1896. self.isHovering = False
  1897. self.notHovering = True
  1898. # when True, the app has to return from any thread
  1899. self.abort_flag = False
  1900. # ###############################################################################
  1901. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  1902. # ############# It's done only once after install ###############
  1903. # ###############################################################################
  1904. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1905. fac_def_from_file = factory_file.read()
  1906. factory_defaults = json.loads(fac_def_from_file)
  1907. # if the file contain an empty dictionary then save the factory defaults into the file
  1908. if not factory_defaults:
  1909. self.save_factory_defaults(silent=False)
  1910. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  1911. initial_lay = 'compact'
  1912. self.on_layout(lay=initial_lay)
  1913. # Set the combobox in Preferences to the current layout
  1914. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  1915. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  1916. factory_file.close()
  1917. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1918. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1919. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1920. # after the first run, this object should be False
  1921. self.defaults["first_run"] = False
  1922. # ###############################################################################
  1923. # ################# ADDING FlatCAM EDITORS section ##############################
  1924. # ###############################################################################
  1925. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1926. # at the first launch of the App , the editors will not be functional.
  1927. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  1928. self.exc_editor = FlatCAMExcEditor(self)
  1929. self.grb_editor = FlatCAMGrbEditor(self)
  1930. self.log.debug("Finished adding FlatCAM Editor's.")
  1931. self.set_ui_title(name=_("New Project - Not saved"))
  1932. # ###############################################################################
  1933. # ####################### Finished the CONSTRUCTOR ##############################
  1934. # ###############################################################################
  1935. App.log.debug("END of constructor. Releasing control.")
  1936. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1937. # the path/file_name must be enclosed in quotes if it contain spaces
  1938. if App.args:
  1939. self.args_at_startup.emit(App.args)
  1940. @staticmethod
  1941. def copy_and_overwrite(from_path, to_path):
  1942. """
  1943. From here:
  1944. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1945. :param from_path: source path
  1946. :param to_path: destination path
  1947. :return: None
  1948. """
  1949. if os.path.exists(to_path):
  1950. shutil.rmtree(to_path)
  1951. try:
  1952. shutil.copytree(from_path, to_path)
  1953. except FileNotFoundError:
  1954. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  1955. shutil.copytree(from_new_path, to_path)
  1956. def on_startup_args(self, args=None):
  1957. """
  1958. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1959. :param args: a list containing the application args at startup
  1960. :return: None
  1961. """
  1962. if args:
  1963. args_to_process = args
  1964. else:
  1965. args_to_process = App.args
  1966. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1967. for argument in args_to_process:
  1968. if '.FlatPrj' in argument:
  1969. try:
  1970. project_name = str(argument)
  1971. if project_name == "":
  1972. self.inform.emit(_("Open cancelled."))
  1973. else:
  1974. # self.open_project(project_name)
  1975. run_from_arg = True
  1976. # self.worker_task.emit({'fcn': self.open_project,
  1977. # 'params': [project_name, run_from_arg]})
  1978. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1979. except Exception as e:
  1980. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1981. elif '.FlatConfig' in argument:
  1982. try:
  1983. file_name = str(argument)
  1984. if file_name == "":
  1985. self.inform.emit(_("Open Config file failed."))
  1986. else:
  1987. # run_from_arg = True
  1988. # self.worker_task.emit({'fcn': self.open_config_file,
  1989. # 'params': [file_name, run_from_arg]})
  1990. self.open_config_file(file_name, run_from_arg=True)
  1991. except Exception as e:
  1992. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1993. elif '.FlatScript' in argument:
  1994. try:
  1995. file_name = str(argument)
  1996. if file_name == "":
  1997. self.inform.emit(_("Open Script file failed."))
  1998. else:
  1999. # run_from_arg = True
  2000. # self.worker_task.emit({'fcn': self.open_script_file,
  2001. # 'params': [file_name, run_from_arg]})
  2002. self.on_filerunscript(name=file_name)
  2003. except Exception as e:
  2004. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2005. else:
  2006. exc_list = self.ui.fa_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2007. proc_arg = argument.lower()
  2008. for ext in exc_list:
  2009. proc_ext = ext.replace(' ', '')
  2010. if proc_ext.lower() in proc_arg and proc_ext != '':
  2011. file_name = str(argument)
  2012. if file_name == "":
  2013. self.inform.emit(_("Open Excellon file failed."))
  2014. else:
  2015. self.on_fileopenexcellon(name=file_name)
  2016. return
  2017. gco_list = self.ui.fa_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2018. for ext in gco_list:
  2019. proc_ext = ext.replace(' ', '')
  2020. if proc_ext.lower() in proc_arg and proc_ext != '':
  2021. file_name = str(argument)
  2022. if file_name == "":
  2023. self.inform.emit(_("Open GCode file failed."))
  2024. else:
  2025. self.on_fileopengcode(name=file_name)
  2026. return
  2027. grb_list = self.ui.fa_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2028. for ext in grb_list:
  2029. proc_ext = ext.replace(' ', '')
  2030. if proc_ext.lower() in proc_arg and proc_ext != '':
  2031. file_name = str(argument)
  2032. if file_name == "":
  2033. self.inform.emit(_("Open Gerber file failed."))
  2034. else:
  2035. self.on_fileopengerber(name=file_name)
  2036. return
  2037. def set_ui_title(self, name):
  2038. """
  2039. Sets the title of the main window.
  2040. :param name: String that store the project path and project name
  2041. :return: None
  2042. """
  2043. self.ui.setWindowTitle('FlatCAM %s %s - %s %s' %
  2044. (self.version,
  2045. ('BETA' if self.beta else ''),
  2046. platform.architecture()[0],
  2047. name)
  2048. )
  2049. def defaults_read_form(self):
  2050. """
  2051. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2052. :return: None
  2053. """
  2054. for option in self.defaults_form_fields:
  2055. try:
  2056. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2057. except Exception as e:
  2058. log.debug("App.defaults_read_form() --> %s" % str(e))
  2059. def defaults_write_form(self, factor=None, fl_units=None):
  2060. """
  2061. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2062. self.defaults dictionary.
  2063. :param factor: will apply a factor to the values that written in the GUI elements
  2064. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2065. :return: None
  2066. """
  2067. for option in self.defaults:
  2068. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2069. # try:
  2070. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2071. # except KeyError:
  2072. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2073. # # TODO: Rethink this?
  2074. # pass
  2075. def defaults_write_form_field(self, field, factor=None, units=None):
  2076. """
  2077. Basically it is the worker in the self.defaults_write_form()
  2078. :param field: the GUI element in Preferences GUI to be updated
  2079. :param factor: factor to be applied to the field parameter
  2080. :param units: current FLatCAM measuring units
  2081. :return: None, it updates GUI elements
  2082. """
  2083. try:
  2084. if factor is None:
  2085. if units is None:
  2086. self.defaults_form_fields[field].set_value(self.defaults[field])
  2087. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2088. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=6)
  2089. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2090. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=4)
  2091. else:
  2092. if units is None:
  2093. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2094. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2095. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=6)
  2096. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2097. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=4)
  2098. except KeyError:
  2099. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2100. # TODO: Rethink this?
  2101. pass
  2102. except AttributeError:
  2103. log.debug(field)
  2104. def clear_pool(self):
  2105. """
  2106. Clear the multiprocessing pool and calls garbage collector.
  2107. :return: None
  2108. """
  2109. self.pool.close()
  2110. self.pool = Pool()
  2111. self.pool_recreated.emit(self.pool)
  2112. gc.collect()
  2113. def install_tools(self):
  2114. """
  2115. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2116. Instantiation of the Tools classes.
  2117. The order that the tools are installed is important as they can depend on each other install position.
  2118. :return: None
  2119. """
  2120. self.dblsidedtool = DblSidedTool(self)
  2121. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2122. self.measurement_tool = Measurement(self)
  2123. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  2124. self.panelize_tool = Panelize(self)
  2125. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  2126. self.film_tool = Film(self)
  2127. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2128. self.paste_tool = SolderPaste(self)
  2129. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2130. self.calculator_tool = ToolCalculator(self)
  2131. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'), separator=True)
  2132. self.sub_tool = ToolSub(self)
  2133. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2134. self.move_tool = ToolMove(self)
  2135. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2136. before=self.ui.menueditorigin)
  2137. self.cutout_tool = CutOut(self)
  2138. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2139. before=self.measurement_tool.menuAction)
  2140. self.ncclear_tool = NonCopperClear(self)
  2141. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2142. before=self.measurement_tool.menuAction, separator=True)
  2143. self.paint_tool = ToolPaint(self)
  2144. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2145. before=self.measurement_tool.menuAction, separator=True)
  2146. self.transform_tool = ToolTransform(self)
  2147. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2148. self.properties_tool = Properties(self)
  2149. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2150. self.pdf_tool = ToolPDF(self)
  2151. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2152. separator=True)
  2153. self.image_tool = ToolImage(self)
  2154. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2155. separator=True)
  2156. self.pcb_wizard_tool = PcbWizard(self)
  2157. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2158. self.log.debug("Tools are installed.")
  2159. def remove_tools(self):
  2160. """
  2161. Will remove all the actions in the Tool menu.
  2162. :return: None
  2163. """
  2164. for act in self.ui.menutool.actions():
  2165. self.ui.menutool.removeAction(act)
  2166. def init_tools(self):
  2167. """
  2168. Initialize the Tool tab in the notebook side of the central widget.
  2169. Remove the actions in the Tools menu.
  2170. Instantiate again the FlatCAM tools (plugins).
  2171. All this is required when changing the layout: standard, compact etc.
  2172. :return: None
  2173. """
  2174. log.debug("init_tools()")
  2175. # delete the data currently in the Tools Tab and the Tab itself
  2176. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2177. if widget is not None:
  2178. widget.deleteLater()
  2179. self.ui.notebook.removeTab(2)
  2180. # rebuild the Tools Tab
  2181. self.ui.tool_tab = QtWidgets.QWidget()
  2182. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2183. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2184. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2185. self.ui.tool_scroll_area = VerticalScrollArea()
  2186. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2187. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2188. # first remove all of them
  2189. self.remove_tools()
  2190. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2191. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2192. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2193. # third install all of them
  2194. self.install_tools()
  2195. self.log.debug("Tools are initialized.")
  2196. # def parse_system_fonts(self):
  2197. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2198. # 'params': []})
  2199. def connect_toolbar_signals(self):
  2200. """
  2201. Reconnect the signals to the actions in the toolbar.
  2202. This has to be done each time after the FlatCAM tools are removed/installed.
  2203. :return: None
  2204. """
  2205. # Toolbar
  2206. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2207. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2208. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2209. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2210. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2211. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2212. self.ui.replot_btn.triggered.connect(self.plot_all)
  2213. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2214. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2215. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2216. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2217. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2218. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2219. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2220. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2221. self.ui.delete_btn.triggered.connect(self.on_delete)
  2222. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2223. # Tools Toolbar Signals
  2224. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2225. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2226. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2227. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2228. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2229. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2230. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2231. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2232. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2233. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2234. def object2editor(self):
  2235. """
  2236. Send the current Geometry or Excellon object (if any) into the it's editor.
  2237. :return: None
  2238. """
  2239. self.report_usage("object2editor()")
  2240. edited_object = self.collection.get_active()
  2241. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2242. isinstance(edited_object, FlatCAMExcellon):
  2243. pass
  2244. else:
  2245. self.inform.emit('[WARNING_NOTCL] %s' %
  2246. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2247. return
  2248. if isinstance(edited_object, FlatCAMGeometry):
  2249. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2250. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2251. # we set the notebook to hidden
  2252. self.ui.splitter.setSizes([0, 1])
  2253. if edited_object.multigeo is True:
  2254. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  2255. if len(edited_tools) > 1:
  2256. self.inform.emit('[WARNING_NOTCL] %s' %
  2257. _("Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  2258. "is not possible.\n"
  2259. "Edit only one geometry at a time."))
  2260. # determine the tool dia of the selected tool
  2261. selected_tooldia = float(edited_object.ui.geo_tools_table.item((edited_tools[0] - 1), 1).text())
  2262. # now find the key in the edited_object.tools that has this tooldia
  2263. multi_tool = 1
  2264. for tool in edited_object.tools:
  2265. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2266. multi_tool = tool
  2267. break
  2268. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2269. else:
  2270. self.geo_editor.edit_fcgeometry(edited_object)
  2271. # set call source to the Editor we go into
  2272. self.call_source = 'geo_editor'
  2273. elif isinstance(edited_object, FlatCAMExcellon):
  2274. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2275. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2276. if self.ui.splitter.sizes()[0] == 0:
  2277. self.ui.splitter.setSizes([1, 1])
  2278. self.exc_editor.edit_fcexcellon(edited_object)
  2279. # set call source to the Editor we go into
  2280. self.call_source = 'exc_editor'
  2281. elif isinstance(edited_object, FlatCAMGerber):
  2282. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2283. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2284. if self.ui.splitter.sizes()[0] == 0:
  2285. self.ui.splitter.setSizes([1, 1])
  2286. self.grb_editor.edit_fcgerber(edited_object)
  2287. # set call source to the Editor we go into
  2288. self.call_source = 'grb_editor'
  2289. # make sure that we can't select another object while in Editor Mode:
  2290. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2291. self.ui.project_frame.setDisabled(True)
  2292. # delete any selection shape that might be active as they are not relevant in Editor
  2293. self.delete_selection_shape()
  2294. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2295. self.ui.plot_tab_area.protectTab(0)
  2296. self.inform.emit('[WARNING_NOTCL] %s' %
  2297. _("Editor is activated ..."))
  2298. self.should_we_save = True
  2299. def editor2object(self, cleanup=None):
  2300. """
  2301. Transfers the Geometry or Excellon from it's editor to the current object.
  2302. :return: None
  2303. """
  2304. self.report_usage("editor2object()")
  2305. # do not update a geometry or excellon object unless it comes out of an editor
  2306. if self.call_source != 'app':
  2307. edited_obj = self.collection.get_active()
  2308. if cleanup is None:
  2309. msgbox = QtWidgets.QMessageBox()
  2310. msgbox.setText(_("Do you want to save the edited object?"))
  2311. msgbox.setWindowTitle(_("Close Editor"))
  2312. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2313. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2314. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2315. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2316. msgbox.setDefaultButton(bt_yes)
  2317. msgbox.exec_()
  2318. response = msgbox.clickedButton()
  2319. if response == bt_yes:
  2320. # clean the Tools Tab
  2321. self.ui.tool_scroll_area.takeWidget()
  2322. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2323. self.ui.notebook.setTabText(2, "Tool")
  2324. if isinstance(edited_obj, FlatCAMGeometry):
  2325. obj_type = "Geometry"
  2326. if cleanup is None:
  2327. self.geo_editor.update_fcgeometry(edited_obj)
  2328. self.geo_editor.update_options(edited_obj)
  2329. self.geo_editor.deactivate()
  2330. # update the geo object options so it is including the bounding box values
  2331. try:
  2332. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2333. edited_obj.options['xmin'] = xmin
  2334. edited_obj.options['ymin'] = ymin
  2335. edited_obj.options['xmax'] = xmax
  2336. edited_obj.options['ymax'] = ymax
  2337. except AttributeError as e:
  2338. self.inform.emit('[WARNING] %s' %
  2339. _("Object empty after edit."))
  2340. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2341. elif isinstance(edited_obj, FlatCAMGerber):
  2342. obj_type = "Gerber"
  2343. if cleanup is None:
  2344. self.grb_editor.update_fcgerber()
  2345. self.grb_editor.update_options(edited_obj)
  2346. self.grb_editor.deactivate_grb_editor()
  2347. # delete the old object (the source object) if it was an empty one
  2348. if len(edited_obj.solid_geometry) == 0:
  2349. old_name = edited_obj.options['name']
  2350. self.collection.set_active(old_name)
  2351. self.collection.delete_active()
  2352. elif isinstance(edited_obj, FlatCAMExcellon):
  2353. obj_type = "Excellon"
  2354. if cleanup is None:
  2355. self.exc_editor.update_fcexcellon(edited_obj)
  2356. self.exc_editor.update_options(edited_obj)
  2357. self.exc_editor.deactivate()
  2358. else:
  2359. self.inform.emit('[WARNING_NOTCL] %s' %
  2360. _("Select a Gerber, Geometry or Excellon Object to update."))
  2361. return
  2362. self.inform.emit('[selected] %s %s' %
  2363. (obj_type, _("is updated, returning to App...")))
  2364. elif response == bt_no:
  2365. # clean the Tools Tab
  2366. self.ui.tool_scroll_area.takeWidget()
  2367. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2368. self.ui.notebook.setTabText(2, "Tool")
  2369. if isinstance(edited_obj, FlatCAMGeometry):
  2370. self.geo_editor.deactivate()
  2371. elif isinstance(edited_obj, FlatCAMGerber):
  2372. self.grb_editor.deactivate_grb_editor()
  2373. elif isinstance(edited_obj, FlatCAMExcellon):
  2374. self.exc_editor.deactivate()
  2375. # set focus on the project tab
  2376. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  2377. else:
  2378. self.inform.emit('[WARNING_NOTCL] %s' %
  2379. _("Select a Gerber, Geometry or Excellon Object to update."))
  2380. return
  2381. elif response == bt_cancel:
  2382. return
  2383. else:
  2384. if isinstance(edited_obj, FlatCAMGeometry):
  2385. self.geo_editor.deactivate()
  2386. elif isinstance(edited_obj, FlatCAMGerber):
  2387. self.grb_editor.deactivate_grb_editor()
  2388. elif isinstance(edited_obj, FlatCAMExcellon):
  2389. self.exc_editor.deactivate()
  2390. else:
  2391. self.inform.emit('[WARNING_NOTCL] %s' %
  2392. _("Select a Gerber, Geometry or Excellon Object to update."))
  2393. return
  2394. # if notebook is hidden we show it
  2395. if self.ui.splitter.sizes()[0] == 0:
  2396. self.ui.splitter.setSizes([1, 1])
  2397. # restore the call_source to app
  2398. self.call_source = 'app'
  2399. edited_obj.plot()
  2400. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2401. self.ui.plot_tab_area.protectTab(0)
  2402. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2403. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2404. self.ui.project_frame.setDisabled(False)
  2405. def get_last_folder(self):
  2406. """
  2407. Get the folder path from where the last file was opened.
  2408. :return: String, last opened folder path
  2409. """
  2410. return self.defaults["global_last_folder"]
  2411. def get_last_save_folder(self):
  2412. """
  2413. Get the folder path from where the last file was saved.
  2414. :return: String, last saved folder path
  2415. """
  2416. loc = self.defaults["global_last_save_folder"]
  2417. if loc is None:
  2418. loc = self.defaults["global_last_folder"]
  2419. if loc is None:
  2420. loc = os.path.dirname(__file__)
  2421. return loc
  2422. def report_usage(self, resource):
  2423. """
  2424. Increments usage counter for the given resource
  2425. in self.defaults['global_stats'].
  2426. :param resource: Name of the resource.
  2427. :return: None
  2428. """
  2429. if resource in self.defaults['global_stats']:
  2430. self.defaults['global_stats'][resource] += 1
  2431. else:
  2432. self.defaults['global_stats'][resource] = 1
  2433. def init_tcl(self):
  2434. """
  2435. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2436. :return: None
  2437. """
  2438. if hasattr(self, 'tcl'):
  2439. # self.tcl = None
  2440. # TODO we need to clean non default variables and procedures here
  2441. # new object cannot be used here as it will not remember values created for next passes,
  2442. # because tcl was execudted in old instance of TCL
  2443. pass
  2444. else:
  2445. self.tcl = tk.Tcl()
  2446. self.setup_shell()
  2447. self.log.debug("TCL Shell has been initialized.")
  2448. # TODO: This shouldn't be here.
  2449. class TclErrorException(Exception):
  2450. """
  2451. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2452. """
  2453. pass
  2454. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2455. """
  2456. Shows a message on the FlatCAM Shell
  2457. :param msg: Message to display.
  2458. :param show: Opens the shell.
  2459. :param error: Shows the message as an error.
  2460. :param warning: Shows the message as an warning.
  2461. :param success: Shows the message as an success.
  2462. :param selected: Indicate that something was selected on canvas
  2463. :return: None
  2464. """
  2465. if show:
  2466. self.ui.shell_dock.show()
  2467. try:
  2468. if error:
  2469. self.shell.append_error(msg + "\n")
  2470. elif warning:
  2471. self.shell.append_warning(msg + "\n")
  2472. elif success:
  2473. self.shell.append_success(msg + "\n")
  2474. elif selected:
  2475. self.shell.append_selected(msg + "\n")
  2476. else:
  2477. self.shell.append_output(msg + "\n")
  2478. except AttributeError:
  2479. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2480. def raise_tcl_unknown_error(self, unknownException):
  2481. """
  2482. Raise exception if is different type than TclErrorException
  2483. this is here mainly to show unknown errors inside TCL shell console.
  2484. :param unknownException:
  2485. :return:
  2486. """
  2487. if not isinstance(unknownException, self.TclErrorException):
  2488. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2489. else:
  2490. raise unknownException
  2491. def display_tcl_error(self, error, error_info=None):
  2492. """
  2493. Escape bracket [ with '\' otherwise there is error
  2494. "ERROR: missing close-bracket" instead of real error
  2495. :param error: it may be text or exception
  2496. :param error_info: Some informations about the error
  2497. :return: None
  2498. """
  2499. if isinstance(error, Exception):
  2500. exc_type, exc_value, exc_traceback = error_info
  2501. if not isinstance(error, self.TclErrorException):
  2502. show_trace = 1
  2503. else:
  2504. show_trace = int(self.defaults['global_verbose_error_level'])
  2505. if show_trace > 0:
  2506. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2507. trc_formated = []
  2508. for a in reversed(trc):
  2509. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2510. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2511. else:
  2512. text = "%s" % error
  2513. else:
  2514. text = error
  2515. text = text.replace('[', '\\[').replace('"', '\\"')
  2516. self.tcl.eval('return -code error "%s"' % text)
  2517. def raise_tcl_error(self, text):
  2518. """
  2519. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2520. :param text: text of error
  2521. :return: raise exception
  2522. """
  2523. self.display_tcl_error(text)
  2524. raise self.TclErrorException(text)
  2525. def exec_command(self, text):
  2526. """
  2527. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2528. Also handles execution in separated threads
  2529. :param text: FlatCAM TclCommand with parameters
  2530. :return: output if there was any
  2531. """
  2532. self.report_usage('exec_command')
  2533. result = self.exec_command_test(text, False)
  2534. # MS: added this method call so the geometry is updated once the TCL command is executed
  2535. self.plot_all()
  2536. return result
  2537. def exec_command_test(self, text, reraise=True):
  2538. """
  2539. Same as exec_command(...) with additional control over exceptions.
  2540. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2541. :param text: Input command
  2542. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2543. :return: Output from the command
  2544. """
  2545. text = str(text)
  2546. try:
  2547. self.shell.open_proccessing() # Disables input box.
  2548. result = self.tcl.eval(str(text))
  2549. if result != 'None':
  2550. self.shell.append_output(result + '\n')
  2551. except tk.TclError as e:
  2552. # This will display more precise answer if something in TCL shell fails
  2553. result = self.tcl.eval("set errorInfo")
  2554. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2555. self.shell.append_error('ERROR: ' + result + '\n')
  2556. # Show error in console and just return or in test raise exception
  2557. if reraise:
  2558. raise e
  2559. finally:
  2560. self.shell.close_proccessing()
  2561. pass
  2562. return result
  2563. # """
  2564. # Code below is unsused. Saved for later.
  2565. # """
  2566. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2567. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2568. # self.log.debug(parts)
  2569. # try:
  2570. # if parts[0] not in commands:
  2571. # self.shell.append_error("Unknown command\n")
  2572. # return
  2573. #
  2574. # #import inspect
  2575. # #inspect.getargspec(someMethod)
  2576. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2577. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2578. # self.shell.append_error(
  2579. # "Command %s takes %d arguments. %d given.\n" %
  2580. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2581. # )
  2582. # return
  2583. #
  2584. # cmdfcn = commands[parts[0]]["fcn"]
  2585. # cmdconv = commands[parts[0]]["converters"]
  2586. # if len(parts) - 1 > 0:
  2587. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2588. # else:
  2589. # retval = cmdfcn()
  2590. # retfcn = commands[parts[0]]["retfcn"]
  2591. # if retval and retfcn(retval):
  2592. # self.shell.append_output(retfcn(retval) + "\n")
  2593. #
  2594. # except Exception as e:
  2595. # #self.shell.append_error(''.join(traceback.format_exc()))
  2596. # #self.shell.append_error("?\n")
  2597. # self.shell.append_error(str(e) + "\n")
  2598. def info(self, msg):
  2599. """
  2600. Informs the user. Normally on the status bar, optionally
  2601. also on the shell.
  2602. :param msg: Text to write.
  2603. :return: None
  2604. """
  2605. # Type of message in brackets at the beginning of the message.
  2606. match = re.search("\[([^\]]+)\](.*)", msg)
  2607. if match:
  2608. level = match.group(1)
  2609. msg_ = match.group(2)
  2610. self.ui.fcinfo.set_status(str(msg_), level=level)
  2611. if level.lower() == "error":
  2612. self.shell_message(msg, error=True, show=True)
  2613. elif level.lower() == "warning":
  2614. self.shell_message(msg, warning=True, show=True)
  2615. elif level.lower() == "error_notcl":
  2616. self.shell_message(msg, error=True, show=False)
  2617. elif level.lower() == "warning_notcl":
  2618. self.shell_message(msg, warning=True, show=False)
  2619. elif level.lower() == "success":
  2620. self.shell_message(msg, success=True, show=False)
  2621. elif level.lower() == "selected":
  2622. self.shell_message(msg, selected=True, show=False)
  2623. else:
  2624. self.shell_message(msg, show=False)
  2625. else:
  2626. self.ui.fcinfo.set_status(str(msg), level="info")
  2627. # make sure that if the message is to clear the infobar with a space
  2628. # is not printed over and over on the shell
  2629. if msg != '':
  2630. self.shell_message(msg)
  2631. def restore_toolbar_view(self):
  2632. """
  2633. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  2634. was saved in the defaults dictionary.
  2635. :return: None
  2636. """
  2637. tb = self.defaults["global_toolbar_view"]
  2638. if tb & 1:
  2639. self.ui.toolbarfile.setVisible(True)
  2640. else:
  2641. self.ui.toolbarfile.setVisible(False)
  2642. if tb & 2:
  2643. self.ui.toolbargeo.setVisible(True)
  2644. else:
  2645. self.ui.toolbargeo.setVisible(False)
  2646. if tb & 4:
  2647. self.ui.toolbarview.setVisible(True)
  2648. else:
  2649. self.ui.toolbarview.setVisible(False)
  2650. if tb & 8:
  2651. self.ui.toolbartools.setVisible(True)
  2652. else:
  2653. self.ui.toolbartools.setVisible(False)
  2654. if tb & 16:
  2655. self.ui.exc_edit_toolbar.setVisible(True)
  2656. else:
  2657. self.ui.exc_edit_toolbar.setVisible(False)
  2658. if tb & 32:
  2659. self.ui.geo_edit_toolbar.setVisible(True)
  2660. else:
  2661. self.ui.geo_edit_toolbar.setVisible(False)
  2662. if tb & 64:
  2663. self.ui.grb_edit_toolbar.setVisible(True)
  2664. else:
  2665. self.ui.grb_edit_toolbar.setVisible(False)
  2666. if tb & 128:
  2667. self.ui.snap_toolbar.setVisible(True)
  2668. else:
  2669. self.ui.snap_toolbar.setVisible(False)
  2670. if tb & 256:
  2671. self.ui.toolbarshell.setVisible(True)
  2672. else:
  2673. self.ui.toolbarshell.setVisible(False)
  2674. def load_defaults(self, filename):
  2675. """
  2676. Loads the aplication's default settings from current_defaults.FlatConfig into
  2677. ``self.defaults``.
  2678. :return: None
  2679. """
  2680. try:
  2681. f = open(self.data_path + "/" + filename + ".FlatConfig")
  2682. options = f.read()
  2683. f.close()
  2684. except IOError:
  2685. self.log.error("Could not load defaults file.")
  2686. self.inform.emit('[ERROR] %s' %
  2687. _("Could not load defaults file."))
  2688. # in case the defaults file can't be loaded, show all toolbars
  2689. self.defaults["global_toolbar_view"] = 511
  2690. return
  2691. try:
  2692. defaults = json.loads(options)
  2693. except:
  2694. # in case the defaults file can't be loaded, show all toolbars
  2695. self.defaults["global_toolbar_view"] = 511
  2696. e = sys.exc_info()[0]
  2697. App.log.error(str(e))
  2698. self.inform.emit('[ERROR] %s' %
  2699. _("Failed to parse defaults file."))
  2700. return
  2701. self.defaults.update(defaults)
  2702. log.debug("FlatCAM defaults loaded from: %s" % filename)
  2703. # restore the toolbar view
  2704. self.restore_toolbar_view()
  2705. def on_import_preferences(self):
  2706. """
  2707. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  2708. ``self.defaults``.
  2709. :return: None
  2710. """
  2711. self.report_usage("on_import_preferences")
  2712. App.log.debug("on_import_preferences()")
  2713. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2714. try:
  2715. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2716. directory=self.data_path,
  2717. filter=filter_)
  2718. except TypeError:
  2719. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2720. filter=filter_)
  2721. filename = str(filename)
  2722. if filename == "":
  2723. self.inform.emit('[WARNING_NOTCL] %s' %
  2724. _("FlatCAM preferences import cancelled."))
  2725. else:
  2726. try:
  2727. f = open(filename)
  2728. options = f.read()
  2729. f.close()
  2730. except IOError:
  2731. self.log.error("Could not load defaults file.")
  2732. self.inform.emit('[ERROR_NOTCL] %s' %
  2733. _("Could not load defaults file."))
  2734. return
  2735. try:
  2736. defaults_from_file = json.loads(options)
  2737. except Exception as e:
  2738. e = sys.exc_info()[0]
  2739. App.log.error(str(e))
  2740. self.inform.emit('[ERROR_NOTCL] %s' %
  2741. _("Failed to parse defaults file."))
  2742. return
  2743. self.defaults.update(defaults_from_file)
  2744. self.on_preferences_edited()
  2745. self.inform.emit('[success] %s: %s' %
  2746. (_("Imported Defaults from"), filename))
  2747. def on_export_preferences(self):
  2748. """
  2749. Save the defaults dictionary to a file.
  2750. :return: None
  2751. """
  2752. self.report_usage("on_export_preferences")
  2753. App.log.debug("on_export_preferences()")
  2754. defaults_file_content = None
  2755. self.date = str(datetime.today()).rpartition('.')[0]
  2756. self.date = ''.join(c for c in self.date if c not in ':-')
  2757. self.date = self.date.replace(' ', '_')
  2758. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  2759. try:
  2760. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  2761. caption=_("Export FlatCAM Preferences"),
  2762. directory=self.data_path + '/preferences_' + self.date,
  2763. filter=filter__
  2764. )
  2765. except TypeError:
  2766. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  2767. filter=filter__)
  2768. filename = str(filename)
  2769. defaults_from_file = {}
  2770. if filename == "":
  2771. self.inform.emit('[WARNING_NOTCL] %s' %
  2772. _("FlatCAM preferences export cancelled."))
  2773. return
  2774. else:
  2775. try:
  2776. f = open(filename, 'w')
  2777. defaults_file_content = f.read()
  2778. f.close()
  2779. except PermissionError:
  2780. self.inform.emit('[WARNING] %s' %
  2781. _("Permission denied, saving not possible.\n"
  2782. "Most likely another app is holding the file open and not accessible."))
  2783. return
  2784. except IOError:
  2785. App.log.debug('Creating a new preferences file ...')
  2786. f = open(filename, 'w')
  2787. json.dump({}, f)
  2788. f.close()
  2789. except:
  2790. e = sys.exc_info()[0]
  2791. App.log.error("Could not load defaults file.")
  2792. App.log.error(str(e))
  2793. self.inform.emit('[ERROR_NOTCL] %s' %
  2794. _("Could not load preferences file."))
  2795. return
  2796. try:
  2797. defaults_from_file = json.loads(defaults_file_content)
  2798. except:
  2799. App.log.warning("Trying to read an empty Preferences file. Continue.")
  2800. # Update options
  2801. self.defaults_read_form()
  2802. defaults_from_file.update(self.defaults)
  2803. self.propagate_defaults(silent=True)
  2804. # Save update options
  2805. try:
  2806. f = open(filename, "w")
  2807. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  2808. f.close()
  2809. except:
  2810. self.inform.emit('[ERROR_NOTCL] %s' %
  2811. _("Failed to write defaults to file."))
  2812. return
  2813. if self.defaults["global_open_style"] is False:
  2814. self.file_opened.emit("preferences", filename)
  2815. self.file_saved.emit("preferences", filename)
  2816. self.inform.emit('[success] %s: %s' %
  2817. (_("Exported preferences to"), filename))
  2818. def on_preferences_open_folder(self):
  2819. """
  2820. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  2821. :return: None
  2822. """
  2823. self.report_usage("on_preferences_open_folder()")
  2824. if sys.platform == 'win32':
  2825. subprocess.Popen('explorer %s' % self.data_path)
  2826. elif sys.platform == 'darwin':
  2827. os.system('open "%s"' % self.data_path)
  2828. else:
  2829. subprocess.Popen(['xdg-open', self.data_path])
  2830. self.inform.emit('[success] %s' %
  2831. _("FlatCAM Preferences Folder opened."))
  2832. def save_geometry(self, x, y, width, height, notebook_width):
  2833. """
  2834. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2835. launch of the application.
  2836. :param x: X position of the main window
  2837. :param y: Y position of the main window
  2838. :param width: width of the main window
  2839. :param height: height of the main window
  2840. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2841. :return: None
  2842. """
  2843. self.defaults["global_def_win_x"] = x
  2844. self.defaults["global_def_win_y"] = y
  2845. self.defaults["global_def_win_w"] = width
  2846. self.defaults["global_def_win_h"] = height
  2847. self.defaults["global_def_notebook_width"] = notebook_width
  2848. self.save_defaults()
  2849. def message_dialog(self, title, message, kind="info"):
  2850. """
  2851. Builds and show a custom QMessageBox to be used in FlatCAM.
  2852. :param title: title of the QMessageBox
  2853. :param message: message to be displayed
  2854. :param kind: type of QMessageBox; will display a specific icon.
  2855. :return:
  2856. """
  2857. icon = {"info": QtWidgets.QMessageBox.Information,
  2858. "warning": QtWidgets.QMessageBox.Warning,
  2859. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2860. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2861. dlg.setText(message)
  2862. dlg.exec_()
  2863. def register_recent(self, kind, filename):
  2864. """
  2865. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2866. dictionary.
  2867. :param kind: type of file that was opened
  2868. :param filename: the path and file name for the file that was opened
  2869. :return:
  2870. """
  2871. self.log.debug("register_recent()")
  2872. self.log.debug(" %s" % kind)
  2873. self.log.debug(" %s" % filename)
  2874. record = {'kind': str(kind), 'filename': str(filename)}
  2875. if record in self.recent:
  2876. return
  2877. if record in self.recent_projects:
  2878. return
  2879. if record['kind'] == 'project':
  2880. self.recent_projects.insert(0, record)
  2881. else:
  2882. self.recent.insert(0, record)
  2883. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2884. self.recent.pop()
  2885. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2886. self.recent_projects.pop()
  2887. try:
  2888. f = open(self.data_path + '/recent.json', 'w')
  2889. except IOError:
  2890. App.log.error("Failed to open recent items file for writing.")
  2891. self.inform.emit('[ERROR_NOTCL] %s' %
  2892. _('Failed to open recent files file for writing.'))
  2893. return
  2894. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2895. f.close()
  2896. try:
  2897. fp = open(self.data_path + '/recent_projects.json', 'w')
  2898. except IOError:
  2899. App.log.error("Failed to open recent items file for writing.")
  2900. self.inform.emit('[ERROR_NOTCL] %s' %
  2901. _('Failed to open recent projects file for writing.'))
  2902. return
  2903. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2904. fp.close()
  2905. # Re-build the recent items menu
  2906. self.setup_recent_items()
  2907. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  2908. """
  2909. Creates a new specialized FlatCAMObj and attaches it to the application,
  2910. this is, updates the GUI accordingly, any other records and plots it.
  2911. This method is thread-safe.
  2912. Notes:
  2913. * If the name is in use, the self.collection will modify it
  2914. when appending it to the collection. There is no need to handle
  2915. name conflicts here.
  2916. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2917. :type kind: str
  2918. :param name: Name for the object.
  2919. :type name: str
  2920. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2921. The function is called with 2 parameters: the new object and the App instance.
  2922. :type initialize: function
  2923. :param active:
  2924. :param fit:
  2925. :param plot: If to plot the resulting object
  2926. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2927. self.colleaction
  2928. :return: None
  2929. :rtype: None
  2930. """
  2931. App.log.debug("new_object()")
  2932. obj_plot = plot
  2933. obj_autoselected = autoselected
  2934. t0 = time.time() # Debug
  2935. # ## Create object
  2936. classdict = {
  2937. "gerber": FlatCAMGerber,
  2938. "excellon": FlatCAMExcellon,
  2939. "cncjob": FlatCAMCNCjob,
  2940. "geometry": FlatCAMGeometry
  2941. }
  2942. App.log.debug("Calling object constructor...")
  2943. obj = classdict[kind](name)
  2944. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  2945. # Set options from "Project options" form
  2946. self.options_read_form()
  2947. # IMPORTANT
  2948. # The key names in defaults and options dictionary's are not random:
  2949. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2950. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  2951. # the options from project options form into the self.options. After that, below, depending on the type of
  2952. # object that is created, it will strip the name of the object and the underline (if the original key was
  2953. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2954. # "toolchange"
  2955. for option in self.options:
  2956. if option.find(kind + "_") == 0:
  2957. oname = option[len(kind) + 1:]
  2958. obj.options[oname] = self.options[option]
  2959. obj.isHovering = False
  2960. obj.notHovering = True
  2961. # Initialize as per user request
  2962. # User must take care to implement initialize
  2963. # in a thread-safe way as is is likely that we
  2964. # have been invoked in a separate thread.
  2965. t1 = time.time()
  2966. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2967. try:
  2968. return_value = initialize(obj, self)
  2969. except Exception as e:
  2970. msg = '[ERROR_NOTCL] %s' % \
  2971. _("An internal error has ocurred. See shell.\n")
  2972. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2973. msg += traceback.format_exc()
  2974. self.inform.emit(msg)
  2975. # if str(e) == "Empty Geometry":
  2976. # self.inform.emit("[ERROR_NOTCL] )
  2977. # else:
  2978. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  2979. return "fail"
  2980. t2 = time.time()
  2981. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2982. if return_value == 'fail':
  2983. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2984. return "fail"
  2985. # Check units and convert if necessary
  2986. # This condition CAN be true because initialize() can change obj.units
  2987. if self.options["units"].upper() != obj.units.upper():
  2988. self.inform.emit('%s: %s' %
  2989. (_("Converting units to "), self.options["units"]))
  2990. obj.convert_units(self.options["units"])
  2991. t3 = time.time()
  2992. self.log.debug("%f seconds converting units." % (t3 - t2))
  2993. # Create the bounding box for the object and then add the results to the obj.options
  2994. try:
  2995. xmin, ymin, xmax, ymax = obj.bounds()
  2996. obj.options['xmin'] = xmin
  2997. obj.options['ymin'] = ymin
  2998. obj.options['xmax'] = xmax
  2999. obj.options['ymax'] = ymax
  3000. except Exception as e:
  3001. log.warning("The object has no bounds properties. %s" % str(e))
  3002. return "fail"
  3003. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3004. # Move the object to the main thread and let the app know that it is available.
  3005. obj.moveToThread(self.main_thread)
  3006. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3007. return obj
  3008. def new_excellon_object(self):
  3009. """
  3010. Creates a new, blank Excellon object.
  3011. :return: None
  3012. """
  3013. self.report_usage("new_excellon_object()")
  3014. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3015. def new_geometry_object(self):
  3016. """
  3017. Creates a new, blank and single-tool Geometry object.
  3018. :return: None
  3019. """
  3020. self.report_usage("new_geometry_object()")
  3021. def initialize(obj, self):
  3022. obj.multitool = False
  3023. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3024. def new_gerber_object(self):
  3025. """
  3026. Creates a new, blank Gerber object.
  3027. :return: None
  3028. """
  3029. self.report_usage("new_gerber_object()")
  3030. def initialize(grb_obj, self):
  3031. grb_obj.multitool = False
  3032. grb_obj.source_file = []
  3033. grb_obj.multigeo = False
  3034. grb_obj.follow = False
  3035. grb_obj.apertures = {}
  3036. grb_obj.solid_geometry = []
  3037. try:
  3038. grb_obj.options['xmin'] = 0
  3039. grb_obj.options['ymin'] = 0
  3040. grb_obj.options['xmax'] = 0
  3041. grb_obj.options['ymax'] = 0
  3042. except KeyError:
  3043. pass
  3044. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3045. def on_object_created(self, obj, plot, autoselect):
  3046. """
  3047. Event callback for object creation.
  3048. It will add the new object to the collection. After that it will plot the object in a threaded way
  3049. :param obj: The newly created FlatCAM object.
  3050. :param plot: if the newly create object t obe plotted
  3051. :param autoselect: if the newly created object to be autoselected after creation
  3052. :return: None
  3053. """
  3054. t0 = time.time() # DEBUG
  3055. self.log.debug("on_object_created()")
  3056. # The Collection might change the name if there is a collision
  3057. self.collection.append(obj)
  3058. # after adding the object to the collection always update the list of objects that are in the collection
  3059. self.all_objects_list = self.collection.get_list()
  3060. # self.inform.emit('[selected] %s created & selected: %s' %
  3061. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3062. if obj.kind == 'gerber':
  3063. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3064. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3065. elif obj.kind == 'excellon':
  3066. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3067. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3068. elif obj.kind == 'cncjob':
  3069. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3070. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3071. elif obj.kind == 'geometry':
  3072. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3073. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3074. # update the SHELL auto-completer model with the name of the new object
  3075. self.myKeywords.append(obj.options['name'])
  3076. self.shell._edit.set_model_data(self.myKeywords)
  3077. self.ui.code_editor.set_model_data(self.myKeywords)
  3078. if autoselect:
  3079. # select the just opened object but deselect the previous ones
  3080. self.collection.set_all_inactive()
  3081. self.collection.set_active(obj.options["name"])
  3082. else:
  3083. self.collection.set_all_inactive()
  3084. # here it is done the object plotting
  3085. def worker_task(t_obj):
  3086. with self.proc_container.new(_("Plotting")):
  3087. if isinstance(t_obj, FlatCAMCNCjob):
  3088. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3089. else:
  3090. t_obj.plot()
  3091. t1 = time.time() # DEBUG
  3092. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3093. self.object_plotted.emit(t_obj)
  3094. # Send to worker
  3095. # self.worker.add_task(worker_task, [self])
  3096. if plot is True:
  3097. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3098. def on_object_changed(self, obj):
  3099. """
  3100. Called whenever the geometry of the object was changed in some way.
  3101. This require the update of it's bounding values so it can be the selected on canvas.
  3102. Update the bounding box data from obj.options
  3103. :param obj: the object that was changed
  3104. :return: None
  3105. """
  3106. xmin, ymin, xmax, ymax = obj.bounds()
  3107. obj.options['xmin'] = xmin
  3108. obj.options['ymin'] = ymin
  3109. obj.options['xmax'] = xmax
  3110. obj.options['ymax'] = ymax
  3111. log.debug("Object changed, updating the bounding box data on self.options")
  3112. # delete the old selection shape
  3113. self.delete_selection_shape()
  3114. self.should_we_save = True
  3115. def on_object_plotted(self, obj):
  3116. """
  3117. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3118. :param obj: object to be fit into view
  3119. :return: None
  3120. """
  3121. self.on_zoom_fit(None)
  3122. def options_read_form(self):
  3123. """
  3124. Same as it's equivalent from the defaults.
  3125. self.options use to store the preferences per project. No longer used.
  3126. :return: None
  3127. """
  3128. for option in self.options_form_fields:
  3129. self.options[option] = self.options_form_fields[option].get_value()
  3130. def options_write_form(self):
  3131. """
  3132. Same as it's equivalent from the defaults.
  3133. self.options use to store the preferences per project. No longer used.
  3134. :return: None
  3135. """
  3136. for option in self.options:
  3137. self.options_write_form_field(option)
  3138. def options_write_form_field(self, field):
  3139. """
  3140. Same as it's equivalent from the defaults.
  3141. self.options use to store the preferences per project. No longer used.
  3142. :return: None
  3143. """
  3144. try:
  3145. self.options_form_fields[field].set_value(self.options[field])
  3146. except KeyError:
  3147. # Changed from error to debug. This allows to have data stored
  3148. # which is not user-editable.
  3149. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  3150. pass
  3151. def on_about(self):
  3152. """
  3153. Displays the "about" dialog found in the Menu --> Help.
  3154. :return: None
  3155. """
  3156. self.report_usage("on_about")
  3157. version = self.version
  3158. version_date = self.version_date
  3159. beta = self.beta
  3160. class AboutDialog(QtWidgets.QDialog):
  3161. def __init__(self, parent=None):
  3162. QtWidgets.QDialog.__init__(self, parent)
  3163. # Icon and title
  3164. self.setWindowIcon(parent.app_icon)
  3165. self.setWindowTitle(_("About FlatCAM"))
  3166. self.resize(600, 200)
  3167. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3168. # self.setStyleSheet(
  3169. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3170. # "background-attachment: fixed"
  3171. # )
  3172. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3173. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3174. # palette = QtGui.QPalette()
  3175. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3176. # self.setPalette(palette)
  3177. logo = QtWidgets.QLabel()
  3178. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3179. title = QtWidgets.QLabel(
  3180. _(
  3181. "<font size=8><B>FlatCAM</B></font><BR>"
  3182. "2D Computer-Aided Printed Circuit Board<BR>"
  3183. "Manufacturing.<BR>"
  3184. "<BR>"
  3185. "<BR>"
  3186. "<B>Development</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3187. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  3188. "<b>DOWNLOAD</B> area &nbsp;&nbsp;&nbsp;&nbsp;"
  3189. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  3190. "<b>Issue tracker</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3191. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">here.</a><BR>"
  3192. )
  3193. )
  3194. title.setOpenExternalLinks(True)
  3195. closebtn = QtWidgets.QPushButton(_("Close"))
  3196. tab_widget = QtWidgets.QTabWidget()
  3197. description_label = QtWidgets.QLabel(
  3198. _(
  3199. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3200. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>"
  3201. ).format(version=version,
  3202. beta=('BETA' if beta else ''),
  3203. date=version_date,
  3204. arch=platform.architecture()[0])
  3205. )
  3206. description_label.setOpenExternalLinks(True)
  3207. programmers_label = QtWidgets.QLabel(
  3208. _(
  3209. "Juan Pablo Caram <BR>"
  3210. "<BR>"
  3211. "Denis Hayrullin<BR>"
  3212. "Kamil Sopko<BR>"
  3213. "Marius Stanciu<BR>"
  3214. "Matthieu Berthomé<BR><Br>"
  3215. "and many others found "
  3216. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  3217. "<BR>"
  3218. )
  3219. )
  3220. programmers_label.setOpenExternalLinks(True)
  3221. translators_label = QtWidgets.QLabel(
  3222. _(
  3223. "Brasilian - Portuguese: \t\t Carlos Stein\n"
  3224. "German: \t\t Marius Stanciu (Google-Translation)\n"
  3225. "Romanian: \t\t Marius Stanciu\n"
  3226. "Russian: \t\t Andrey Kultyapov <camellan@yandex.ru>\n"
  3227. "Spanish: \t\t Marius Stanciu (Google-Translation)\n"
  3228. )
  3229. )
  3230. translators_label.setOpenExternalLinks(True)
  3231. license_label = QtWidgets.QLabel(
  3232. _(
  3233. '(c) Copyright 2014 Juan Pablo Caram.\n\n'
  3234. 'Licensed under the MIT license:\n'
  3235. 'http://www.opensource.org/licenses/mit-license.php\n\n'
  3236. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3237. 'of this software and associated documentation files (the "Software"), to deal\n'
  3238. 'in the Software without restriction, including without limitation the rights\n'
  3239. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3240. 'copies of the Software, and to permit persons to whom the Software is\n'
  3241. ' furnished to do so, subject to the following conditions:\n\n'
  3242. 'The above copyright notice and this permission notice shall be included in\n'
  3243. 'all copies or substantial portions of the Software.\n\n'
  3244. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3245. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3246. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3247. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3248. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3249. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3250. 'THE SOFTWARE.'
  3251. )
  3252. )
  3253. license_label.setOpenExternalLinks(True)
  3254. # layouts
  3255. layout1 = QtWidgets.QVBoxLayout()
  3256. layout1_1 = QtWidgets.QHBoxLayout()
  3257. layout1_2 = QtWidgets.QHBoxLayout()
  3258. layout2 = QtWidgets.QHBoxLayout()
  3259. layout3 = QtWidgets.QHBoxLayout()
  3260. self.setLayout(layout1)
  3261. layout1.addLayout(layout1_1)
  3262. layout1.addLayout(layout1_2)
  3263. layout1.addLayout(layout2)
  3264. layout1.addLayout(layout3)
  3265. layout1_1.addStretch()
  3266. layout1_1.addWidget(description_label)
  3267. layout1_2.addWidget(tab_widget)
  3268. self.splash_tab = QtWidgets.QWidget()
  3269. self.splash_tab.setObjectName("splash_about")
  3270. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3271. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3272. tab_widget.addTab(self.splash_tab, _("Splash"))
  3273. self.programmmers_tab = QtWidgets.QWidget()
  3274. self.programmmers_tab.setObjectName("programmers_about")
  3275. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3276. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3277. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3278. self.translators_tab = QtWidgets.QWidget()
  3279. self.translators_tab.setObjectName("translators_about")
  3280. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3281. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3282. tab_widget.addTab(self.translators_tab, _("Translators"))
  3283. self.license_tab = QtWidgets.QWidget()
  3284. self.license_tab.setObjectName("license_about")
  3285. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3286. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3287. tab_widget.addTab(self.license_tab, _("License"))
  3288. self.splash_tab_layout.addWidget(logo, stretch=0)
  3289. self.splash_tab_layout.addWidget(title, stretch=1)
  3290. self.programmmers_tab_layout.addWidget(programmers_label)
  3291. self.programmmers_tab_layout.addStretch()
  3292. self.translators_tab_layout.addWidget(translators_label)
  3293. self.translators_tab_layout.addStretch()
  3294. self.license_tab_layout.addWidget(license_label)
  3295. self.license_tab_layout.addStretch()
  3296. layout3.addStretch()
  3297. layout3.addWidget(closebtn)
  3298. closebtn.clicked.connect(self.accept)
  3299. AboutDialog(self.ui).exec_()
  3300. def on_file_savedefaults(self):
  3301. """
  3302. Callback for menu item File->Save Defaults. Saves application default options
  3303. ``self.defaults`` to current_defaults.FlatConfig.
  3304. :return: None
  3305. """
  3306. self.save_defaults()
  3307. # def on_app_exit(self):
  3308. # self.report_usage("on_app_exit()")
  3309. #
  3310. # if self.collection.get_list():
  3311. # msgbox = QtWidgets.QMessageBox()
  3312. # # msgbox.setText("<B>Save changes ...</B>")
  3313. # msgbox.setText("There are files/objects opened in FlatCAM. "
  3314. # "\n"
  3315. # "Do you want to Save the project?")
  3316. # msgbox.setWindowTitle("Save changes")
  3317. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3318. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  3319. # QtWidgets.QMessageBox.Cancel)
  3320. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  3321. #
  3322. # response = msgbox.exec_()
  3323. #
  3324. # if response == QtWidgets.QMessageBox.Yes:
  3325. # self.on_file_saveprojectas(thread=False)
  3326. # elif response == QtWidgets.QMessageBox.Cancel:
  3327. # return
  3328. # self.save_defaults()
  3329. # else:
  3330. # self.save_defaults()
  3331. # log.debug("Application defaults saved ... Exit event.")
  3332. # QtWidgets.qApp.quit()
  3333. def save_defaults(self, silent=False, data_path=None):
  3334. """
  3335. Saves application default options
  3336. ``self.defaults`` to current_defaults.FlatConfig file.
  3337. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  3338. used at the next launch of the application.
  3339. :param silent: whether to display a message in status bar or not; boolean
  3340. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  3341. When the application is portable it should be a mobile location.
  3342. :return: None
  3343. """
  3344. self.report_usage("save_defaults")
  3345. if data_path is None:
  3346. data_path = self.data_path
  3347. # Read options from file
  3348. try:
  3349. f = open(data_path + "/current_defaults.FlatConfig")
  3350. defaults_file_content = f.read()
  3351. f.close()
  3352. except:
  3353. e = sys.exc_info()[0]
  3354. App.log.error("Could not load defaults file.")
  3355. App.log.error(str(e))
  3356. self.inform.emit('[ERROR_NOTCL] %s' %
  3357. _("Could not load defaults file."))
  3358. return
  3359. try:
  3360. defaults = json.loads(defaults_file_content)
  3361. except:
  3362. e = sys.exc_info()[0]
  3363. App.log.error("Failed to parse defaults file.")
  3364. App.log.error(str(e))
  3365. self.inform.emit('[ERROR_NOTCL] %s' %
  3366. _("Failed to parse defaults file."))
  3367. return
  3368. # Update options
  3369. self.defaults_read_form()
  3370. defaults.update(self.defaults)
  3371. self.propagate_defaults(silent=True)
  3372. # Save the toolbar view
  3373. tb_status = 0
  3374. if self.ui.toolbarfile.isVisible():
  3375. tb_status += 1
  3376. if self.ui.toolbargeo.isVisible():
  3377. tb_status += 2
  3378. if self.ui.toolbarview.isVisible():
  3379. tb_status += 4
  3380. if self.ui.toolbartools.isVisible():
  3381. tb_status += 8
  3382. if self.ui.exc_edit_toolbar.isVisible():
  3383. tb_status += 16
  3384. if self.ui.geo_edit_toolbar.isVisible():
  3385. tb_status += 32
  3386. if self.ui.grb_edit_toolbar.isVisible():
  3387. tb_status += 64
  3388. if self.ui.snap_toolbar.isVisible():
  3389. tb_status += 128
  3390. if self.ui.toolbarshell.isVisible():
  3391. tb_status += 256
  3392. self.defaults["global_toolbar_view"] = tb_status
  3393. # Save update options
  3394. try:
  3395. f = open(data_path + "/current_defaults.FlatConfig", "w")
  3396. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  3397. f.close()
  3398. except:
  3399. self.inform.emit('[ERROR_NOTCL] %s' %
  3400. _("Failed to write defaults to file."))
  3401. return
  3402. if not silent:
  3403. self.inform.emit('[success] %s' %
  3404. _("Preferences saved."))
  3405. def save_factory_defaults(self, silent=False, data_path=None):
  3406. """
  3407. Saves application factory default options
  3408. ``self.defaults`` to factory_defaults.FlatConfig.
  3409. It's a one time job done just after the first install.
  3410. :param silent: whether to display a message in status bar or not; boolean
  3411. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  3412. When the application is portable it should be a mobile location.
  3413. :return: None
  3414. """
  3415. self.report_usage("save_factory_defaults")
  3416. if data_path is None:
  3417. data_path = self.data_path
  3418. # Read options from file
  3419. try:
  3420. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  3421. factory_defaults_file_content = f_f_def.read()
  3422. f_f_def.close()
  3423. except:
  3424. e = sys.exc_info()[0]
  3425. App.log.error("Could not load factory defaults file.")
  3426. App.log.error(str(e))
  3427. self.inform.emit('[ERROR_NOTCL] %s' %
  3428. _("Could not load factory defaults file."))
  3429. return
  3430. try:
  3431. factory_defaults = json.loads(factory_defaults_file_content)
  3432. except:
  3433. e = sys.exc_info()[0]
  3434. App.log.error("Failed to parse factory defaults file.")
  3435. App.log.error(str(e))
  3436. self.inform.emit('[ERROR_NOTCL] %s' %
  3437. _("Failed to parse factory defaults file."))
  3438. return
  3439. # Update options
  3440. self.defaults_read_form()
  3441. factory_defaults.update(self.defaults)
  3442. self.propagate_defaults(silent=True)
  3443. # Save update options
  3444. try:
  3445. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  3446. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3447. f_f_def_s.close()
  3448. except:
  3449. self.inform.emit('[ERROR_NOTCL] %s' %
  3450. _("Failed to write factory defaults to file."))
  3451. return
  3452. if silent is False:
  3453. self.inform.emit(_("Factory defaults saved."))
  3454. def final_save(self):
  3455. """
  3456. Callback for doing a preferences save to file whenever the application is about to quit.
  3457. If the project has changes, it will ask the user to save the project.
  3458. :return: None
  3459. """
  3460. if self.save_in_progress:
  3461. self.inform.emit('[WARNING_NOTCL] %s' %
  3462. _("Application is saving the project. Please wait ..."))
  3463. return
  3464. if self.should_we_save and self.collection.get_list():
  3465. msgbox = QtWidgets.QMessageBox()
  3466. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  3467. "\n"
  3468. "Do you want to Save the project?"))
  3469. msgbox.setWindowTitle(_("Save changes"))
  3470. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3471. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  3472. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  3473. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3474. msgbox.setDefaultButton(bt_yes)
  3475. msgbox.exec_()
  3476. response = msgbox.clickedButton()
  3477. if response == bt_yes:
  3478. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  3479. elif response == bt_no:
  3480. self.quit_application()
  3481. elif response == bt_cancel:
  3482. return
  3483. else:
  3484. self.quit_application()
  3485. def quit_application(self):
  3486. """
  3487. Called (as a pyslot or not) when the application is quit.
  3488. :return: None
  3489. """
  3490. self.save_defaults()
  3491. log.debug("App.final_save() --> App Defaults saved.")
  3492. # save toolbar state to file
  3493. settings = QSettings("Open Source", "FlatCAM")
  3494. settings.setValue('saved_gui_state', self.ui.saveState())
  3495. settings.setValue('maximized_gui', self.ui.isMaximized())
  3496. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  3497. settings.setValue('notebook_font_size',
  3498. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value())
  3499. settings.setValue('axis_font_size',
  3500. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value())
  3501. settings.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  3502. # This will write the setting to the platform specific storage.
  3503. del settings
  3504. log.debug("App.final_save() --> App UI state saved.")
  3505. QtWidgets.qApp.quit()
  3506. def on_portable_checked(self, state):
  3507. """
  3508. Callback called when the checkbox in Preferences GUI is checked.
  3509. It will set the application as portable by creating the preferences and recent files in the
  3510. 'config' folder found in the FlatCAM installation folder.
  3511. :param state: boolean, the state of the checkbox when clicked/checked
  3512. :return:
  3513. """
  3514. line_no = 0
  3515. data = None
  3516. if sys.platform != 'win32':
  3517. # this won't work in Linux or MacOS
  3518. return
  3519. # test if the app was frozen and choose the path for the configuration file
  3520. if getattr(sys, "frozen", False) is True:
  3521. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  3522. else:
  3523. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  3524. config_file = current_data_path + '\\configuration.txt'
  3525. try:
  3526. with open(config_file, 'r') as f:
  3527. try:
  3528. data = f.readlines()
  3529. except Exception as e:
  3530. log.debug('App.__init__() -->%s' % str(e))
  3531. return
  3532. except FileNotFoundError:
  3533. pass
  3534. for line in data:
  3535. line = line.strip('\n')
  3536. param = str(line).rpartition('=')
  3537. if param[0] == 'portable':
  3538. break
  3539. line_no += 1
  3540. if state:
  3541. data[line_no] = 'portable=True\n'
  3542. # create the new defauults files
  3543. # create current_defaults.FlatConfig file if there is none
  3544. try:
  3545. f = open(current_data_path + '/current_defaults.FlatConfig')
  3546. f.close()
  3547. except IOError:
  3548. App.log.debug('Creating empty current_defaults.FlatConfig')
  3549. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3550. json.dump({}, f)
  3551. f.close()
  3552. # create factory_defaults.FlatConfig file if there is none
  3553. try:
  3554. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3555. f.close()
  3556. except IOError:
  3557. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3558. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3559. json.dump({}, f)
  3560. f.close()
  3561. try:
  3562. f = open(current_data_path + '/recent.json')
  3563. f.close()
  3564. except IOError:
  3565. App.log.debug('Creating empty recent.json')
  3566. f = open(current_data_path + '/recent.json', 'w')
  3567. json.dump([], f)
  3568. f.close()
  3569. try:
  3570. fp = open(current_data_path + '/recent_projects.json')
  3571. fp.close()
  3572. except IOError:
  3573. App.log.debug('Creating empty recent_projects.json')
  3574. fp = open(current_data_path + '/recent_projects.json', 'w')
  3575. json.dump([], fp)
  3576. fp.close()
  3577. # save the current defaults to the new defaults file
  3578. self.save_defaults(silent=True, data_path=current_data_path)
  3579. self.save_factory_defaults(silent=True, data_path=current_data_path)
  3580. else:
  3581. data[line_no] = 'portable=False\n'
  3582. with open(config_file, 'w') as f:
  3583. f.writelines(data)
  3584. def on_toggle_shell(self):
  3585. """
  3586. Toggle shell: if is visible close it, if it is closed then open it
  3587. :return:
  3588. """
  3589. self.report_usage("on_toggle_shell()")
  3590. if self.ui.shell_dock.isVisible():
  3591. self.ui.shell_dock.hide()
  3592. else:
  3593. self.ui.shell_dock.show()
  3594. def on_register_files(self, obj_type=None):
  3595. """
  3596. Called whenever there is a need to register file extensions with FlatCAM.
  3597. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3598. :param obj_type: the type of object to be register for.
  3599. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3600. :return: None
  3601. """
  3602. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3603. new_reg_path = 'Software\\Classes\\'
  3604. # find if the current user is admin
  3605. try:
  3606. is_admin = os.getuid() == 0
  3607. except AttributeError:
  3608. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3609. if is_admin is True:
  3610. root_path = winreg.HKEY_CLASSES_ROOT
  3611. else:
  3612. root_path = winreg.HKEY_CURRENT_USER
  3613. # create the keys
  3614. def set_reg(name, root_path, new_reg_path, value):
  3615. try:
  3616. winreg.CreateKey(root_path, new_reg_path)
  3617. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3618. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3619. return True
  3620. except WindowsError:
  3621. return False
  3622. # delete key in registry
  3623. def delete_reg(root_path, reg_path, key_to_del):
  3624. key_to_del_path = reg_path + key_to_del
  3625. try:
  3626. winreg.DeleteKey(root_path, key_to_del_path)
  3627. return True
  3628. except WindowsError:
  3629. return False
  3630. if obj_type is None or obj_type == 'excellon':
  3631. exc_list = self.ui.fa_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3632. exc_list = [x for x in exc_list if x != '']
  3633. # register all keys in the Preferences window
  3634. for ext in exc_list:
  3635. new_k = new_reg_path + ext
  3636. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3637. # and unregister those that are no longer in the Preferences windows but are in the file
  3638. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3639. if ext not in exc_list:
  3640. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del=ext)
  3641. # now write the updated extensions to the self.defaults
  3642. new_ext = ''
  3643. for ext in exc_list:
  3644. new_ext = new_ext + ext + ', '
  3645. self.defaults["fa_excellon"] = new_ext
  3646. self.inform.emit(_("[success] Selected Excellon file extensions registered with FlatCAM."))
  3647. if obj_type is None or obj_type == 'gcode':
  3648. gco_list = self.ui.fa_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3649. gco_list = [x for x in gco_list if x != '']
  3650. # register all keys in the Preferences window
  3651. for ext in gco_list:
  3652. new_k = new_reg_path + ext
  3653. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3654. # and unregister those that are no longer in the Preferences windows but are in the file
  3655. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3656. if ext not in gco_list:
  3657. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del=ext)
  3658. # now write the updated extensions to the self.defaults
  3659. new_ext = ''
  3660. for ext in gco_list:
  3661. new_ext = new_ext + ext + ', '
  3662. self.defaults["fa_gcode"] = new_ext
  3663. self.inform.emit('[success] %s' %
  3664. _("Selected GCode file extensions registered with FlatCAM."))
  3665. if obj_type is None or obj_type == 'gerber':
  3666. grb_list = self.ui.fa_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3667. grb_list = [x for x in grb_list if x != '']
  3668. # register all keys in the Preferences window
  3669. for ext in grb_list:
  3670. new_k = new_reg_path + ext
  3671. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3672. # and unregister those that are no longer in the Preferences windows but are in the file
  3673. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3674. if ext not in grb_list:
  3675. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del=ext)
  3676. # now write the updated extensions to the self.defaults
  3677. new_ext = ''
  3678. for ext in grb_list:
  3679. new_ext = new_ext + ext + ', '
  3680. self.defaults["fa_gerber"] = new_ext
  3681. self.inform.emit('[success] %s' %
  3682. _("Selected Gerber file extensions registered with FlatCAM."))
  3683. def on_edit_join(self, name=None):
  3684. """
  3685. Callback for Edit->Join. Joins the selected geometry objects into
  3686. a new one.
  3687. :return: None
  3688. """
  3689. self.report_usage("on_edit_join()")
  3690. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3691. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3692. tooldias = []
  3693. geo_type_list = set()
  3694. objs = self.collection.get_selected()
  3695. for obj in objs:
  3696. geo_type_list.add(obj.multigeo)
  3697. # if len(geo_type_list) == 1 means that all list elements are the same
  3698. if len(geo_type_list) != 1:
  3699. self.inform.emit('[ERROR] %s' %
  3700. _("Failed join. The Geometry objects are of different types.\n"
  3701. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3702. "convert from one to another and retry joining \n"
  3703. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3704. "the result may not be what was expected. \n"
  3705. "Check the generated GCODE."))
  3706. return
  3707. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3708. if True in geo_type_list:
  3709. def initialize(obj, app):
  3710. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=True)
  3711. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3712. for v in obj.tools.values():
  3713. v['data']['name'] = obj_name_multi
  3714. self.new_object("geometry", obj_name_multi, initialize)
  3715. else:
  3716. def initialize(obj, app):
  3717. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=False)
  3718. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3719. for v in obj.tools.values():
  3720. v['data']['name'] = obj_name_single
  3721. self.new_object("geometry", obj_name_single, initialize)
  3722. self.should_we_save = True
  3723. def on_edit_join_exc(self):
  3724. """
  3725. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3726. a new Excellon.
  3727. :return: None
  3728. """
  3729. self.report_usage("on_edit_join_exc()")
  3730. objs = self.collection.get_selected()
  3731. for obj in objs:
  3732. if not isinstance(obj, FlatCAMExcellon):
  3733. self.inform.emit('[ERROR_NOTCL] %s' %
  3734. _("Failed. Excellon joining works only on Excellon objects."))
  3735. return
  3736. def initialize(obj, app):
  3737. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=obj)
  3738. self.new_object("excellon", 'Combo_Excellon', initialize)
  3739. self.should_we_save = True
  3740. def on_edit_join_grb(self):
  3741. """
  3742. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3743. a new Gerber object.
  3744. :return: None
  3745. """
  3746. self.report_usage("on_edit_join_grb()")
  3747. objs = self.collection.get_selected()
  3748. for obj in objs:
  3749. if not isinstance(obj, FlatCAMGerber):
  3750. self.inform.emit('[ERROR_NOTCL] %s' %
  3751. _("Failed. Gerber joining works only on Gerber objects."))
  3752. return
  3753. def initialize(obj, app):
  3754. FlatCAMGerber.merge(self, grb_list=objs, grb_final=obj)
  3755. self.new_object("gerber", 'Combo_Gerber', initialize)
  3756. self.should_we_save = True
  3757. def on_convert_singlegeo_to_multigeo(self):
  3758. """
  3759. Called for converting a Geometry object from single-geo to multi-geo.
  3760. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3761. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3762. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3763. the solid-geometry of that tool.
  3764. :return: None
  3765. """
  3766. self.report_usage("on_convert_singlegeo_to_multigeo()")
  3767. obj = self.collection.get_active()
  3768. if obj is None:
  3769. self.inform.emit('[ERROR_NOTCL] %s' %
  3770. _("Failed. Select a Geometry Object and try again."))
  3771. return
  3772. if not isinstance(obj, FlatCAMGeometry):
  3773. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3774. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  3775. return
  3776. obj.multigeo = True
  3777. for tooluid, dict_value in obj.tools.items():
  3778. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3779. if not isinstance(obj.solid_geometry, list):
  3780. obj.solid_geometry = [obj.solid_geometry]
  3781. obj.solid_geometry[:] = []
  3782. obj.plot()
  3783. self.should_we_save = True
  3784. self.inform.emit('[success] %s' %
  3785. _("A Geometry object was converted to MultiGeo type."))
  3786. def on_convert_multigeo_to_singlegeo(self):
  3787. """
  3788. Called for converting a Geometry object from multi-geo to single-geo.
  3789. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3790. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3791. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3792. the solid-geometry of that tool.
  3793. :return: None
  3794. """
  3795. self.report_usage("on_convert_multigeo_to_singlegeo()")
  3796. obj = self.collection.get_active()
  3797. if obj is None:
  3798. self.inform.emit('[ERROR_NOTCL] %s' %
  3799. _("Failed. Select a Geometry Object and try again."))
  3800. return
  3801. if not isinstance(obj, FlatCAMGeometry):
  3802. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3803. (_("Expected a FlatCAMGeometry, got %s"), type(obj)))
  3804. return
  3805. obj.multigeo = False
  3806. total_solid_geometry = []
  3807. for tooluid, dict_value in obj.tools.items():
  3808. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3809. # clear the original geometry
  3810. dict_value['solid_geometry'][:] = []
  3811. obj.solid_geometry = deepcopy(total_solid_geometry)
  3812. obj.plot()
  3813. self.should_we_save = True
  3814. self.inform.emit('[success] %s' %
  3815. _("A Geometry object was converted to SingleGeo type."))
  3816. def on_options_dict_change(self, field):
  3817. """
  3818. Called whenever a key changed in the self.options dictionary. This dict was used to store the preferences of the
  3819. current project. This feature is no longer used.
  3820. :param field:
  3821. :return:
  3822. """
  3823. self.options_write_form_field(field)
  3824. if field == "units":
  3825. self.set_screen_units(self.options['units'])
  3826. def on_defaults_dict_change(self, field):
  3827. """
  3828. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3829. Edit -> Preferences tab window.
  3830. :param field: the key of the self.defaults dictionary that was changed.
  3831. :return: None
  3832. """
  3833. self.defaults_write_form_field(field)
  3834. if field == "units":
  3835. self.set_screen_units(self.defaults['units'])
  3836. def set_screen_units(self, units):
  3837. """
  3838. Set the FlatCAM units on the status bar.
  3839. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3840. :return: None
  3841. """
  3842. self.ui.units_label.setText("[" + units.lower() + "]")
  3843. def on_toggle_units(self, no_pref=False):
  3844. """
  3845. Callback for the Units radio-button change in the Preferences tab.
  3846. Changes the application's default units adn for the project too.
  3847. If changing the project's units, the change propagates to all of
  3848. the objects in the project.
  3849. :return: None
  3850. """
  3851. self.report_usage("on_toggle_units")
  3852. if self.toggle_units_ignore:
  3853. return
  3854. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3855. # If option is the same, then ignore
  3856. if new_units == self.defaults["units"].upper():
  3857. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  3858. return
  3859. # Options to scale
  3860. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3861. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  3862. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3863. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  3864. "excellon_z_pdepth",
  3865. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3866. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3867. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  3868. "geometry_feedrate_probe",
  3869. 'cncjob_tooldia',
  3870. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  3871. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia"
  3872. "tools_2sided_drilldia", "tools_film_boundary",
  3873. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  3874. "tools_panelize_constrainx", "tools_panelize_constrainy",
  3875. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3876. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  3877. "tools_transform_offset_y",
  3878. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3879. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3880. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3881. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3882. 'global_gridx', 'global_gridy', 'global_snap_max']
  3883. def scale_options(sfactor):
  3884. for dim in dimensions:
  3885. if dim == 'excellon_toolchangexy':
  3886. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  3887. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3888. coords_xy[0] *= sfactor
  3889. coords_xy[1] *= sfactor
  3890. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3891. elif dim == 'geometry_toolchangexy':
  3892. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  3893. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3894. coords_xy[0] *= sfactor
  3895. coords_xy[1] *= sfactor
  3896. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3897. elif dim == 'geometry_cnctooldia':
  3898. tools_diameters = []
  3899. try:
  3900. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  3901. tools_diameters = [eval(a) for a in tools_string if a != '']
  3902. except Exception as e:
  3903. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3904. self.options['geometry_cnctooldia'] = ''
  3905. for t in range(len(tools_diameters)):
  3906. tools_diameters[t] *= sfactor
  3907. self.options['geometry_cnctooldia'] += "%f," % tools_diameters[t]
  3908. elif dim == 'tools_ncctools':
  3909. ncctools = []
  3910. try:
  3911. tools_string = self.defaults["tools_ncctools"].split(",")
  3912. ncctools = [eval(a) for a in tools_string if a != '']
  3913. except Exception as e:
  3914. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3915. self.options['tools_ncctools'] = ''
  3916. for t in range(len(ncctools)):
  3917. ncctools[t] *= sfactor
  3918. self.options['tools_ncctools'] += "%f," % ncctools[t]
  3919. elif dim == 'tools_solderpaste_tools':
  3920. sptools = []
  3921. try:
  3922. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  3923. sptools = [eval(a) for a in tools_string if a != '']
  3924. except Exception as e:
  3925. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3926. self.options['tools_solderpaste_tools'] = ""
  3927. for t in range(len(sptools)):
  3928. sptools[t] *= sfactor
  3929. self.options['tools_solderpaste_tools'] += "%f," % sptools[t]
  3930. elif dim == 'tools_solderpaste_xy_toolchange':
  3931. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  3932. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  3933. sp_coords[0] *= sfactor
  3934. sp_coords[1] *= sfactor
  3935. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  3936. elif dim == 'global_gridx' or dim == 'global_gridy':
  3937. if new_units == 'IN':
  3938. val = 0.1
  3939. try:
  3940. val = float(self.defaults[dim]) * sfactor
  3941. except Exception as e:
  3942. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3943. self.options[dim] = float('%.6f' % val)
  3944. else:
  3945. val = 0.1
  3946. try:
  3947. val = float(self.defaults[dim]) * sfactor
  3948. except Exception as e:
  3949. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3950. self.options[dim] = float('%.4f' % val)
  3951. else:
  3952. val = 0.1
  3953. try:
  3954. val = float(self.options[dim]) * sfactor
  3955. except Exception as e:
  3956. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  3957. self.options[dim] = val
  3958. def scale_defaults(sfactor):
  3959. for dim in dimensions:
  3960. if dim == 'excellon_toolchangexy':
  3961. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  3962. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3963. coords_xy[0] *= sfactor
  3964. coords_xy[1] *= sfactor
  3965. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  3966. elif dim == 'geometry_toolchangexy':
  3967. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  3968. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3969. coords_xy[0] *= sfactor
  3970. coords_xy[1] *= sfactor
  3971. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  3972. elif dim == 'geometry_cnctooldia':
  3973. tools_diameters = []
  3974. try:
  3975. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  3976. tools_diameters = [eval(a) for a in tools_string if a != '']
  3977. except Exception as e:
  3978. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3979. self.defaults['geometry_cnctooldia'] = ''
  3980. for t in range(len(tools_diameters)):
  3981. tools_diameters[t] *= sfactor
  3982. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  3983. elif dim == 'tools_ncctools':
  3984. ncctools = []
  3985. try:
  3986. tools_string = self.defaults["tools_ncctools"].split(",")
  3987. ncctools = [eval(a) for a in tools_string if a != '']
  3988. except Exception as e:
  3989. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3990. self.defaults['tools_ncctools'] = ''
  3991. for t in range(len(ncctools)):
  3992. ncctools[t] *= sfactor
  3993. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  3994. elif dim == 'tools_solderpaste_tools':
  3995. sptools = []
  3996. try:
  3997. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  3998. sptools = [eval(a) for a in tools_string if a != '']
  3999. except Exception as e:
  4000. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4001. self.defaults['tools_solderpaste_tools'] = ""
  4002. for t in range(len(sptools)):
  4003. sptools[t] *= sfactor
  4004. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  4005. elif dim == 'tools_solderpaste_xy_toolchange':
  4006. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4007. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4008. sp_coords[0] *= sfactor
  4009. sp_coords[1] *= sfactor
  4010. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  4011. elif dim == 'global_gridx' or dim == 'global_gridy':
  4012. if new_units == 'IN':
  4013. val = 0.1
  4014. try:
  4015. val = float(self.defaults[dim]) * sfactor
  4016. except Exception as e:
  4017. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4018. self.defaults[dim] = float('%.6f' % val)
  4019. else:
  4020. val = 0.1
  4021. try:
  4022. val = float(self.defaults[dim]) * sfactor
  4023. except Exception as e:
  4024. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4025. self.defaults[dim] = float('%.4f' % val)
  4026. else:
  4027. val = 0.1
  4028. try:
  4029. val = float(self.defaults[dim]) * sfactor
  4030. except Exception as e:
  4031. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4032. self.defaults[dim] = val
  4033. # The scaling factor depending on choice of units.
  4034. factor = 1/25.4
  4035. if new_units == 'MM':
  4036. factor = 25.4
  4037. # Changing project units. Warn user.
  4038. msgbox = QtWidgets.QMessageBox()
  4039. msgbox.setWindowTitle(_("Toggle Units"))
  4040. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  4041. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4042. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  4043. "properties of all objects to be scaled accordingly.\nContinue?"))
  4044. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4045. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4046. msgbox.setDefaultButton(bt_ok)
  4047. msgbox.exec_()
  4048. response = msgbox.clickedButton()
  4049. if response == bt_ok:
  4050. if no_pref is False:
  4051. self.options_read_form()
  4052. scale_options(factor)
  4053. self.options_write_form()
  4054. self.defaults_read_form()
  4055. scale_defaults(factor)
  4056. self.defaults_write_form(fl_units=new_units)
  4057. # save the defaults to file, some may assume that the conversion is enough and it's not
  4058. self.on_save_button()
  4059. self.should_we_save = True
  4060. # change this only if the workspace is active
  4061. if self.defaults['global_workspace'] is True:
  4062. self.plotcanvas.draw_workspace()
  4063. # adjust the grid values on the main toolbar
  4064. dec = 6 if new_units == 'IN'else 4
  4065. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  4066. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  4067. if not self.ui.grid_gap_link_cb.isChecked():
  4068. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  4069. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  4070. for obj in self.collection.get_list():
  4071. obj.convert_units(new_units)
  4072. # make that the properties stored in the object are also updated
  4073. self.object_changed.emit(obj)
  4074. obj.build_ui()
  4075. current = self.collection.get_active()
  4076. if current is not None:
  4077. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4078. if not isinstance(current, FlatCAMGeometry):
  4079. current.to_form()
  4080. self.plot_all()
  4081. self.inform.emit('[success] %s: %s' %
  4082. (_("Converted units to %s"), new_units))
  4083. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4084. self.set_screen_units(new_units)
  4085. else:
  4086. # Undo toggling
  4087. self.toggle_units_ignore = True
  4088. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4089. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4090. else:
  4091. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4092. self.toggle_units_ignore = False
  4093. self.inform.emit('[WARNING_NOTCL]%s' %
  4094. _(" Units conversion cancelled."))
  4095. self.options_read_form()
  4096. self.defaults_read_form()
  4097. def on_toggle_units_click(self):
  4098. try:
  4099. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4100. except (TypeError, AttributeError):
  4101. pass
  4102. if self.defaults["units"] == 'MM':
  4103. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4104. else:
  4105. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4106. self.on_toggle_units(no_pref=True)
  4107. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4108. lambda: self.on_toggle_units(no_pref=False))
  4109. def on_fullscreen(self):
  4110. self.report_usage("on_fullscreen()")
  4111. if self.toggle_fscreen is False:
  4112. if sys.platform == 'win32':
  4113. self.ui.showFullScreen()
  4114. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4115. tb.setVisible(False)
  4116. self.ui.splitter_left.setVisible(False)
  4117. self.toggle_fscreen = True
  4118. else:
  4119. if sys.platform == 'win32':
  4120. self.ui.showNormal()
  4121. self.restore_toolbar_view()
  4122. self.ui.splitter_left.setVisible(True)
  4123. self.toggle_fscreen = False
  4124. def on_toggle_plotarea(self):
  4125. self.report_usage("on_toggle_plotarea()")
  4126. try:
  4127. name = self.ui.plot_tab_area.widget(0).objectName()
  4128. except AttributeError:
  4129. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4130. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4131. self.ui.plot_tab_area.protectTab(0)
  4132. return
  4133. if name != 'plotarea':
  4134. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4135. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4136. self.ui.plot_tab_area.protectTab(0)
  4137. else:
  4138. self.ui.plot_tab_area.closeTab(0)
  4139. def on_toggle_notebook(self):
  4140. if self.ui.splitter.sizes()[0] == 0:
  4141. self.ui.splitter.setSizes([1, 1])
  4142. else:
  4143. self.ui.splitter.setSizes([0, 1])
  4144. def on_toggle_axis(self):
  4145. self.report_usage("on_toggle_axis()")
  4146. if self.toggle_axis is False:
  4147. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4148. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4149. self.plotcanvas.redraw()
  4150. self.toggle_axis = True
  4151. else:
  4152. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4153. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4154. self.plotcanvas.redraw()
  4155. self.toggle_axis = False
  4156. def on_toggle_grid(self):
  4157. self.report_usage("on_toggle_grid()")
  4158. self.ui.grid_snap_btn.trigger()
  4159. def on_options_combo_change(self, sel):
  4160. """
  4161. Called when the combo box to choose between application defaults and
  4162. project option changes value. The corresponding variables are
  4163. copied to the UI.
  4164. :param sel: The option index that was chosen.
  4165. :return: None
  4166. """
  4167. # combo_sel = self.ui.notebook.combo_options.get_active()
  4168. App.log.debug("Options --> %s" % sel)
  4169. # form = [self.defaults_form, self.options_form][sel]
  4170. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  4171. if sel == 0:
  4172. self.gen_form = self.ui.general_defaults_form
  4173. self.ger_form = self.ui.gerber_defaults_form
  4174. self.exc_form = self.ui.excellon_defaults_form
  4175. self.geo_form = self.ui.geometry_defaults_form
  4176. self.cnc_form = self.ui.cncjob_defaults_form
  4177. self.tools_form = self.ui.tools_defaults_form
  4178. self.fa_form = self.ui.fa_defaults_form
  4179. elif sel == 1:
  4180. self.gen_form = self.ui.general_options_form
  4181. self.ger_form = self.ui.gerber_options_form
  4182. self.exc_form = self.ui.excellon_options_form
  4183. self.geo_form = self.ui.geometry_options_form
  4184. self.cnc_form = self.ui.cncjob_options_form
  4185. self.tools_form = self.ui.tools_options_form
  4186. self.fa_form = self.ui.fa_options_form
  4187. else:
  4188. return
  4189. try:
  4190. self.ui.general_scroll_area.takeWidget()
  4191. except:
  4192. self.log.debug("Nothing to remove")
  4193. self.ui.general_scroll_area.setWidget(self.gen_form)
  4194. self.gen_form.show()
  4195. try:
  4196. self.ui.gerber_scroll_area.takeWidget()
  4197. except:
  4198. self.log.debug("Nothing to remove")
  4199. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  4200. self.ger_form.show()
  4201. try:
  4202. self.ui.excellon_scroll_area.takeWidget()
  4203. except:
  4204. self.log.debug("Nothing to remove")
  4205. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  4206. self.exc_form.show()
  4207. try:
  4208. self.ui.geometry_scroll_area.takeWidget()
  4209. except:
  4210. self.log.debug("Nothing to remove")
  4211. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  4212. self.geo_form.show()
  4213. try:
  4214. self.ui.cncjob_scroll_area.takeWidget()
  4215. except:
  4216. self.log.debug("Nothing to remove")
  4217. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  4218. self.cnc_form.show()
  4219. try:
  4220. self.ui.tools_scroll_area.takeWidget()
  4221. except:
  4222. self.log.debug("Nothing to remove")
  4223. self.ui.tools_scroll_area.setWidget(self.tools_form)
  4224. self.tools_form.show()
  4225. try:
  4226. self.ui.fa_scroll_area.takeWidget()
  4227. except:
  4228. self.log.debug("Nothing to remove")
  4229. self.ui.fa_scroll_area.setWidget(self.fa_form)
  4230. self.fa_form.show()
  4231. self.log.debug("Finished GUI form initialization.")
  4232. # self.options2form()
  4233. def on_excellon_defaults_button(self):
  4234. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  4235. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  4236. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  4237. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  4238. self.defaults_form_fields["excellon_zeros"].set_value('L')
  4239. self.defaults_form_fields["excellon_units"].set_value('INCH')
  4240. log.debug("Excellon app defaults loaded ...")
  4241. def on_excellon_options_button(self):
  4242. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  4243. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  4244. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  4245. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  4246. self.options_form_fields["excellon_zeros"].set_value('L')
  4247. self.options_form_fields["excellon_units"].set_value('INCH')
  4248. log.debug("Excellon options defaults loaded ...")
  4249. # Setting plot colors handlers
  4250. def on_pf_color_entry(self):
  4251. self.defaults['global_plot_fill'] = \
  4252. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  4253. self.defaults['global_plot_fill'][7:9]
  4254. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4255. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  4256. def on_pf_color_button(self):
  4257. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  4258. c_dialog = QtWidgets.QColorDialog()
  4259. plot_fill_color = c_dialog.getColor(initial=current_color)
  4260. if plot_fill_color.isValid() is False:
  4261. return
  4262. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4263. "background-color:%s" % str(plot_fill_color.name()))
  4264. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  4265. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  4266. self.defaults['global_plot_fill'] = new_val
  4267. def on_pf_color_spinner(self):
  4268. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  4269. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  4270. self.defaults['global_plot_fill'] = \
  4271. self.defaults['global_plot_fill'][:7] + \
  4272. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4273. self.defaults['global_plot_line'] = \
  4274. self.defaults['global_plot_line'][:7] + \
  4275. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4276. def on_pf_color_slider(self):
  4277. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  4278. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  4279. def on_pl_color_entry(self):
  4280. self.defaults['global_plot_line'] = \
  4281. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  4282. self.defaults['global_plot_line'][7:9]
  4283. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4284. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  4285. def on_pl_color_button(self):
  4286. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  4287. # print(current_color)
  4288. c_dialog = QtWidgets.QColorDialog()
  4289. plot_line_color = c_dialog.getColor(initial=current_color)
  4290. if plot_line_color.isValid() is False:
  4291. return
  4292. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4293. "background-color:%s" % str(plot_line_color.name()))
  4294. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  4295. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  4296. self.defaults['global_plot_line'] = new_val_line
  4297. # Setting selection colors (left - right) handlers
  4298. def on_sf_color_entry(self):
  4299. self.defaults['global_sel_fill'] = \
  4300. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  4301. self.defaults['global_sel_fill'][7:9]
  4302. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4303. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  4304. def on_sf_color_button(self):
  4305. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  4306. c_dialog = QtWidgets.QColorDialog()
  4307. plot_fill_color = c_dialog.getColor(initial=current_color)
  4308. if plot_fill_color.isValid() is False:
  4309. return
  4310. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4311. "background-color:%s" % str(plot_fill_color.name()))
  4312. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  4313. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  4314. self.defaults['global_sel_fill'] = new_val
  4315. def on_sf_color_spinner(self):
  4316. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  4317. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  4318. self.defaults['global_sel_fill'] = \
  4319. self.defaults['global_sel_fill'][:7] + \
  4320. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4321. self.defaults['global_sel_line'] = \
  4322. self.defaults['global_sel_line'][:7] + \
  4323. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4324. def on_sf_color_slider(self):
  4325. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  4326. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  4327. def on_sl_color_entry(self):
  4328. self.defaults['global_sel_line'] = \
  4329. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  4330. self.defaults['global_sel_line'][7:9]
  4331. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4332. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  4333. def on_sl_color_button(self):
  4334. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  4335. c_dialog = QtWidgets.QColorDialog()
  4336. plot_line_color = c_dialog.getColor(initial=current_color)
  4337. if plot_line_color.isValid() is False:
  4338. return
  4339. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4340. "background-color:%s" % str(plot_line_color.name()))
  4341. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  4342. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  4343. self.defaults['global_sel_line'] = new_val_line
  4344. # Setting selection colors (right - left) handlers
  4345. def on_alt_sf_color_entry(self):
  4346. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  4347. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  4348. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4349. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  4350. def on_alt_sf_color_button(self):
  4351. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  4352. c_dialog = QtWidgets.QColorDialog()
  4353. plot_fill_color = c_dialog.getColor(initial=current_color)
  4354. if plot_fill_color.isValid() is False:
  4355. return
  4356. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4357. "background-color:%s" % str(plot_fill_color.name()))
  4358. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  4359. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  4360. self.defaults['global_alt_sel_fill'] = new_val
  4361. def on_alt_sf_color_spinner(self):
  4362. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  4363. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  4364. self.defaults['global_alt_sel_fill'] = \
  4365. self.defaults['global_alt_sel_fill'][:7] + \
  4366. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4367. self.defaults['global_alt_sel_line'] = \
  4368. self.defaults['global_alt_sel_line'][:7] + \
  4369. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4370. def on_alt_sf_color_slider(self):
  4371. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  4372. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  4373. def on_alt_sl_color_entry(self):
  4374. self.defaults['global_alt_sel_line'] = \
  4375. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  4376. self.defaults['global_alt_sel_line'][7:9]
  4377. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  4378. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  4379. def on_alt_sl_color_button(self):
  4380. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  4381. c_dialog = QtWidgets.QColorDialog()
  4382. plot_line_color = c_dialog.getColor(initial=current_color)
  4383. if plot_line_color.isValid() is False:
  4384. return
  4385. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  4386. "background-color:%s" % str(plot_line_color.name()))
  4387. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  4388. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  4389. self.defaults['global_alt_sel_line'] = new_val_line
  4390. # Setting Editor colors
  4391. def on_draw_color_entry(self):
  4392. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  4393. .draw_color_entry.get_value()
  4394. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  4395. "background-color:%s" % str(self.defaults['global_draw_color']))
  4396. def on_draw_color_button(self):
  4397. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  4398. c_dialog = QtWidgets.QColorDialog()
  4399. draw_color = c_dialog.getColor(initial=current_color)
  4400. if draw_color.isValid() is False:
  4401. return
  4402. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  4403. "background-color:%s" % str(draw_color.name()))
  4404. new_val = str(draw_color.name())
  4405. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  4406. self.defaults['global_draw_color'] = new_val
  4407. def on_sel_draw_color_entry(self):
  4408. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  4409. .sel_draw_color_entry.get_value()
  4410. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  4411. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  4412. def on_sel_draw_color_button(self):
  4413. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  4414. c_dialog = QtWidgets.QColorDialog()
  4415. sel_draw_color = c_dialog.getColor(initial=current_color)
  4416. if sel_draw_color.isValid() is False:
  4417. return
  4418. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  4419. "background-color:%s" % str(sel_draw_color.name()))
  4420. new_val_sel = str(sel_draw_color.name())
  4421. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  4422. self.defaults['global_sel_draw_color'] = new_val_sel
  4423. def on_proj_color_entry(self):
  4424. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  4425. .proj_color_entry.get_value()
  4426. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  4427. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  4428. def on_proj_color_button(self):
  4429. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  4430. c_dialog = QtWidgets.QColorDialog()
  4431. proj_color = c_dialog.getColor(initial=current_color)
  4432. if proj_color.isValid() is False:
  4433. return
  4434. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  4435. "background-color:%s" % str(proj_color.name()))
  4436. new_val_sel = str(proj_color.name())
  4437. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  4438. self.defaults['global_proj_item_color'] = new_val_sel
  4439. def on_proj_color_dis_entry(self):
  4440. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  4441. .proj_color_dis_entry.get_value()
  4442. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  4443. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  4444. def on_proj_color_dis_button(self):
  4445. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  4446. c_dialog = QtWidgets.QColorDialog()
  4447. proj_color = c_dialog.getColor(initial=current_color)
  4448. if proj_color.isValid() is False:
  4449. return
  4450. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  4451. "background-color:%s" % str(proj_color.name()))
  4452. new_val_sel = str(proj_color.name())
  4453. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  4454. self.defaults['global_proj_item_dis_color'] = new_val_sel
  4455. def on_annotation_fontcolor_entry(self):
  4456. self.defaults['cncjob_annotation_fontcolor'] = \
  4457. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.get_value()
  4458. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  4459. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  4460. def on_annotation_fontcolor_button(self):
  4461. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  4462. c_dialog = QtWidgets.QColorDialog()
  4463. annotation_color = c_dialog.getColor(initial=current_color)
  4464. if annotation_color.isValid() is False:
  4465. return
  4466. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  4467. "background-color:%s" % str(annotation_color.name()))
  4468. new_val_sel = str(annotation_color.name())
  4469. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.set_value(new_val_sel)
  4470. self.defaults['global_proj_item_dis_color'] = new_val_sel
  4471. def on_notebook_tab_rmb_click(self, checked):
  4472. self.ui.notebook.set_detachable(val=checked)
  4473. self.defaults["global_tabs_detachable"] = checked
  4474. self.ui.plot_tab_area.set_detachable(val=checked)
  4475. self.defaults["global_tabs_detachable"] = checked
  4476. def on_deselect_all(self):
  4477. self.collection.set_all_inactive()
  4478. self.delete_selection_shape()
  4479. def on_workspace_modified(self):
  4480. self.save_defaults(silent=True)
  4481. self.plotcanvas.draw_workspace()
  4482. def on_workspace(self):
  4483. self.report_usage("on_workspace()")
  4484. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  4485. self.plotcanvas.restore_workspace()
  4486. else:
  4487. self.plotcanvas.delete_workspace()
  4488. self.save_defaults(silent=True)
  4489. def on_workspace_menu(self):
  4490. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  4491. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  4492. else:
  4493. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  4494. self.on_workspace()
  4495. def on_layout(self, index=None, lay=None):
  4496. self.report_usage("on_layout()")
  4497. if lay:
  4498. current_layout = lay
  4499. else:
  4500. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  4501. settings = QSettings("Open Source", "FlatCAM")
  4502. settings.setValue('layout', current_layout)
  4503. # This will write the setting to the platform specific storage.
  4504. del settings
  4505. # first remove the toolbars:
  4506. try:
  4507. self.ui.removeToolBar(self.ui.toolbarfile)
  4508. self.ui.removeToolBar(self.ui.toolbargeo)
  4509. self.ui.removeToolBar(self.ui.toolbarview)
  4510. self.ui.removeToolBar(self.ui.toolbarshell)
  4511. self.ui.removeToolBar(self.ui.toolbartools)
  4512. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  4513. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  4514. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  4515. self.ui.removeToolBar(self.ui.snap_toolbar)
  4516. self.ui.removeToolBar(self.ui.toolbarshell)
  4517. except Exception as e:
  4518. pass
  4519. if current_layout == 'standard':
  4520. # ## TOOLBAR INSTALLATION # ##
  4521. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  4522. self.ui.toolbarfile.setObjectName('File_TB')
  4523. self.ui.addToolBar(self.ui.toolbarfile)
  4524. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  4525. self.ui.toolbargeo.setObjectName('Edit_TB')
  4526. self.ui.addToolBar(self.ui.toolbargeo)
  4527. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  4528. self.ui.toolbarview.setObjectName('View_TB')
  4529. self.ui.addToolBar(self.ui.toolbarview)
  4530. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  4531. self.ui.toolbarshell.setObjectName('Shell_TB')
  4532. self.ui.addToolBar(self.ui.toolbarshell)
  4533. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  4534. self.ui.toolbartools.setObjectName('Tools_TB')
  4535. self.ui.addToolBar(self.ui.toolbartools)
  4536. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  4537. self.ui.exc_edit_toolbar.setVisible(False)
  4538. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  4539. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  4540. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  4541. self.ui.geo_edit_toolbar.setVisible(False)
  4542. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  4543. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  4544. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  4545. self.ui.grb_edit_toolbar.setVisible(False)
  4546. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  4547. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  4548. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  4549. self.ui.snap_toolbar.setObjectName('Snap_TB')
  4550. # self.ui.snap_toolbar.setMaximumHeight(30)
  4551. self.ui.addToolBar(self.ui.snap_toolbar)
  4552. self.ui.corner_snap_btn.setVisible(False)
  4553. self.ui.snap_magnet.setVisible(False)
  4554. elif current_layout == 'compact':
  4555. # ## TOOLBAR INSTALLATION # ##
  4556. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  4557. self.ui.toolbarfile.setObjectName('File_TB')
  4558. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  4559. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  4560. self.ui.toolbargeo.setObjectName('Edit_TB')
  4561. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  4562. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  4563. self.ui.toolbarview.setObjectName('View_TB')
  4564. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarview)
  4565. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  4566. self.ui.toolbarshell.setObjectName('Shell_TB')
  4567. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  4568. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  4569. self.ui.toolbartools.setObjectName('Tools_TB')
  4570. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  4571. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  4572. # self.ui.geo_edit_toolbar.setVisible(False)
  4573. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  4574. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  4575. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  4576. # self.ui.grb_edit_toolbar.setVisible(False)
  4577. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  4578. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  4579. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  4580. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  4581. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  4582. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  4583. self.ui.snap_toolbar.setObjectName('Snap_TB')
  4584. self.ui.snap_toolbar.setMaximumHeight(30)
  4585. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  4586. self.ui.corner_snap_btn.setVisible(True)
  4587. self.ui.snap_magnet.setVisible(True)
  4588. # add all the actions to the toolbars
  4589. self.ui.populate_toolbars()
  4590. # reconnect all the signals to the toolbar actions
  4591. self.connect_toolbar_signals()
  4592. self.ui.grid_snap_btn.setChecked(True)
  4593. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  4594. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  4595. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  4596. self.ui.grid_gap_link_cb.setChecked(True)
  4597. def on_cnc_custom_parameters(self, signal_text):
  4598. if signal_text == 'Parameters':
  4599. return
  4600. else:
  4601. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  4602. def on_save_button(self):
  4603. log.debug("App.on_save_button() --> Saving preferences to file.")
  4604. self.preferences_changed_flag = False
  4605. self.save_defaults(silent=False)
  4606. # load the defaults so they are updated into the app
  4607. self.load_defaults(filename='current_defaults')
  4608. # Re-fresh project options
  4609. self.on_options_app2project()
  4610. # save the notebook font size
  4611. settings = QSettings("Open Source", "FlatCAM")
  4612. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  4613. settings.setValue('notebook_font_size', fsize)
  4614. # save the axis font size
  4615. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  4616. settings.setValue('axis_font_size', g_fsize)
  4617. # This will write the setting to the platform specific storage.
  4618. del settings
  4619. def handlePrint(self):
  4620. self.report_usage("handlePrint()")
  4621. dialog = QtPrintSupport.QPrintDialog()
  4622. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  4623. self.ui.code_editor.document().print_(dialog.printer())
  4624. def handlePreview(self):
  4625. self.report_usage("handlePreview()")
  4626. dialog = QtPrintSupport.QPrintPreviewDialog()
  4627. dialog.paintRequested.connect(self.ui.code_editor.print_)
  4628. dialog.exec_()
  4629. def handleTextChanged(self):
  4630. # enable = not self.ui.code_editor.document().isEmpty()
  4631. # self.ui.buttonPrint.setEnabled(enable)
  4632. # self.ui.buttonPreview.setEnabled(enable)
  4633. pass
  4634. def handleOpen(self, filt=None):
  4635. self.report_usage("handleOpen()")
  4636. if filt:
  4637. _filter_ = filt
  4638. else:
  4639. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  4640. "All Files (*.*)"
  4641. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  4642. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  4643. if path:
  4644. file = QtCore.QFile(path)
  4645. if file.open(QtCore.QIODevice.ReadOnly):
  4646. stream = QtCore.QTextStream(file)
  4647. self.gcode_edited = stream.readAll()
  4648. self.ui.code_editor.setPlainText(self.gcode_edited)
  4649. file.close()
  4650. def handleSaveGCode(self, name=None, filt=None):
  4651. self.report_usage("handleSaveGCode()")
  4652. if filt:
  4653. _filter_ = filt
  4654. else:
  4655. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  4656. "All Files (*.*)"
  4657. if name:
  4658. obj_name = name
  4659. else:
  4660. try:
  4661. obj_name = self.collection.get_active().options['name']
  4662. except AttributeError:
  4663. obj_name = 'file'
  4664. if filt is None:
  4665. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  4666. try:
  4667. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  4668. caption=_("Export G-Code ..."),
  4669. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  4670. filter=_filter_
  4671. )[0])
  4672. except TypeError:
  4673. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  4674. if filename == "":
  4675. self.inform.emit('[WARNING_NOTCL] %s' %
  4676. _("Export Code cancelled."))
  4677. return
  4678. else:
  4679. try:
  4680. my_gcode = self.ui.code_editor.toPlainText()
  4681. with open(filename, 'w') as f:
  4682. for line in my_gcode:
  4683. f.write(line)
  4684. except FileNotFoundError:
  4685. self.inform.emit('[WARNING] %s' %
  4686. _("No such file or directory"))
  4687. return
  4688. except PermissionError:
  4689. self.inform.emit('[WARNING] %s' %
  4690. _("Permission denied, saving not possible.\n"
  4691. "Most likely another app is holding the file open and not accessible."))
  4692. return
  4693. # Just for adding it to the recent files list.
  4694. if self.defaults["global_open_style"] is False:
  4695. self.file_opened.emit("cncjob", filename)
  4696. self.file_saved.emit("cncjob", filename)
  4697. self.inform.emit(_("Saved to: %s") % filename)
  4698. def handleFindGCode(self):
  4699. self.report_usage("handleFindGCode()")
  4700. flags = QtGui.QTextDocument.FindCaseSensitively
  4701. text_to_be_found = self.ui.entryFind.get_value()
  4702. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  4703. if r is False:
  4704. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4705. def handleReplaceGCode(self):
  4706. self.report_usage("handleReplaceGCode()")
  4707. old = self.ui.entryFind.get_value()
  4708. new = self.ui.entryReplace.get_value()
  4709. if self.ui.sel_all_cb.isChecked():
  4710. while True:
  4711. cursor = self.ui.code_editor.textCursor()
  4712. cursor.beginEditBlock()
  4713. flags = QtGui.QTextDocument.FindCaseSensitively
  4714. # self.ui.editor is the QPlainTextEdit
  4715. r = self.ui.code_editor.find(str(old), flags)
  4716. if r:
  4717. qc = self.ui.code_editor.textCursor()
  4718. if qc.hasSelection():
  4719. qc.insertText(new)
  4720. else:
  4721. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4722. break
  4723. # Mark end of undo block
  4724. cursor.endEditBlock()
  4725. else:
  4726. cursor = self.ui.code_editor.textCursor()
  4727. cursor.beginEditBlock()
  4728. qc = self.ui.code_editor.textCursor()
  4729. if qc.hasSelection():
  4730. qc.insertText(new)
  4731. # Mark end of undo block
  4732. cursor.endEditBlock()
  4733. def on_tool_add_keypress(self):
  4734. # ## Current application units in Upper Case
  4735. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4736. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4737. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4738. if notebook_widget_name == 'selected_tab':
  4739. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  4740. # Tool add works for Geometry only if Advanced is True in Preferences
  4741. if self.defaults["global_app_level"] == 'a':
  4742. tool_add_popup = FCInputDialog(title="New Tool ...",
  4743. text='Enter a Tool Diameter:',
  4744. min=0.0000, max=99.9999, decimals=4)
  4745. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  4746. val, ok = tool_add_popup.get_value()
  4747. if ok:
  4748. if float(val) == 0:
  4749. self.inform.emit('[WARNING_NOTCL] %s' %
  4750. _("Please enter a tool diameter with non-zero value, in Float format."))
  4751. return
  4752. self.collection.get_active().on_tool_add(dia=float(val))
  4753. else:
  4754. self.inform.emit('[WARNING_NOTCL] %s...' %
  4755. _("Adding Tool cancelled"))
  4756. else:
  4757. msgbox = QtWidgets.QMessageBox()
  4758. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  4759. "Go to Preferences -> General - Show Advanced Options."))
  4760. msgbox.setWindowTitle("Tool adding ...")
  4761. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  4762. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4763. msgbox.setDefaultButton(bt_ok)
  4764. msgbox.exec_()
  4765. # work only if the notebook tab on focus is the Tools_Tab
  4766. if notebook_widget_name == 'tool_tab':
  4767. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4768. tool_add_popup = FCInputDialog(title="New Tool ...",
  4769. text='Enter a Tool Diameter:',
  4770. min=0.0000, max=99.9999, decimals=4)
  4771. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  4772. val, ok = tool_add_popup.get_value()
  4773. # and only if the tool is NCC Tool
  4774. if tool_widget == self.ncclear_tool.toolName:
  4775. if ok:
  4776. if float(val) == 0:
  4777. self.inform.emit('[WARNING_NOTCL] %s' %
  4778. _("Please enter a tool diameter with non-zero value, in Float format."))
  4779. return
  4780. self.ncclear_tool.on_tool_add(dia=float(val))
  4781. else:
  4782. self.inform.emit('[WARNING_NOTCL] %s...' %
  4783. _("Adding Tool cancelled"))
  4784. # and only if the tool is Paint Area Tool
  4785. elif tool_widget == self.paint_tool.toolName:
  4786. if ok:
  4787. if float(val) == 0:
  4788. self.inform.emit('[WARNING_NOTCL] %s' %
  4789. _("Please enter a tool diameter with non-zero value, in Float format."))
  4790. return
  4791. self.paint_tool.on_tool_add(dia=float(val))
  4792. else:
  4793. self.inform.emit(
  4794. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  4795. # and only if the tool is Solder Paste Dispensing Tool
  4796. elif tool_widget == self.paste_tool.toolName:
  4797. if ok:
  4798. if float(val) == 0:
  4799. self.inform.emit('[WARNING_NOTCL] %s' %
  4800. _("Please enter a tool diameter with non-zero value, in Float format."))
  4801. return
  4802. self.paste_tool.on_tool_add(dia=float(val))
  4803. else:
  4804. self.inform.emit('[WARNING_NOTCL] %s...' %
  4805. _("Adding Tool cancelled"))
  4806. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  4807. # See description bellow.
  4808. def on_delete_keypress(self):
  4809. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4810. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4811. if notebook_widget_name == 'selected_tab':
  4812. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  4813. self.collection.get_active().on_tool_delete()
  4814. # work only if the notebook tab on focus is the Tools_Tab
  4815. elif notebook_widget_name == 'tool_tab':
  4816. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4817. # and only if the tool is NCC Tool
  4818. if tool_widget == self.ncclear_tool.toolName:
  4819. self.ncclear_tool.on_tool_delete()
  4820. # and only if the tool is Paint Tool
  4821. elif tool_widget == self.paint_tool.toolName:
  4822. self.paint_tool.on_tool_delete()
  4823. # and only if the tool is Solder Paste Dispensing Tool
  4824. elif tool_widget == self.paste_tool.toolName:
  4825. self.paste_tool.on_tool_delete()
  4826. else:
  4827. self.on_delete()
  4828. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  4829. # some screens you have to be careful where you hover with your mouse.
  4830. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  4831. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  4832. # Complicated, I know :)
  4833. def on_delete(self):
  4834. """
  4835. Delete the currently selected FlatCAMObjs.
  4836. :return: None
  4837. """
  4838. self.report_usage("on_delete()")
  4839. response = None
  4840. bt_ok = None
  4841. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  4842. # a geometry object before we update it.
  4843. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  4844. and self.grb_editor.editor_active is False:
  4845. if self.defaults["global_delete_confirmation"] is True:
  4846. msgbox = QtWidgets.QMessageBox()
  4847. msgbox.setWindowTitle(_("Delete objects"))
  4848. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  4849. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4850. msgbox.setText(_("Are you sure you want to permanently delete\n"
  4851. "the selected objects?"))
  4852. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4853. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4854. msgbox.setDefaultButton(bt_ok)
  4855. msgbox.exec_()
  4856. response = msgbox.clickedButton()
  4857. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  4858. if self.collection.get_active():
  4859. self.log.debug("App.on_delete()")
  4860. while self.collection.get_active():
  4861. obj_active = self.collection.get_active()
  4862. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  4863. if isinstance(obj_active, FlatCAMGerber):
  4864. for el in obj_active.mark_shapes:
  4865. obj_active.mark_shapes[el].clear(update=True)
  4866. obj_active.mark_shapes[el].enabled = False
  4867. # obj_active.mark_shapes[el] = None
  4868. del el
  4869. elif isinstance(obj_active, FlatCAMCNCjob):
  4870. try:
  4871. obj_active.annotation.clear(update=True)
  4872. obj_active.annotation.enabled = False
  4873. except AttributeError:
  4874. pass
  4875. self.delete_first_selected()
  4876. self.inform.emit('%s...' %
  4877. _("Object(s) deleted"))
  4878. # make sure that the selection shape is deleted, too
  4879. self.delete_selection_shape()
  4880. else:
  4881. self.inform.emit(_("Failed. No object(s) selected..."))
  4882. else:
  4883. self.inform.emit(_("Save the work in Editor and try again ..."))
  4884. def delete_first_selected(self):
  4885. # Keep this for later
  4886. try:
  4887. sel_obj = self.collection.get_active()
  4888. name = sel_obj.options["name"]
  4889. except AttributeError:
  4890. self.log.debug("Nothing selected for deletion")
  4891. return
  4892. # Remove from dictionary
  4893. self.collection.delete_active()
  4894. # Clear form
  4895. self.setup_component_editor()
  4896. self.inform.emit('%s: %s' %
  4897. (_("Object deleted"), name))
  4898. def on_set_origin(self):
  4899. """
  4900. Set the origin to the left mouse click position
  4901. :return: None
  4902. """
  4903. # display the message for the user
  4904. # and ask him to click on the desired position
  4905. self.report_usage("on_set_origin()")
  4906. def origin_replot():
  4907. def worker_task():
  4908. with self.proc_container.new('%s...' % _("Plotting")):
  4909. for obj in self.collection.get_list():
  4910. obj.plot()
  4911. self.plotcanvas.fit_view()
  4912. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  4913. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4914. self.inform.emit(_('Click to set the origin ...'))
  4915. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  4916. # first disconnect it as it may have been used by something else
  4917. try:
  4918. self.replot_signal.disconnect()
  4919. except TypeError:
  4920. pass
  4921. self.replot_signal[list].connect(origin_replot)
  4922. def on_set_zero_click(self, event):
  4923. # this function will be available only for mouse left click
  4924. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  4925. if event.button == 1:
  4926. if self.grid_status() == True:
  4927. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4928. else:
  4929. pos = pos_canvas
  4930. x = 0 - pos[0]
  4931. y = 0 - pos[1]
  4932. def worker_task():
  4933. with self.proc_container.new(_("Setting Origin...")):
  4934. for obj in self.collection.get_list():
  4935. obj.offset((x, y))
  4936. self.object_changed.emit(obj)
  4937. # Update the object bounding box options
  4938. a, b, c, d = obj.bounds()
  4939. obj.options['xmin'] = a
  4940. obj.options['ymin'] = b
  4941. obj.options['xmax'] = c
  4942. obj.options['ymax'] = d
  4943. self.inform.emit('[success]%s...' %
  4944. _('Origin set'))
  4945. self.replot_signal.emit([])
  4946. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4947. self.should_we_save = True
  4948. def on_jump_to(self, custom_location=None, fit_center=True):
  4949. """
  4950. Jump to a location by setting the mouse cursor location
  4951. :return:
  4952. """
  4953. self.report_usage("on_jump_to()")
  4954. if not custom_location:
  4955. dia_box = Dialog_box(title=_("Jump to ..."),
  4956. label=_("Enter the coordinates in format X,Y:"),
  4957. icon=QtGui.QIcon('share/jump_to16.png'))
  4958. if dia_box.ok is True:
  4959. try:
  4960. location = eval(dia_box.location)
  4961. if not isinstance(location, tuple):
  4962. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  4963. return
  4964. except:
  4965. return
  4966. else:
  4967. return
  4968. else:
  4969. location = custom_location
  4970. if fit_center:
  4971. self.plotcanvas.fit_center(loc=location)
  4972. cursor = QtGui.QCursor()
  4973. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4974. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  4975. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  4976. self.inform.emit('[success] %s' %
  4977. _("Done."))
  4978. return location
  4979. def on_copy_object(self):
  4980. self.report_usage("on_copy_object()")
  4981. def initialize(obj_init, app):
  4982. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4983. try:
  4984. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4985. except AttributeError:
  4986. pass
  4987. try:
  4988. obj_init.apertures = deepcopy(obj.apertures)
  4989. except AttributeError:
  4990. pass
  4991. try:
  4992. if obj.tools:
  4993. obj_init.tools = deepcopy(obj.tools)
  4994. except Exception as e:
  4995. log.debug("App.on_copy_object() --> %s" % str(e))
  4996. def initialize_excellon(obj_init, app):
  4997. obj_init.tools = deepcopy(obj.tools)
  4998. # drills are offset, so they need to be deep copied
  4999. obj_init.drills = deepcopy(obj.drills)
  5000. # slots are offset, so they need to be deep copied
  5001. obj_init.slots = deepcopy(obj.slots)
  5002. obj_init.create_geometry()
  5003. for obj in self.collection.get_selected():
  5004. obj_name = obj.options["name"]
  5005. try:
  5006. if isinstance(obj, FlatCAMExcellon):
  5007. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  5008. elif isinstance(obj, FlatCAMGerber):
  5009. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  5010. elif isinstance(obj, FlatCAMGeometry):
  5011. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  5012. except Exception as e:
  5013. return "Operation failed: %s" % str(e)
  5014. def on_copy_object2(self, custom_name):
  5015. def initialize_geometry(obj_init, app):
  5016. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5017. try:
  5018. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5019. except AttributeError:
  5020. pass
  5021. try:
  5022. obj_init.apertures = deepcopy(obj.apertures)
  5023. except AttributeError:
  5024. pass
  5025. try:
  5026. if obj.tools:
  5027. obj_init.tools = deepcopy(obj.tools)
  5028. except Exception as e:
  5029. log.debug("on_copy_object2() --> %s" % str(e))
  5030. def initialize_gerber(obj_init, app):
  5031. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5032. obj_init.apertures = deepcopy(obj.apertures)
  5033. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  5034. def initialize_excellon(obj_init, app):
  5035. obj_init.tools = deepcopy(obj.tools)
  5036. # drills are offset, so they need to be deep copied
  5037. obj_init.drills = deepcopy(obj.drills)
  5038. # slots are offset, so they need to be deep copied
  5039. obj_init.slots = deepcopy(obj.slots)
  5040. obj_init.create_geometry()
  5041. for obj in self.collection.get_selected():
  5042. obj_name = obj.options["name"]
  5043. try:
  5044. if isinstance(obj, FlatCAMExcellon):
  5045. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  5046. elif isinstance(obj, FlatCAMGerber):
  5047. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  5048. elif isinstance(obj, FlatCAMGeometry):
  5049. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  5050. except Exception as e:
  5051. return "Operation failed: %s" % str(e)
  5052. def on_rename_object(self, text):
  5053. self.report_usage("on_rename_object()")
  5054. named_obj = self.collection.get_active()
  5055. for obj in named_obj:
  5056. if obj is list:
  5057. self.on_rename_object(text)
  5058. else:
  5059. try:
  5060. obj.options['name'] = text
  5061. except Exception as e:
  5062. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  5063. def convert_any2geo(self):
  5064. self.report_usage("convert_any2geo()")
  5065. def initialize(obj_init, app):
  5066. obj_init.solid_geometry = obj.solid_geometry
  5067. try:
  5068. obj_init.follow_geometry = obj.follow_geometry
  5069. except AttributeError:
  5070. pass
  5071. try:
  5072. obj_init.apertures = obj.apertures
  5073. except AttributeError:
  5074. pass
  5075. try:
  5076. if obj.tools:
  5077. obj_init.tools = obj.tools
  5078. except AttributeError:
  5079. pass
  5080. def initialize_excellon(obj_init, app):
  5081. # objs = self.collection.get_selected()
  5082. # FlatCAMGeometry.merge(objs, obj)
  5083. solid_geo = []
  5084. for tool in obj.tools:
  5085. for geo in obj.tools[tool]['solid_geometry']:
  5086. solid_geo.append(geo)
  5087. obj_init.solid_geometry = deepcopy(solid_geo)
  5088. if not self.collection.get_selected():
  5089. log.warning("App.convert_any2geo --> No object selected")
  5090. self.inform.emit('[WARNING_NOTCL] %s' %
  5091. _("No object is selected. Select an object and try again."))
  5092. return
  5093. for obj in self.collection.get_selected():
  5094. obj_name = obj.options["name"]
  5095. try:
  5096. if isinstance(obj, FlatCAMExcellon):
  5097. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  5098. else:
  5099. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  5100. except Exception as e:
  5101. return "Operation failed: %s" % str(e)
  5102. def convert_any2gerber(self):
  5103. self.report_usage("convert_any2gerber()")
  5104. def initialize_geometry(obj_init, app):
  5105. apertures = {}
  5106. apid = 0
  5107. apertures[str(apid)] = {}
  5108. apertures[str(apid)]['geometry'] = []
  5109. for obj_orig in obj.solid_geometry:
  5110. new_elem = dict()
  5111. new_elem['solid'] = obj_orig
  5112. new_elem['follow'] = obj_orig.exterior
  5113. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  5114. apertures[str(apid)]['size'] = 0.0
  5115. apertures[str(apid)]['type'] = 'C'
  5116. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5117. obj_init.apertures = deepcopy(apertures)
  5118. def initialize_excellon(obj_init, app):
  5119. apertures = {}
  5120. apid = 10
  5121. for tool in obj.tools:
  5122. apertures[str(apid)] = {}
  5123. apertures[str(apid)]['geometry'] = []
  5124. for geo in obj.tools[tool]['solid_geometry']:
  5125. new_el = dict()
  5126. new_el['solid'] = geo
  5127. new_el['follow'] = geo.exterior
  5128. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  5129. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  5130. apertures[str(apid)]['type'] = 'C'
  5131. apid += 1
  5132. # create solid_geometry
  5133. solid_geometry = []
  5134. for apid in apertures:
  5135. for geo_el in apertures[apid]['geometry']:
  5136. solid_geometry.append(geo_el['solid'])
  5137. solid_geometry = MultiPolygon(solid_geometry)
  5138. solid_geometry = solid_geometry.buffer(0.0000001)
  5139. obj_init.solid_geometry = deepcopy(solid_geometry)
  5140. obj_init.apertures = deepcopy(apertures)
  5141. # clear the working objects (perhaps not necessary due of Python GC)
  5142. apertures.clear()
  5143. if not self.collection.get_selected():
  5144. log.warning("App.convert_any2gerber --> No object selected")
  5145. self.inform.emit('[WARNING_NOTCL] %s' %
  5146. _("No object is selected. Select an object and try again."))
  5147. return
  5148. for obj in self.collection.get_selected():
  5149. obj_name = obj.options["name"]
  5150. try:
  5151. if isinstance(obj, FlatCAMExcellon):
  5152. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  5153. elif isinstance(obj, FlatCAMGeometry):
  5154. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  5155. else:
  5156. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  5157. except Exception as e:
  5158. return "Operation failed: %s" % str(e)
  5159. def abort_all_tasks(self):
  5160. if self.abort_flag is False:
  5161. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  5162. self.abort_flag = True
  5163. def app_is_idle(self):
  5164. if self.abort_flag:
  5165. self.inform.emit('[WARNING_NOTCL] %s' %
  5166. _("The current task was gracefully closed on user request..."))
  5167. self.abort_flag = False
  5168. def on_selectall(self):
  5169. self.report_usage("on_selectall()")
  5170. # delete the possible selection box around a possible selected object
  5171. self.delete_selection_shape()
  5172. for name in self.collection.get_names():
  5173. self.collection.set_active(name)
  5174. curr_sel_obj = self.collection.get_by_name(name)
  5175. # create the selection box around the selected object
  5176. if self.defaults['global_selection_shape'] is True:
  5177. self.draw_selection_shape(curr_sel_obj)
  5178. def on_preferences(self):
  5179. # add the tab if it was closed
  5180. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  5181. # delete the absolute and relative position and messages in the infobar
  5182. self.ui.position_label.setText("")
  5183. self.ui.rel_position_label.setText("")
  5184. # Switch plot_area to preferences page
  5185. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  5186. self.ui.show()
  5187. # this disconnect() is done so the slot will be connected only once
  5188. try:
  5189. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_preferences_closed)
  5190. except (TypeError, AttributeError):
  5191. pass
  5192. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_preferences_closed)
  5193. # detect changes in the preferences
  5194. for idx in range(self.ui.pref_tab_area.count()):
  5195. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5196. try:
  5197. try:
  5198. tb.textEdited.disconnect(self.on_preferences_edited)
  5199. except (TypeError, AttributeError):
  5200. pass
  5201. tb.textEdited.connect(self.on_preferences_edited)
  5202. except AttributeError:
  5203. pass
  5204. try:
  5205. try:
  5206. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5207. except (TypeError, AttributeError):
  5208. pass
  5209. tb.modificationChanged.connect(self.on_preferences_edited)
  5210. except AttributeError:
  5211. pass
  5212. try:
  5213. try:
  5214. tb.toggled.disconnect(self.on_preferences_edited)
  5215. except (TypeError, AttributeError):
  5216. pass
  5217. tb.toggled.connect(self.on_preferences_edited)
  5218. except AttributeError:
  5219. pass
  5220. try:
  5221. try:
  5222. tb.valueChanged.disconnect(self.on_preferences_edited)
  5223. except (TypeError, AttributeError):
  5224. pass
  5225. tb.valueChanged.connect(self.on_preferences_edited)
  5226. except AttributeError:
  5227. pass
  5228. try:
  5229. try:
  5230. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5231. except (TypeError, AttributeError):
  5232. pass
  5233. tb.currentIndexChanged.connect(self.on_preferences_edited)
  5234. except AttributeError:
  5235. pass
  5236. def on_preferences_edited(self):
  5237. self.inform.emit('[WARNING_NOTCL] %s' %
  5238. _("Preferences edited but not saved."))
  5239. self.preferences_changed_flag = True
  5240. def on_preferences_closed(self):
  5241. # disconnect
  5242. for idx in range(self.ui.pref_tab_area.count()):
  5243. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5244. try:
  5245. tb.textEdited.disconnect(self.on_preferences_edited)
  5246. except (TypeError, AttributeError):
  5247. pass
  5248. try:
  5249. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5250. except (TypeError, AttributeError):
  5251. pass
  5252. try:
  5253. tb.toggled.disconnect(self.on_preferences_edited)
  5254. except (TypeError, AttributeError):
  5255. pass
  5256. try:
  5257. tb.valueChanged.disconnect(self.on_preferences_edited)
  5258. except (TypeError, AttributeError):
  5259. pass
  5260. try:
  5261. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5262. except (TypeError, AttributeError):
  5263. pass
  5264. if self.preferences_changed_flag is True:
  5265. msgbox = QtWidgets.QMessageBox()
  5266. msgbox.setText(_("One or more values are changed.\n"
  5267. "Do you want to save the Preferences?"))
  5268. msgbox.setWindowTitle(_("Save Preferences"))
  5269. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  5270. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5271. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5272. msgbox.setDefaultButton(bt_yes)
  5273. msgbox.exec_()
  5274. response = msgbox.clickedButton()
  5275. if response == bt_yes:
  5276. self.on_save_button()
  5277. self.inform.emit('[success] %s' %
  5278. _("Preferences saved."))
  5279. else:
  5280. self.preferences_changed_flag = False
  5281. return
  5282. def on_flipy(self):
  5283. self.report_usage("on_flipy()")
  5284. obj_list = self.collection.get_selected()
  5285. xminlist = []
  5286. yminlist = []
  5287. xmaxlist = []
  5288. ymaxlist = []
  5289. if not obj_list:
  5290. self.inform.emit('[WARNING_NOTCL] %s' %
  5291. _("No object selected to Flip on Y axis."))
  5292. else:
  5293. try:
  5294. # first get a bounding box to fit all
  5295. for obj in obj_list:
  5296. xmin, ymin, xmax, ymax = obj.bounds()
  5297. xminlist.append(xmin)
  5298. yminlist.append(ymin)
  5299. xmaxlist.append(xmax)
  5300. ymaxlist.append(ymax)
  5301. # get the minimum x,y and maximum x,y for all objects selected
  5302. xminimal = min(xminlist)
  5303. yminimal = min(yminlist)
  5304. xmaximal = max(xmaxlist)
  5305. ymaximal = max(ymaxlist)
  5306. px = 0.5 * (xminimal + xmaximal)
  5307. py = 0.5 * (yminimal + ymaximal)
  5308. # execute mirroring
  5309. for obj in obj_list:
  5310. obj.mirror('X', [px, py])
  5311. obj.plot()
  5312. self.object_changed.emit(obj)
  5313. self.inform.emit('[success] %s' %
  5314. _("Flip on Y axis done."))
  5315. except Exception as e:
  5316. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  5317. (_("Flip action was not executed."), str(e)))
  5318. return
  5319. def on_flipx(self):
  5320. self.report_usage("on_flipx()")
  5321. obj_list = self.collection.get_selected()
  5322. xminlist = []
  5323. yminlist = []
  5324. xmaxlist = []
  5325. ymaxlist = []
  5326. if not obj_list:
  5327. self.inform.emit('[WARNING_NOTCL] %s' %
  5328. _("No object selected to Flip on X axis."))
  5329. else:
  5330. try:
  5331. # first get a bounding box to fit all
  5332. for obj in obj_list:
  5333. xmin, ymin, xmax, ymax = obj.bounds()
  5334. xminlist.append(xmin)
  5335. yminlist.append(ymin)
  5336. xmaxlist.append(xmax)
  5337. ymaxlist.append(ymax)
  5338. # get the minimum x,y and maximum x,y for all objects selected
  5339. xminimal = min(xminlist)
  5340. yminimal = min(yminlist)
  5341. xmaximal = max(xmaxlist)
  5342. ymaximal = max(ymaxlist)
  5343. px = 0.5 * (xminimal + xmaximal)
  5344. py = 0.5 * (yminimal + ymaximal)
  5345. # execute mirroring
  5346. for obj in obj_list:
  5347. obj.mirror('Y', [px, py])
  5348. obj.plot()
  5349. self.object_changed.emit(obj)
  5350. self.inform.emit('[success] %s' %
  5351. _("Flip on X axis done."))
  5352. except Exception as e:
  5353. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  5354. (_("Flip action was not executed."), str(e)))
  5355. return
  5356. def on_rotate(self, silent=False, preset=None):
  5357. self.report_usage("on_rotate()")
  5358. obj_list = self.collection.get_selected()
  5359. xminlist = []
  5360. yminlist = []
  5361. xmaxlist = []
  5362. ymaxlist = []
  5363. if not obj_list:
  5364. self.inform.emit('[WARNING_NOTCL] %s' %
  5365. _("No object selected to Rotate."))
  5366. else:
  5367. if silent is False:
  5368. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5369. min=-360, max=360, decimals=4,
  5370. init_val=float(self.defaults['tools_transform_rotate']))
  5371. num, ok = rotatebox.get_value()
  5372. else:
  5373. num = preset
  5374. ok = True
  5375. if ok:
  5376. try:
  5377. # first get a bounding box to fit all
  5378. for obj in obj_list:
  5379. xmin, ymin, xmax, ymax = obj.bounds()
  5380. xminlist.append(xmin)
  5381. yminlist.append(ymin)
  5382. xmaxlist.append(xmax)
  5383. ymaxlist.append(ymax)
  5384. # get the minimum x,y and maximum x,y for all objects selected
  5385. xminimal = min(xminlist)
  5386. yminimal = min(yminlist)
  5387. xmaximal = max(xmaxlist)
  5388. ymaximal = max(ymaxlist)
  5389. px = 0.5 * (xminimal + xmaximal)
  5390. py = 0.5 * (yminimal + ymaximal)
  5391. for sel_obj in obj_list:
  5392. sel_obj.rotate(-float(num), point=(px, py))
  5393. sel_obj.plot()
  5394. self.object_changed.emit(sel_obj)
  5395. self.inform.emit('[success] %s' %
  5396. _("Rotation done."))
  5397. except Exception as e:
  5398. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  5399. (_("Rotation movement was not executed."), str(e)))
  5400. return
  5401. def on_skewx(self):
  5402. self.report_usage("on_skewx()")
  5403. obj_list = self.collection.get_selected()
  5404. xminlist = []
  5405. yminlist = []
  5406. if not obj_list:
  5407. self.inform.emit('[WARNING_NOTCL] %s' %
  5408. _("No object selected to Skew/Shear on X axis."))
  5409. else:
  5410. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5411. min=-360, max=360, decimals=4,
  5412. init_val=float(self.defaults['tools_transform_skew_x']))
  5413. num, ok = skewxbox.get_value()
  5414. if ok:
  5415. # first get a bounding box to fit all
  5416. for obj in obj_list:
  5417. xmin, ymin, xmax, ymax = obj.bounds()
  5418. xminlist.append(xmin)
  5419. yminlist.append(ymin)
  5420. # get the minimum x,y and maximum x,y for all objects selected
  5421. xminimal = min(xminlist)
  5422. yminimal = min(yminlist)
  5423. for obj in obj_list:
  5424. obj.skew(num, 0, point=(xminimal, yminimal))
  5425. obj.plot()
  5426. self.object_changed.emit(obj)
  5427. self.inform.emit('[success] %s' %
  5428. _("Skew on X axis done."))
  5429. def on_skewy(self):
  5430. self.report_usage("on_skewy()")
  5431. obj_list = self.collection.get_selected()
  5432. xminlist = []
  5433. yminlist = []
  5434. if not obj_list:
  5435. self.inform.emit('[WARNING_NOTCL] %s' %
  5436. _("No object selected to Skew/Shear on Y axis."))
  5437. else:
  5438. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5439. min=-360, max=360, decimals=4,
  5440. init_val=float(self.defaults['tools_transform_skew_y']))
  5441. num, ok = skewybox.get_value()
  5442. if ok:
  5443. # first get a bounding box to fit all
  5444. for obj in obj_list:
  5445. xmin, ymin, xmax, ymax = obj.bounds()
  5446. xminlist.append(xmin)
  5447. yminlist.append(ymin)
  5448. # get the minimum x,y and maximum x,y for all objects selected
  5449. xminimal = min(xminlist)
  5450. yminimal = min(yminlist)
  5451. for obj in obj_list:
  5452. obj.skew(0, num, point=(xminimal, yminimal))
  5453. obj.plot()
  5454. self.object_changed.emit(obj)
  5455. self.inform.emit('[success] %s' %
  5456. _("Skew on Y axis done."))
  5457. def on_plots_updated(self):
  5458. """
  5459. Callback used to report when the plots have changed.
  5460. Adjust axes and zooms to fit.
  5461. :return: None
  5462. """
  5463. self.plotcanvas.update() # TODO: Need update canvas?
  5464. self.on_zoom_fit(None)
  5465. self.collection.update_view()
  5466. # self.inform.emit(_("Plots updated ..."))
  5467. # TODO: Rework toolbar 'clear', 'replot' functions
  5468. def on_toolbar_replot(self):
  5469. """
  5470. Callback for toolbar button. Re-plots all objects.
  5471. :return: None
  5472. """
  5473. self.report_usage("on_toolbar_replot")
  5474. self.log.debug("on_toolbar_replot()")
  5475. try:
  5476. self.collection.get_active().read_form()
  5477. except AttributeError:
  5478. self.log.debug("on_toolbar_replot(): AttributeError")
  5479. pass
  5480. self.plot_all()
  5481. def on_row_activated(self, index):
  5482. if index.isValid():
  5483. if index.internalPointer().parent_item != self.collection.root_item:
  5484. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5485. self.collection.on_item_activated(index)
  5486. def grid_status(self):
  5487. if self.ui.grid_snap_btn.isChecked():
  5488. return True
  5489. else:
  5490. return False
  5491. def populate_cmenu_grids(self):
  5492. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  5493. self.ui.cmenu_gridmenu.clear()
  5494. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5495. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  5496. grid_toggle.setCheckable(True)
  5497. if self.grid_status() == True:
  5498. grid_toggle.setChecked(True)
  5499. else:
  5500. grid_toggle.setChecked(False)
  5501. self.ui.cmenu_gridmenu.addSeparator()
  5502. for grid in sorted_list:
  5503. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  5504. action.triggered.connect(self.set_grid)
  5505. self.ui.cmenu_gridmenu.addSeparator()
  5506. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  5507. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  5508. grid_add.triggered.connect(self.on_grid_add)
  5509. grid_delete.triggered.connect(self.on_grid_delete)
  5510. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5511. def set_grid(self):
  5512. self.ui.grid_gap_x_entry.setText(self.sender().text())
  5513. self.ui.grid_gap_y_entry.setText(self.sender().text())
  5514. def on_grid_add(self):
  5515. # ## Current application units in lower Case
  5516. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  5517. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5518. text=_('Enter a Grid Value:'),
  5519. min=0.0000, max=99.9999, decimals=4)
  5520. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  5521. val, ok = grid_add_popup.get_value()
  5522. if ok:
  5523. if float(val) == 0:
  5524. self.inform.emit('[WARNING_NOTCL] %s' %
  5525. _("Please enter a grid value with non-zero value, in Float format."))
  5526. return
  5527. else:
  5528. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5529. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5530. self.inform.emit('[success] %s...' %
  5531. _("New Grid added"))
  5532. else:
  5533. self.inform.emit('[WARNING_NOTCL] %s...' %
  5534. _("Grid already exists"))
  5535. else:
  5536. self.inform.emit('[WARNING_NOTCL] %s...' %
  5537. _("Adding New Grid cancelled"))
  5538. def on_grid_delete(self):
  5539. # ## Current application units in lower Case
  5540. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  5541. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5542. text='Enter a Grid Value:',
  5543. min=0.0000, max=99.9999, decimals=4)
  5544. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  5545. val, ok = grid_del_popup.get_value()
  5546. if ok:
  5547. if float(val) == 0:
  5548. self.inform.emit('[WARNING_NOTCL] %s' %
  5549. _("Please enter a grid value with non-zero value, in Float format."))
  5550. return
  5551. else:
  5552. try:
  5553. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5554. except ValueError:
  5555. self.inform.emit('[ERROR_NOTCL]%s...' %
  5556. _(" Grid Value does not exist"))
  5557. return
  5558. self.inform.emit('[success] %s...' %
  5559. _("Grid Value deleted"))
  5560. else:
  5561. self.inform.emit('[WARNING_NOTCL] %s...' %
  5562. _("Delete Grid value cancelled"))
  5563. def on_shortcut_list(self):
  5564. self.report_usage("on_shortcut_list()")
  5565. # add the tab if it was closed
  5566. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5567. # delete the absolute and relative position and messages in the infobar
  5568. self.ui.position_label.setText("")
  5569. self.ui.rel_position_label.setText("")
  5570. # Switch plot_area to preferences page
  5571. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5572. self.ui.show()
  5573. def on_select_tab(self, name):
  5574. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5575. if self.ui.splitter.sizes()[0] == 0:
  5576. self.ui.splitter.setSizes([1, 1])
  5577. else:
  5578. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5579. self.ui.splitter.setSizes([0, 1])
  5580. if name == 'project':
  5581. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5582. elif name == 'selected':
  5583. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5584. elif name == 'tool':
  5585. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5586. def on_copy_name(self):
  5587. self.report_usage("on_copy_name()")
  5588. obj = self.collection.get_active()
  5589. try:
  5590. name = obj.options["name"]
  5591. except AttributeError:
  5592. log.debug("on_copy_name() --> No object selected to copy it's name")
  5593. self.inform.emit('[WARNING_NOTCL]%s' %
  5594. _(" No object selected to copy it's name"))
  5595. return
  5596. self.clipboard.setText(name)
  5597. self.inform.emit(_("Name copied on clipboard ..."))
  5598. def on_mouse_click_over_plot(self, event):
  5599. """
  5600. Default actions are:
  5601. :param event: Contains information about the event, like which button
  5602. was clicked, the pixel coordinates and the axes coordinates.
  5603. :return: None
  5604. """
  5605. self.pos = []
  5606. # So it can receive key presses
  5607. self.plotcanvas.native.setFocus()
  5608. # Set the mouse button for panning
  5609. self.plotcanvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  5610. self.pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5611. if self.grid_status() == True:
  5612. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5613. self.app_cursor.enabled = True
  5614. else:
  5615. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5616. self.app_cursor.enabled = False
  5617. try:
  5618. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5619. if event.button == 1:
  5620. # Reset here the relative coordinates so there is a new reference on the click position
  5621. if self.rel_point1 is None:
  5622. self.rel_point1 = self.pos
  5623. else:
  5624. self.rel_point2 = copy(self.rel_point1)
  5625. self.rel_point1 = self.pos
  5626. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5627. if modifiers == QtCore.Qt.ShiftModifier:
  5628. # do not auto open the Project Tab
  5629. self.click_noproject = True
  5630. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  5631. self.inform.emit('[success] %s' %
  5632. _("Coordinates copied to clipboard."))
  5633. return
  5634. self.on_mouse_move_over_plot(event, origin_click=True)
  5635. except Exception as e:
  5636. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5637. def on_double_click_over_plot(self, event):
  5638. self.doubleclick = True
  5639. def on_mouse_move_over_plot(self, event, origin_click=None):
  5640. """
  5641. Callback for the mouse motion event over the plot.
  5642. :param event: Contains information about the event.
  5643. :param origin_click
  5644. :return: None
  5645. """
  5646. # So it can receive key presses
  5647. self.plotcanvas.native.setFocus()
  5648. self.pos_jump = event.pos
  5649. self.ui.popMenu.mouse_is_panning = False
  5650. if not origin_click:
  5651. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5652. if event.button == 2 and event.is_dragging == 1:
  5653. self.ui.popMenu.mouse_is_panning = True
  5654. return
  5655. if self.rel_point1 is not None:
  5656. try: # May fail in case mouse not within axes
  5657. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5658. if self.grid_status() == True:
  5659. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5660. self.app_cursor.enabled = True
  5661. # Update cursor
  5662. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  5663. else:
  5664. pos = (pos_canvas[0], pos_canvas[1])
  5665. self.app_cursor.enabled = False
  5666. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5667. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  5668. dx = pos[0] - self.rel_point1[0]
  5669. dy = pos[1] - self.rel_point1[1]
  5670. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5671. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  5672. self.mouse = [pos[0], pos[1]]
  5673. # if the mouse is moved and the LMB is clicked then the action is a selection
  5674. if event.is_dragging == 1 and event.button == 1:
  5675. self.delete_selection_shape()
  5676. if dx < 0:
  5677. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5678. face_color=self.defaults['global_alt_sel_fill'])
  5679. self.selection_type = False
  5680. else:
  5681. self.draw_moving_selection_shape(self.pos, pos)
  5682. self.selection_type = True
  5683. # hover effect - enabled in Preferences -> General -> GUI Settings
  5684. if self.defaults['global_hover']:
  5685. for obj in self.collection.get_list():
  5686. try:
  5687. # select the object(s) only if it is enabled (plotted)
  5688. if obj.options['plot']:
  5689. if obj not in self.collection.get_selected():
  5690. poly_obj = Polygon(
  5691. [(obj.options['xmin'], obj.options['ymin']),
  5692. (obj.options['xmax'], obj.options['ymin']),
  5693. (obj.options['xmax'], obj.options['ymax']),
  5694. (obj.options['xmin'], obj.options['ymax'])]
  5695. )
  5696. if Point(pos).within(poly_obj):
  5697. if obj.isHovering is False:
  5698. obj.isHovering = True
  5699. obj.notHovering = True
  5700. # create the selection box around the selected object
  5701. self.draw_hover_shape(obj, color='#d1e0e0')
  5702. else:
  5703. if obj.notHovering is True:
  5704. obj.notHovering = False
  5705. obj.isHovering = False
  5706. self.delete_hover_shape()
  5707. except:
  5708. # the Exception here will happen if we try to select on screen and we have an
  5709. # newly (and empty) just created Geometry or Excellon object that do not have the
  5710. # xmin, xmax, ymin, ymax options.
  5711. # In this case poly_obj creation (see above) will fail
  5712. pass
  5713. except:
  5714. self.ui.position_label.setText("")
  5715. self.ui.rel_position_label.setText("")
  5716. self.mouse = None
  5717. def on_mouse_click_release_over_plot(self, event):
  5718. """
  5719. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5720. and has been registered in ''self.__init__()''.
  5721. :param event: contains information about the event.
  5722. :return:
  5723. """
  5724. pos = 0, 0
  5725. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5726. if self.grid_status() == True:
  5727. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5728. else:
  5729. pos = (pos_canvas[0], pos_canvas[1])
  5730. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5731. # canvas menu
  5732. if event.button == 2: # right click
  5733. if self.ui.popMenu.mouse_is_panning is False:
  5734. self.cursor = QtGui.QCursor()
  5735. self.populate_cmenu_grids()
  5736. self.ui.popMenu.popup(self.cursor.pos())
  5737. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5738. # selection and then select a type of selection ("enclosing" or "touching")
  5739. try:
  5740. if event.button == 1: # left click
  5741. if self.doubleclick is True:
  5742. self.doubleclick = False
  5743. if self.collection.get_selected():
  5744. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5745. if self.ui.splitter.sizes()[0] == 0:
  5746. self.ui.splitter.setSizes([1, 1])
  5747. # delete the selection shape(S) as it may be in the way
  5748. self.delete_selection_shape()
  5749. self.delete_hover_shape()
  5750. else:
  5751. if self.selection_type is not None:
  5752. self.selection_area_handler(self.pos, pos, self.selection_type)
  5753. self.selection_type = None
  5754. else:
  5755. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5756. if key_modifier == QtCore.Qt.ShiftModifier:
  5757. mod_key = 'Shift'
  5758. elif key_modifier == QtCore.Qt.ControlModifier:
  5759. mod_key = 'Control'
  5760. else:
  5761. mod_key = None
  5762. if mod_key == self.defaults["global_mselect_key"]:
  5763. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5764. # deselect, and if it's not selected then it will be selected
  5765. # If there is no active command (self.command_active is None) then we check if we clicked
  5766. # on a object by checking the bounding limits against mouse click position
  5767. if self.command_active is None:
  5768. self.select_objects(key='CTRL')
  5769. self.delete_hover_shape()
  5770. else:
  5771. # If there is no active command (self.command_active is None) then we check if we clicked
  5772. # on a object by checking the bounding limits against mouse click position
  5773. if self.command_active is None:
  5774. self.select_objects()
  5775. self.delete_hover_shape()
  5776. except Exception as e:
  5777. log.warning("Error: %s" % str(e))
  5778. return
  5779. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5780. """
  5781. :param start_pos: mouse position when the selection LMB click was done
  5782. :param end_pos: mouse position when the left mouse button is released
  5783. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5784. :return:
  5785. """
  5786. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5787. self.delete_selection_shape()
  5788. for obj in self.collection.get_list():
  5789. try:
  5790. # select the object(s) only if it is enabled (plotted)
  5791. if obj.options['plot']:
  5792. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5793. (obj.options['xmax'], obj.options['ymin']),
  5794. (obj.options['xmax'], obj.options['ymax']),
  5795. (obj.options['xmin'], obj.options['ymax'])])
  5796. if sel_type is True:
  5797. if poly_obj.within(poly_selection):
  5798. # create the selection box around the selected object
  5799. if self.defaults['global_selection_shape'] is True:
  5800. self.draw_selection_shape(obj)
  5801. self.collection.set_active(obj.options['name'])
  5802. else:
  5803. if poly_selection.intersects(poly_obj):
  5804. # create the selection box around the selected object
  5805. if self.defaults['global_selection_shape'] is True:
  5806. self.draw_selection_shape(obj)
  5807. self.collection.set_active(obj.options['name'])
  5808. except Exception as e:
  5809. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5810. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5811. # In this case poly_obj creation (see above) will fail
  5812. log.debug("App.selection_area_handler() --> %s" % str(e))
  5813. def select_objects(self, key=None):
  5814. # list where we store the overlapped objects under our mouse left click position
  5815. objects_under_the_click_list = []
  5816. # Populate the list with the overlapped objects on the click position
  5817. curr_x, curr_y = self.pos
  5818. for obj in self.all_objects_list:
  5819. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5820. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5821. if obj.options['name'] not in objects_under_the_click_list:
  5822. if obj.options['plot']:
  5823. # add objects to the objects_under_the_click list only if the object is plotted
  5824. # (active and not disabled)
  5825. objects_under_the_click_list.append(obj.options['name'])
  5826. try:
  5827. # If there is no element in the overlapped objects list then make everyone inactive
  5828. # because we selected "nothing"
  5829. if not objects_under_the_click_list:
  5830. self.collection.set_all_inactive()
  5831. # delete the possible selection box around a possible selected object
  5832. self.delete_selection_shape()
  5833. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5834. # only when working on App
  5835. if self.call_source == 'app':
  5836. if self.click_noproject is False:
  5837. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5838. else:
  5839. # restore auto open the Project Tab
  5840. self.click_noproject = False
  5841. # delete any text in the status bar, implicitly the last object name that was selected
  5842. self.inform.emit("")
  5843. else:
  5844. self.call_source = 'app'
  5845. else:
  5846. # case when there is only an object under the click and we toggle it
  5847. if len(objects_under_the_click_list) == 1:
  5848. if self.collection.get_active() is None:
  5849. self.collection.set_active(objects_under_the_click_list[0])
  5850. # create the selection box around the selected object
  5851. curr_sel_obj = self.collection.get_active()
  5852. if self.defaults['global_selection_shape'] is True:
  5853. self.draw_selection_shape(curr_sel_obj)
  5854. # self.inform.emit('[selected] %s: %s selected' %
  5855. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  5856. if curr_sel_obj.kind == 'gerber':
  5857. self.inform.emit(
  5858. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5859. color='green', name=str(curr_sel_obj.options['name'])))
  5860. elif curr_sel_obj.kind == 'excellon':
  5861. self.inform.emit(
  5862. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5863. color='brown', name=str(curr_sel_obj.options['name'])))
  5864. elif curr_sel_obj.kind == 'cncjob':
  5865. self.inform.emit(
  5866. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5867. color='blue', name=str(curr_sel_obj.options['name'])))
  5868. elif curr_sel_obj.kind == 'geometry':
  5869. self.inform.emit(
  5870. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5871. color='red', name=str(curr_sel_obj.options['name'])))
  5872. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  5873. self.collection.set_all_inactive()
  5874. self.delete_selection_shape()
  5875. self.collection.set_active(objects_under_the_click_list[0])
  5876. # create the selection box around the selected object
  5877. curr_sel_obj = self.collection.get_active()
  5878. if self.defaults['global_selection_shape'] is True:
  5879. self.draw_selection_shape(curr_sel_obj)
  5880. # self.inform.emit('[selected] %s: %s selected' %
  5881. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  5882. if curr_sel_obj.kind == 'gerber':
  5883. self.inform.emit(
  5884. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5885. color='green', name=str(curr_sel_obj.options['name'])))
  5886. elif curr_sel_obj.kind == 'excellon':
  5887. self.inform.emit(
  5888. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5889. color='brown', name=str(curr_sel_obj.options['name'])))
  5890. elif curr_sel_obj.kind == 'cncjob':
  5891. self.inform.emit(
  5892. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5893. color='blue', name=str(curr_sel_obj.options['name'])))
  5894. elif curr_sel_obj.kind == 'geometry':
  5895. self.inform.emit(
  5896. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  5897. color='red', name=str(curr_sel_obj.options['name'])))
  5898. else:
  5899. self.collection.set_all_inactive()
  5900. self.delete_selection_shape()
  5901. if self.call_source == 'app':
  5902. # delete any text in the status bar, implicitly the last object name that was selected
  5903. self.inform.emit("")
  5904. else:
  5905. self.call_source = 'app'
  5906. else:
  5907. # If there is no selected object
  5908. # make active the first element of the overlapped objects list
  5909. if self.collection.get_active() is None:
  5910. self.collection.set_active(objects_under_the_click_list[0])
  5911. name_sel_obj = self.collection.get_active().options['name']
  5912. # In case that there is a selected object but it is not in the overlapped object list
  5913. # make that object inactive and activate the first element in the overlapped object list
  5914. if name_sel_obj not in objects_under_the_click_list:
  5915. self.collection.set_inactive(name_sel_obj)
  5916. name_sel_obj = objects_under_the_click_list[0]
  5917. self.collection.set_active(name_sel_obj)
  5918. else:
  5919. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  5920. self.collection.set_all_inactive()
  5921. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  5922. len(objects_under_the_click_list)])
  5923. curr_sel_obj = self.collection.get_active()
  5924. # delete the possible selection box around a possible selected object
  5925. self.delete_selection_shape()
  5926. # create the selection box around the selected object
  5927. if self.defaults['global_selection_shape'] is True:
  5928. self.draw_selection_shape(curr_sel_obj)
  5929. # self.inform.emit('[selected] %s: %s selected' %
  5930. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  5931. if curr_sel_obj.kind == 'gerber':
  5932. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5933. color='green', name=str(curr_sel_obj.options['name'])))
  5934. elif curr_sel_obj.kind == 'excellon':
  5935. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5936. color='brown', name=str(curr_sel_obj.options['name'])))
  5937. elif curr_sel_obj.kind == 'cncjob':
  5938. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5939. color='blue', name=str(curr_sel_obj.options['name'])))
  5940. elif curr_sel_obj.kind == 'geometry':
  5941. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5942. color='red', name=str(curr_sel_obj.options['name'])))
  5943. # for obj in self.collection.get_list():
  5944. # obj.plot()
  5945. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  5946. # TODO: on selected objects change the object colors and do not draw the selection box
  5947. # self.plotcanvas.update() # this updates the canvas
  5948. except Exception as e:
  5949. log.error("[ERROR] Something went bad. %s" % str(e))
  5950. return
  5951. def delete_hover_shape(self):
  5952. self.hover_shapes.clear()
  5953. self.hover_shapes.redraw()
  5954. def draw_hover_shape(self, sel_obj, color=None):
  5955. """
  5956. :param sel_obj: the object for which the hover shape must be drawn
  5957. :return:
  5958. """
  5959. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5960. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5961. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5962. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5963. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5964. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  5965. hover_rect = hover_rect.buffer(-0.1)
  5966. hover_rect = hover_rect.buffer(0.2)
  5967. else:
  5968. hover_rect = hover_rect.buffer(-0.00393)
  5969. hover_rect = hover_rect.buffer(0.00787)
  5970. if color:
  5971. face = Color(color)
  5972. face.alpha = 0.2
  5973. outline = Color(color, alpha=0.8)
  5974. else:
  5975. face = Color(self.defaults['global_sel_fill'])
  5976. face.alpha = 0.2
  5977. outline = self.defaults['global_sel_line']
  5978. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5979. def delete_selection_shape(self):
  5980. self.move_tool.sel_shapes.clear()
  5981. self.move_tool.sel_shapes.redraw()
  5982. def draw_selection_shape(self, sel_obj, color=None):
  5983. """
  5984. :param sel_obj: the object for which the selection shape must be drawn
  5985. :return:
  5986. """
  5987. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5988. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5989. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5990. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5991. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5992. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  5993. sel_rect = sel_rect.buffer(-0.1)
  5994. sel_rect = sel_rect.buffer(0.2)
  5995. else:
  5996. sel_rect = sel_rect.buffer(-0.00393)
  5997. sel_rect = sel_rect.buffer(0.00787)
  5998. if color:
  5999. face = Color(color, alpha=0.2)
  6000. outline = Color(color, alpha=0.8)
  6001. else:
  6002. face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  6003. outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  6004. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  6005. color=outline,
  6006. face_color=face,
  6007. update=True,
  6008. layer=0,
  6009. tolerance=None))
  6010. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  6011. """
  6012. :param old_coords: old coordinates
  6013. :param coords: new coordinates
  6014. :return:
  6015. """
  6016. if 'color' in kwargs:
  6017. color = kwargs['color']
  6018. else:
  6019. color = self.defaults['global_sel_line']
  6020. if 'face_color' in kwargs:
  6021. face_color = kwargs['face_color']
  6022. else:
  6023. face_color = self.defaults['global_sel_fill']
  6024. if 'face_alpha' in kwargs:
  6025. face_alpha = kwargs['face_alpha']
  6026. else:
  6027. face_alpha = 0.3
  6028. x0, y0 = old_coords
  6029. x1, y1 = coords
  6030. pt1 = (x0, y0)
  6031. pt2 = (x1, y0)
  6032. pt3 = (x1, y1)
  6033. pt4 = (x0, y1)
  6034. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6035. color_t = Color(face_color)
  6036. color_t.alpha = face_alpha
  6037. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  6038. layer=0, tolerance=None)
  6039. def on_file_new_click(self):
  6040. if self.collection.get_list() and self.should_we_save:
  6041. msgbox = QtWidgets.QMessageBox()
  6042. # msgbox.setText("<B>Save changes ...</B>")
  6043. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  6044. "Creating a New project will delete them.\n"
  6045. "Do you want to Save the project?"))
  6046. msgbox.setWindowTitle(_("Save changes"))
  6047. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6048. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6049. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6050. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6051. msgbox.setDefaultButton(bt_yes)
  6052. msgbox.exec_()
  6053. response = msgbox.clickedButton()
  6054. if response == bt_yes:
  6055. self.on_file_saveprojectas()
  6056. elif response == bt_cancel:
  6057. return
  6058. elif response == bt_no:
  6059. self.on_file_new()
  6060. else:
  6061. self.on_file_new()
  6062. self.inform.emit('[success] %s...' %
  6063. _("New Project created"))
  6064. def on_file_new(self):
  6065. """
  6066. Callback for menu item File->New. Returns the application to its
  6067. startup state. This method is thread-safe.
  6068. :return: None
  6069. """
  6070. self.report_usage("on_file_new")
  6071. # Remove everything from memory
  6072. App.log.debug("on_file_new()")
  6073. if self.call_source != 'app':
  6074. self.editor2object(cleanup=True)
  6075. # ## EDITOR section
  6076. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  6077. self.exc_editor = FlatCAMExcEditor(self)
  6078. self.grb_editor = FlatCAMGrbEditor(self)
  6079. # Clear pool
  6080. self.clear_pool()
  6081. for obj in self.collection.get_list():
  6082. # delete shapes left drawn from mark shape_collections, if any
  6083. if isinstance(obj, FlatCAMGerber):
  6084. try:
  6085. obj.mark_shapes.enabled = False
  6086. obj.mark_shapes.clear(update=True)
  6087. except AttributeError:
  6088. pass
  6089. # also delete annotation shapes, if any
  6090. elif isinstance(obj, FlatCAMCNCjob):
  6091. try:
  6092. obj.annotation.enabled = False
  6093. obj.annotation.clear(update=True)
  6094. except AttributeError:
  6095. pass
  6096. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6097. self.init_tcl()
  6098. self.delete_selection_shape()
  6099. self.collection.delete_all()
  6100. self.setup_component_editor()
  6101. # Clear project filename
  6102. self.project_filename = None
  6103. # Load the application defaults
  6104. self.load_defaults(filename='current_defaults')
  6105. # Re-fresh project options
  6106. self.on_options_app2project()
  6107. # Init Tools
  6108. self.init_tools()
  6109. # Close any Tabs opened in the Plot Tab Area section
  6110. for index in range(self.ui.plot_tab_area.count()):
  6111. self.ui.plot_tab_area.closeTab(index)
  6112. # for whatever reason previous command does not close the last tab so I do it manually
  6113. self.ui.plot_tab_area.closeTab(0)
  6114. # # And then add again the Plot Area
  6115. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  6116. self.ui.plot_tab_area.protectTab(0)
  6117. # take the focus of the Notebook on Project Tab.
  6118. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6119. self.set_ui_title(name=_("New Project - Not saved"))
  6120. def obj_properties(self):
  6121. self.report_usage("obj_properties()")
  6122. self.properties_tool.run(toggle=False)
  6123. def on_project_context_save(self):
  6124. obj = self.collection.get_active()
  6125. if type(obj) == FlatCAMGeometry:
  6126. self.on_file_exportdxf()
  6127. elif type(obj) == FlatCAMExcellon:
  6128. self.on_file_saveexcellon()
  6129. elif type(obj) == FlatCAMCNCjob:
  6130. obj.on_exportgcode_button_click()
  6131. elif type(obj) == FlatCAMGerber:
  6132. self.on_file_savegerber()
  6133. def obj_move(self):
  6134. self.report_usage("obj_move()")
  6135. self.move_tool.run(toggle=False)
  6136. def on_fileopengerber(self, checked=None, name=None):
  6137. """
  6138. File menu callback for opening a Gerber.
  6139. :return: None
  6140. """
  6141. self.report_usage("on_fileopengerber")
  6142. App.log.debug("on_fileopengerber()")
  6143. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6144. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6145. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  6146. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6147. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6148. "*.mil);;" \
  6149. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6150. "Allegro Files (*.art);;" \
  6151. "Mentor Files (*.pho *.gdo);;" \
  6152. "All Files (*.*)"
  6153. if name is None:
  6154. try:
  6155. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6156. directory=self.get_last_folder(),
  6157. filter=_filter_)
  6158. except TypeError:
  6159. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6160. filenames = [str(filename) for filename in filenames]
  6161. else:
  6162. filenames = [name]
  6163. if len(filenames) == 0:
  6164. self.inform.emit('[WARNING_NOTCL] %s' %
  6165. _("Open Gerber cancelled."))
  6166. else:
  6167. for filename in filenames:
  6168. if filename != '':
  6169. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6170. def on_fileopenexcellon(self, checked=None, name=None):
  6171. """
  6172. File menu callback for opening an Excellon file.
  6173. :return: None
  6174. """
  6175. self.report_usage("on_fileopenexcellon")
  6176. App.log.debug("on_fileopenexcellon()")
  6177. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6178. "All Files (*.*)"
  6179. if name is None:
  6180. try:
  6181. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6182. directory=self.get_last_folder(),
  6183. filter=_filter_)
  6184. except TypeError:
  6185. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6186. filenames = [str(filename) for filename in filenames]
  6187. else:
  6188. filenames = [str(name)]
  6189. if len(filenames) == 0:
  6190. self.inform.emit('[WARNING_NOTCL]%s' %
  6191. _(" Open Excellon cancelled."))
  6192. else:
  6193. for filename in filenames:
  6194. if filename != '':
  6195. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6196. def on_fileopengcode(self, checked=None, name=None):
  6197. """
  6198. File menu call back for opening gcode.
  6199. :return: None
  6200. """
  6201. self.report_usage("on_fileopengcode")
  6202. App.log.debug("on_fileopengcode()")
  6203. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6204. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6205. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  6206. "All Files (*.*)"
  6207. if name is None:
  6208. try:
  6209. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6210. directory=self.get_last_folder(),
  6211. filter=_filter_)
  6212. except TypeError:
  6213. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6214. filenames = [str(filename) for filename in filenames]
  6215. else:
  6216. filenames = [name]
  6217. if len(filenames) == 0:
  6218. self.inform.emit('[WARNING_NOTCL] %s' %
  6219. _("Open G-Code cancelled."))
  6220. else:
  6221. for filename in filenames:
  6222. if filename != '':
  6223. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename]})
  6224. def on_file_openproject(self, checked=None):
  6225. """
  6226. File menu callback for opening a project.
  6227. :return: None
  6228. """
  6229. self.report_usage("on_file_openproject")
  6230. App.log.debug("on_file_openproject()")
  6231. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6232. try:
  6233. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6234. directory=self.get_last_folder(), filter=_filter_)
  6235. except TypeError:
  6236. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6237. # The Qt methods above will return a QString which can cause problems later.
  6238. # So far json.dump() will fail to serialize it.
  6239. # TODO: Improve the serialization methods and remove this fix.
  6240. filename = str(filename)
  6241. if filename == "":
  6242. self.inform.emit('[WARNING_NOTCL] %s' %
  6243. _("Open Project cancelled."))
  6244. else:
  6245. # self.worker_task.emit({'fcn': self.open_project,
  6246. # 'params': [filename]})
  6247. # The above was failing because open_project() is not
  6248. # thread safe. The new_project()
  6249. self.open_project(filename)
  6250. def on_file_openconfig(self, checked=None):
  6251. """
  6252. File menu callback for opening a config file.
  6253. :return: None
  6254. """
  6255. self.report_usage("on_file_openconfig")
  6256. App.log.debug("on_file_openconfig()")
  6257. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6258. try:
  6259. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6260. directory=self.data_path, filter=_filter_)
  6261. except TypeError:
  6262. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6263. filter=_filter_)
  6264. if filename == "":
  6265. self.inform.emit('[WARNING_NOTCL] %s' %
  6266. _("Open Config cancelled."))
  6267. else:
  6268. self.open_config_file(filename)
  6269. def on_file_exportsvg(self):
  6270. """
  6271. Callback for menu item File->Export SVG.
  6272. :return: None
  6273. """
  6274. self.report_usage("on_file_exportsvg")
  6275. App.log.debug("on_file_exportsvg()")
  6276. obj = self.collection.get_active()
  6277. if obj is None:
  6278. self.inform.emit('[WARNING_NOTCL] %s' %
  6279. _("No object selected."))
  6280. msg = _("Please Select a Geometry object to export")
  6281. msgbox = QtWidgets.QMessageBox()
  6282. msgbox.setInformativeText(msg)
  6283. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6284. msgbox.setDefaultButton(bt_ok)
  6285. msgbox.exec_()
  6286. return
  6287. # Check for more compatible types and add as required
  6288. if (not isinstance(obj, FlatCAMGeometry)
  6289. and not isinstance(obj, FlatCAMGerber)
  6290. and not isinstance(obj, FlatCAMCNCjob)
  6291. and not isinstance(obj, FlatCAMExcellon)):
  6292. msg = '[ERROR_NOTCL] %s' % \
  6293. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6294. msgbox = QtWidgets.QMessageBox()
  6295. msgbox.setInformativeText(msg)
  6296. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6297. msgbox.setDefaultButton(bt_ok)
  6298. msgbox.exec_()
  6299. return
  6300. name = obj.options["name"]
  6301. _filter = "SVG File (*.svg);;All Files (*.*)"
  6302. try:
  6303. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6304. caption=_("Export SVG"),
  6305. directory=self.get_last_save_folder() + '/' + str(name),
  6306. filter=_filter)
  6307. except TypeError:
  6308. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  6309. filename = str(filename)
  6310. if filename == "":
  6311. self.inform.emit('[WARNING_NOTCL]%s' %
  6312. _(" Export SVG cancelled."))
  6313. return
  6314. else:
  6315. self.export_svg(name, filename)
  6316. if self.defaults["global_open_style"] is False:
  6317. self.file_opened.emit("SVG", filename)
  6318. self.file_saved.emit("SVG", filename)
  6319. def on_file_exportpng(self):
  6320. self.report_usage("on_file_exportpng")
  6321. App.log.debug("on_file_exportpng()")
  6322. self.date = str(datetime.today()).rpartition('.')[0]
  6323. self.date = ''.join(c for c in self.date if c not in ':-')
  6324. self.date = self.date.replace(' ', '_')
  6325. image = _screenshot()
  6326. data = np.asarray(image)
  6327. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6328. self.inform.emit('[[WARNING_NOTCL]] %s' %
  6329. _('Data must be a 3D array with last dimension 3 or 4'))
  6330. return
  6331. filter_ = "PNG File (*.png);;All Files (*.*)"
  6332. try:
  6333. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6334. caption=_("Export PNG Image"),
  6335. directory=self.get_last_save_folder() + '/png_' + self.date,
  6336. filter=filter_)
  6337. except TypeError:
  6338. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  6339. filename = str(filename)
  6340. if filename == "":
  6341. self.inform.emit(_("Export PNG cancelled."))
  6342. return
  6343. else:
  6344. write_png(filename, data)
  6345. if self.defaults["global_open_style"] is False:
  6346. self.file_opened.emit("png", filename)
  6347. self.file_saved.emit("png", filename)
  6348. def on_file_savegerber(self):
  6349. """
  6350. Callback for menu item in Project context menu.
  6351. :return: None
  6352. """
  6353. self.report_usage("on_file_savegerber")
  6354. App.log.debug("on_file_savegerber()")
  6355. obj = self.collection.get_active()
  6356. if obj is None:
  6357. self.inform.emit('[WARNING_NOTCL] %s' %
  6358. _("No object selected. Please select an Gerber object to export."))
  6359. return
  6360. # Check for more compatible types and add as required
  6361. if not isinstance(obj, FlatCAMGerber):
  6362. self.inform.emit('[ERROR_NOTCL] %s' %
  6363. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6364. return
  6365. name = self.collection.get_active().options["name"]
  6366. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6367. try:
  6368. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6369. caption="Save Gerber source file",
  6370. directory=self.get_last_save_folder() + '/' + name,
  6371. filter=_filter)
  6372. except TypeError:
  6373. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  6374. filename = str(filename)
  6375. if filename == "":
  6376. self.inform.emit('[WARNING_NOTCL] %s' %
  6377. _("Save Gerber source file cancelled."))
  6378. return
  6379. else:
  6380. self.save_source_file(name, filename)
  6381. if self.defaults["global_open_style"] is False:
  6382. self.file_opened.emit("Gerber", filename)
  6383. self.file_saved.emit("Gerber", filename)
  6384. def on_file_saveexcellon(self):
  6385. """
  6386. Callback for menu item in project context menu.
  6387. :return: None
  6388. """
  6389. self.report_usage("on_file_saveexcellon")
  6390. App.log.debug("on_file_saveexcellon()")
  6391. obj = self.collection.get_active()
  6392. if obj is None:
  6393. self.inform.emit('[WARNING_NOTCL] %s' %
  6394. _("No object selected. Please select an Excellon object to export."))
  6395. return
  6396. # Check for more compatible types and add as required
  6397. if not isinstance(obj, FlatCAMExcellon):
  6398. self.inform.emit('[ERROR_NOTCL] %s' %
  6399. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6400. return
  6401. name = self.collection.get_active().options["name"]
  6402. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6403. try:
  6404. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6405. caption=_("Save Excellon source file"),
  6406. directory=self.get_last_save_folder() + '/' + name,
  6407. filter=_filter)
  6408. except TypeError:
  6409. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  6410. filename = str(filename)
  6411. if filename == "":
  6412. self.inform.emit('[WARNING_NOTCL] %s' %
  6413. _("Saving Excellon source file cancelled."))
  6414. return
  6415. else:
  6416. self.save_source_file(name, filename)
  6417. if self.defaults["global_open_style"] is False:
  6418. self.file_opened.emit("Excellon", filename)
  6419. self.file_saved.emit("Excellon", filename)
  6420. def on_file_exportexcellon(self):
  6421. """
  6422. Callback for menu item File->Export->Excellon.
  6423. :return: None
  6424. """
  6425. self.report_usage("on_file_exportexcellon")
  6426. App.log.debug("on_file_exportexcellon()")
  6427. obj = self.collection.get_active()
  6428. if obj is None:
  6429. self.inform.emit('[WARNING_NOTCL] %s' %
  6430. _("No object selected. Please Select an Excellon object to export."))
  6431. return
  6432. # Check for more compatible types and add as required
  6433. if not isinstance(obj, FlatCAMExcellon):
  6434. self.inform.emit('[ERROR_NOTCL] %s' %
  6435. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6436. return
  6437. name = self.collection.get_active().options["name"]
  6438. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6439. try:
  6440. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6441. caption=_("Export Excellon"),
  6442. directory=self.get_last_save_folder() + '/' + name,
  6443. filter=_filter)
  6444. except TypeError:
  6445. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  6446. filename = str(filename)
  6447. if filename == "":
  6448. self.inform.emit('[WARNING_NOTCL] %s' %
  6449. _("Export Excellon cancelled."))
  6450. return
  6451. else:
  6452. self.export_excellon(name, filename)
  6453. if self.defaults["global_open_style"] is False:
  6454. self.file_opened.emit("Excellon", filename)
  6455. self.file_saved.emit("Excellon", filename)
  6456. def on_file_exportgerber(self):
  6457. """
  6458. Callback for menu item File->Export->Gerber.
  6459. :return: None
  6460. """
  6461. self.report_usage("on_file_exportgerber")
  6462. App.log.debug("on_file_exportgerber()")
  6463. obj = self.collection.get_active()
  6464. if obj is None:
  6465. self.inform.emit('[WARNING_NOTCL] %s' %
  6466. _("No object selected. Please Select an Gerber object to export."))
  6467. return
  6468. # Check for more compatible types and add as required
  6469. if not isinstance(obj, FlatCAMGerber):
  6470. self.inform.emit('[ERROR_NOTCL] %s' %
  6471. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6472. return
  6473. name = self.collection.get_active().options["name"]
  6474. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  6475. try:
  6476. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6477. caption=_("Export Gerber"),
  6478. directory=self.get_last_save_folder() + '/' + name,
  6479. filter=_filter_)
  6480. except TypeError:
  6481. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  6482. filename = str(filename)
  6483. if filename == "":
  6484. self.inform.emit('[WARNING_NOTCL] %s' %
  6485. _("Export Gerber cancelled."))
  6486. return
  6487. else:
  6488. self.export_gerber(name, filename)
  6489. if self.defaults["global_open_style"] is False:
  6490. self.file_opened.emit("Gerber", filename)
  6491. self.file_saved.emit("Gerber", filename)
  6492. def on_file_exportdxf(self):
  6493. """
  6494. Callback for menu item File->Export DXF.
  6495. :return: None
  6496. """
  6497. self.report_usage("on_file_exportdxf")
  6498. App.log.debug("on_file_exportdxf()")
  6499. obj = self.collection.get_active()
  6500. if obj is None:
  6501. self.inform.emit('[WARNING_NOTCL] %s' %
  6502. _("No object selected."))
  6503. msg = _("Please Select a Geometry object to export")
  6504. msgbox = QtWidgets.QMessageBox()
  6505. msgbox.setInformativeText(msg)
  6506. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6507. msgbox.setDefaultButton(bt_ok)
  6508. msgbox.exec_()
  6509. return
  6510. # Check for more compatible types and add as required
  6511. if not isinstance(obj, FlatCAMGeometry):
  6512. msg = '[ERROR_NOTCL] %s' % \
  6513. _("Only Geometry objects can be used.")
  6514. msgbox = QtWidgets.QMessageBox()
  6515. msgbox.setInformativeText(msg)
  6516. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6517. msgbox.setDefaultButton(bt_ok)
  6518. msgbox.exec_()
  6519. return
  6520. name = self.collection.get_active().options["name"]
  6521. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  6522. try:
  6523. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6524. caption=_("Export DXF"),
  6525. directory=self.get_last_save_folder() + '/' + name,
  6526. filter=_filter_)
  6527. except TypeError:
  6528. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  6529. filter=_filter_)
  6530. filename = str(filename)
  6531. if filename == "":
  6532. self.inform.emit('[WARNING_NOTCL] %s' %
  6533. _("Export DXF cancelled."))
  6534. return
  6535. else:
  6536. self.export_dxf(name, filename)
  6537. if self.defaults["global_open_style"] is False:
  6538. self.file_opened.emit("DXF", filename)
  6539. self.file_saved.emit("DXF", filename)
  6540. def on_file_importsvg(self, type_of_obj):
  6541. """
  6542. Callback for menu item File->Import SVG.
  6543. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6544. :type type_of_obj: str
  6545. :return: None
  6546. """
  6547. self.report_usage("on_file_importsvg")
  6548. App.log.debug("on_file_importsvg()")
  6549. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  6550. try:
  6551. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6552. directory=self.get_last_folder(), filter=_filter_)
  6553. except TypeError:
  6554. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6555. filter=_filter_)
  6556. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  6557. type_of_obj = "geometry"
  6558. filenames = [str(filename) for filename in filenames]
  6559. if len(filenames) == 0:
  6560. self.inform.emit('[WARNING_NOTCL] %s' %
  6561. _("Open SVG cancelled."))
  6562. else:
  6563. for filename in filenames:
  6564. if filename != '':
  6565. self.worker_task.emit({'fcn': self.import_svg,
  6566. 'params': [filename, type_of_obj]})
  6567. def on_file_importdxf(self, type_of_obj):
  6568. """
  6569. Callback for menu item File->Import DXF.
  6570. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6571. :type type_of_obj: str
  6572. :return: None
  6573. """
  6574. self.report_usage("on_file_importdxf")
  6575. App.log.debug("on_file_importdxf()")
  6576. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  6577. try:
  6578. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6579. directory=self.get_last_folder(),
  6580. filter=_filter_)
  6581. except TypeError:
  6582. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6583. filter=_filter_)
  6584. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  6585. type_of_obj = "geometry"
  6586. filenames = [str(filename) for filename in filenames]
  6587. if len(filenames) == 0:
  6588. self.inform.emit('[WARNING_NOTCL] %s' %
  6589. _("Open DXF cancelled."))
  6590. else:
  6591. for filename in filenames:
  6592. if filename != '':
  6593. self.worker_task.emit({'fcn': self.import_dxf,
  6594. 'params': [filename, type_of_obj]})
  6595. # ###############################################################################################################
  6596. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6597. # ###############################################################################################################
  6598. def init_code_editor(self, name):
  6599. # Signals section
  6600. # Disconnect the old signals
  6601. try:
  6602. self.ui.buttonOpen.clicked.disconnect()
  6603. except TypeError:
  6604. pass
  6605. try:
  6606. self.ui.buttonSave.clicked.disconnect()
  6607. except TypeError:
  6608. pass
  6609. # add the tab if it was closed
  6610. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _('%s') % name)
  6611. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  6612. # delete the absolute and relative position and messages in the infobar
  6613. self.ui.position_label.setText("")
  6614. self.ui.rel_position_label.setText("")
  6615. # first clear previous text in text editor (if any)
  6616. self.ui.code_editor.clear()
  6617. self.ui.code_editor.setReadOnly(False)
  6618. self.toggle_codeeditor = True
  6619. self.ui.code_editor.completer_enable = False
  6620. # Switch plot_area to CNCJob tab
  6621. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  6622. def on_view_source(self):
  6623. self.inform.emit('%s' %
  6624. _("Viewing the source code of the selected object."))
  6625. self.proc_container.view.set_busy(_("Loading..."))
  6626. try:
  6627. obj = self.collection.get_active()
  6628. except Exception as e:
  6629. log.debug("App.on_view_source() --> %s" % str(e))
  6630. self.inform.emit('[WARNING_NOTCL] %s' %
  6631. _("Select an Gerber or Excellon file to view it's source file."))
  6632. return 'fail'
  6633. if obj.kind == 'gerber':
  6634. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  6635. else:
  6636. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  6637. self.init_code_editor(name=_("Source Editor"))
  6638. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  6639. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  6640. # then append the text from GCode to the text editor
  6641. try:
  6642. file = StringIO(obj.source_file)
  6643. except AttributeError:
  6644. self.inform.emit('[WARNING_NOTCL] %s' %
  6645. _("There is no selected object for which to see it's source file code."))
  6646. return 'fail'
  6647. self.ui.cncjob_frame.hide()
  6648. try:
  6649. for line in file:
  6650. QtWidgets.QApplication.processEvents()
  6651. proc_line = str(line).strip('\n')
  6652. self.ui.code_editor.append(proc_line)
  6653. except Exception as e:
  6654. log.debug('App.on_view_source() -->%s' % str(e))
  6655. self.inform.emit('[ERROR] %s: %s' %
  6656. (_('Failed to load the source code for the selected object'), str(e)))
  6657. return
  6658. self.handleTextChanged()
  6659. self.ui.cncjob_frame.show()
  6660. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6661. self.proc_container.view.set_idle()
  6662. # self.ui.show()
  6663. def on_toggle_code_editor(self):
  6664. self.report_usage("on_toggle_code_editor()")
  6665. if self.toggle_codeeditor is False:
  6666. self.init_code_editor(name=_("Code Editor"))
  6667. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  6668. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  6669. else:
  6670. for idx in range(self.ui.plot_tab_area.count()):
  6671. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  6672. self.ui.plot_tab_area.closeTab(idx)
  6673. break
  6674. self.toggle_codeeditor = False
  6675. def on_filenewscript(self):
  6676. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6677. self.init_code_editor(name=_("Script Editor"))
  6678. self.ui.code_editor.completer_enable = True
  6679. self.ui.code_editor.append(_(
  6680. "#\n"
  6681. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  6682. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  6683. "#\n\n"
  6684. "# FlatCAM commands list:\n"
  6685. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, Cncjob,\n"
  6686. "# Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, GetNames, GetSys,\n"
  6687. "# ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillHoles, Mirror, New,\n"
  6688. "# NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject, Options, Paint, Panelize,\n"
  6689. "# Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, SubtractPoly,SubtractRectangle, Version,\n"
  6690. "# WriteGCode\n"
  6691. "#\n\n"
  6692. ))
  6693. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  6694. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  6695. self.handleTextChanged()
  6696. self.ui.code_editor.show()
  6697. def on_fileopenscript(self):
  6698. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  6699. try:
  6700. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  6701. directory=self.get_last_folder(), filter=_filter_)
  6702. except TypeError:
  6703. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  6704. # The Qt methods above will return a QString which can cause problems later.
  6705. # So far json.dump() will fail to serialize it.
  6706. # TODO: Improve the serialization methods and remove this fix.
  6707. filename = str(filename)
  6708. if filename == "":
  6709. self.inform.emit('[WARNING_NOTCL] %s' %
  6710. _("Open TCL script cancelled."))
  6711. else:
  6712. self.on_filenewscript()
  6713. try:
  6714. with open(filename, "r") as opened_script:
  6715. try:
  6716. for line in opened_script:
  6717. proc_line = str(line).strip('\n')
  6718. self.ui.code_editor.append(proc_line)
  6719. except Exception as e:
  6720. log.debug('App.on_fileopenscript() -->%s' % str(e))
  6721. self.inform.emit('[ERROR] %s %s' %
  6722. (_('App.on_fileopenscript() -->'), str(e)))
  6723. return
  6724. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6725. self.handleTextChanged()
  6726. self.ui.show()
  6727. except Exception as e:
  6728. log.debug("App.on_fileopenscript() -> %s" % str(e))
  6729. def on_filerunscript(self, name=None):
  6730. """
  6731. File menu callback for loading and running a TCL script.
  6732. :return: None
  6733. """
  6734. self.report_usage("on_filerunscript")
  6735. App.log.debug("on_file_runscript()")
  6736. if name:
  6737. filename = name
  6738. else:
  6739. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  6740. try:
  6741. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6742. directory=self.get_last_folder(), filter=_filter_)
  6743. except TypeError:
  6744. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6745. # The Qt methods above will return a QString which can cause problems later.
  6746. # So far json.dump() will fail to serialize it.
  6747. # TODO: Improve the serialization methods and remove this fix.
  6748. filename = str(filename)
  6749. if filename == "":
  6750. self.inform.emit('[WARNING_NOTCL] %s' %
  6751. _("Run TCL script cancelled."))
  6752. else:
  6753. try:
  6754. with open(filename, "r") as tcl_script:
  6755. cmd_line_shellfile_content = tcl_script.read()
  6756. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  6757. except Exception as e:
  6758. log.debug("App.on_filerunscript() -> %s" % str(e))
  6759. sys.exit(2)
  6760. def on_file_saveproject(self):
  6761. """
  6762. Callback for menu item File->Save Project. Saves the project to
  6763. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6764. if set to None. The project is saved by calling ``self.save_project()``.
  6765. :return: None
  6766. """
  6767. self.report_usage("on_file_saveproject")
  6768. if self.project_filename is None:
  6769. self.on_file_saveprojectas()
  6770. else:
  6771. self.worker_task.emit({'fcn': self.save_project,
  6772. 'params': [self.project_filename]})
  6773. if self.defaults["global_open_style"] is False:
  6774. self.file_opened.emit("project", self.project_filename)
  6775. self.file_saved.emit("project", self.project_filename)
  6776. self.set_ui_title(name=self.project_filename)
  6777. self.should_we_save = False
  6778. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6779. """
  6780. Callback for menu item File->Save Project As... Opens a file
  6781. chooser and saves the project to the given file via
  6782. ``self.save_project()``.
  6783. :param make_copy if to be create a copy of the project; boolean
  6784. :param use_thread: if to be run in a separate thread; boolean
  6785. :param quit_action: if to be followed by quiting the application; boolean
  6786. :return: None
  6787. """
  6788. self.report_usage("on_file_saveprojectas")
  6789. self.date = str(datetime.today()).rpartition('.')[0]
  6790. self.date = ''.join(c for c in self.date if c not in ':-')
  6791. self.date = self.date.replace(' ', '_')
  6792. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  6793. try:
  6794. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6795. caption=_("Save Project As ..."),
  6796. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  6797. filter=filter_)
  6798. except TypeError:
  6799. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  6800. filename = str(filename)
  6801. if filename == '':
  6802. self.inform.emit('[WARNING_NOTCL] %s' %
  6803. _("Save Project cancelled."))
  6804. return
  6805. try:
  6806. f = open(filename, 'r')
  6807. f.close()
  6808. except IOError:
  6809. pass
  6810. if use_thread is True:
  6811. self.worker_task.emit({'fcn': self.save_project,
  6812. 'params': [filename, quit_action]})
  6813. else:
  6814. self.save_project(filename, quit_action)
  6815. # self.save_project(filename)
  6816. if self.defaults["global_open_style"] is False:
  6817. self.file_opened.emit("project", filename)
  6818. self.file_saved.emit("project", filename)
  6819. if not make_copy:
  6820. self.project_filename = filename
  6821. self.set_ui_title(name=self.project_filename)
  6822. self.should_we_save = False
  6823. def export_svg(self, obj_name, filename, scale_factor=0.00):
  6824. """
  6825. Exports a Geometry Object to an SVG file.
  6826. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6827. :param filename: Path to the SVG file to save to.
  6828. :param scale_factor: factor by which to change/scale the thickness of the features
  6829. :return:
  6830. """
  6831. self.report_usage("export_svg()")
  6832. if filename is None:
  6833. filename = self.defaults["global_last_save_folder"]
  6834. self.log.debug("export_svg()")
  6835. try:
  6836. obj = self.collection.get_by_name(str(obj_name))
  6837. except:
  6838. # TODO: The return behavior has not been established... should raise exception?
  6839. return "Could not retrieve object: %s" % obj_name
  6840. with self.proc_container.new(_("Exporting SVG")) as proc:
  6841. exported_svg = obj.export_svg(scale_factor=scale_factor)
  6842. # Determine bounding area for svg export
  6843. bounds = obj.bounds()
  6844. size = obj.size()
  6845. # Convert everything to strings for use in the xml doc
  6846. svgwidth = str(size[0])
  6847. svgheight = str(size[1])
  6848. minx = str(bounds[0])
  6849. miny = str(bounds[1] - size[1])
  6850. uom = obj.units.lower()
  6851. # Add a SVG Header and footer to the svg output from shapely
  6852. # The transform flips the Y Axis so that everything renders
  6853. # properly within svg apps such as inkscape
  6854. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6855. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6856. svg_header += 'width="' + svgwidth + uom + '" '
  6857. svg_header += 'height="' + svgheight + uom + '" '
  6858. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6859. svg_header += '<g transform="scale(1,-1)">'
  6860. svg_footer = '</g> </svg>'
  6861. svg_elem = svg_header + exported_svg + svg_footer
  6862. # Parse the xml through a xml parser just to add line feeds
  6863. # and to make it look more pretty for the output
  6864. svgcode = parse_xml_string(svg_elem)
  6865. try:
  6866. with open(filename, 'w') as fp:
  6867. fp.write(svgcode.toprettyxml())
  6868. except PermissionError:
  6869. self.inform.emit('[WARNING] %s' %
  6870. _("Permission denied, saving not possible.\n"
  6871. "Most likely another app is holding the file open and not accessible."))
  6872. return 'fail'
  6873. if self.defaults["global_open_style"] is False:
  6874. self.file_opened.emit("SVG", filename)
  6875. self.file_saved.emit("SVG", filename)
  6876. self.inform.emit('[success] %s: %s' %
  6877. (_("SVG file exported to"), filename))
  6878. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  6879. """
  6880. Exports a Geometry Object to an SVG file in negative.
  6881. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6882. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  6883. :param filename: Path to the SVG file to save to.
  6884. :param boundary: thickness of a black border to surround all the features
  6885. :param scale_factor: factor by which to change/scale the thickness of the features
  6886. :param use_thread: if to be run in a separate thread; boolean
  6887. :return:
  6888. """
  6889. self.report_usage("export_negative()")
  6890. if filename is None:
  6891. filename = self.defaults["global_last_save_folder"]
  6892. self.log.debug("export_svg() negative")
  6893. try:
  6894. obj = self.collection.get_by_name(str(obj_name))
  6895. except:
  6896. # TODO: The return behavior has not been established... should raise exception?
  6897. return "Could not retrieve object: %s" % obj_name
  6898. try:
  6899. box = self.collection.get_by_name(str(box_name))
  6900. except:
  6901. # TODO: The return behavior has not been established... should raise exception?
  6902. return "Could not retrieve object: %s" % box_name
  6903. if box is None:
  6904. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  6905. (_("No object Box. Using instead"), obj))
  6906. box = obj
  6907. def make_negative_film():
  6908. exported_svg = obj.export_svg(scale_factor=scale_factor)
  6909. self.progress.emit(40)
  6910. # Determine bounding area for svg export
  6911. bounds = box.bounds()
  6912. size = box.size()
  6913. uom = obj.units.lower()
  6914. # Convert everything to strings for use in the xml doc
  6915. svgwidth = str(size[0] + (2 * boundary))
  6916. svgheight = str(size[1] + (2 * boundary))
  6917. minx = str(bounds[0] - boundary)
  6918. miny = str(bounds[1] + boundary + size[1])
  6919. miny_rect = str(bounds[1] - boundary)
  6920. # Add a SVG Header and footer to the svg output from shapely
  6921. # The transform flips the Y Axis so that everything renders
  6922. # properly within svg apps such as inkscape
  6923. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6924. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6925. svg_header += 'width="' + svgwidth + uom + '" '
  6926. svg_header += 'height="' + svgheight + uom + '" '
  6927. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6928. svg_header += '>'
  6929. svg_header += '<g transform="scale(1,-1)">'
  6930. svg_footer = '</g> </svg>'
  6931. self.progress.emit(60)
  6932. # Change the attributes of the exported SVG
  6933. # We don't need stroke-width - wrong, we do when we have lines with certain width
  6934. # We set opacity to maximum
  6935. # We set the color to WHITE
  6936. root = ET.fromstring(exported_svg)
  6937. for child in root:
  6938. child.set('fill', '#FFFFFF')
  6939. child.set('opacity', '1.0')
  6940. child.set('stroke', '#FFFFFF')
  6941. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  6942. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  6943. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  6944. first_svg_elem_tag = 'rect'
  6945. first_svg_elem_attribs = {
  6946. 'x': minx,
  6947. 'y': miny_rect,
  6948. 'width': svgwidth,
  6949. 'height': svgheight,
  6950. 'id': 'neg_rect',
  6951. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  6952. }
  6953. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  6954. exported_svg = ET.tostring(root)
  6955. svg_elem = svg_header + str(exported_svg) + svg_footer
  6956. self.progress.emit(80)
  6957. # Parse the xml through a xml parser just to add line feeds
  6958. # and to make it look more pretty for the output
  6959. doc = parse_xml_string(svg_elem)
  6960. try:
  6961. with open(filename, 'w') as fp:
  6962. fp.write(doc.toprettyxml())
  6963. except PermissionError:
  6964. self.inform.emit('[WARNING] %s' %
  6965. _("Permission denied, saving not possible.\n"
  6966. "Most likely another app is holding the file open and not accessible."))
  6967. return 'fail'
  6968. self.progress.emit(100)
  6969. if self.defaults["global_open_style"] is False:
  6970. self.file_opened.emit("SVG", filename)
  6971. self.file_saved.emit("SVG", filename)
  6972. self.inform.emit('[success] %s: %s' %
  6973. (_("SVG file exported to"), filename))
  6974. if use_thread is True:
  6975. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  6976. def job_thread_film(app_obj):
  6977. try:
  6978. make_negative_film()
  6979. except Exception as e:
  6980. proc.done()
  6981. return
  6982. proc.done()
  6983. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  6984. else:
  6985. make_negative_film()
  6986. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  6987. """
  6988. Exports a Geometry Object to an SVG file in positive black.
  6989. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6990. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  6991. :param filename: Path to the SVG file to save to.
  6992. :param scale_factor: factor by which to change/scale the thickness of the features
  6993. :param use_thread: if to be run in a separate thread; boolean
  6994. :return:
  6995. """
  6996. self.report_usage("export_svg_black()")
  6997. if filename is None:
  6998. filename = self.defaults["global_last_save_folder"]
  6999. self.log.debug("export_svg() black")
  7000. try:
  7001. obj = self.collection.get_by_name(str(obj_name))
  7002. except:
  7003. # TODO: The return behavior has not been established... should raise exception?
  7004. return "Could not retrieve object: %s" % obj_name
  7005. try:
  7006. box = self.collection.get_by_name(str(box_name))
  7007. except:
  7008. # TODO: The return behavior has not been established... should raise exception?
  7009. return "Could not retrieve object: %s" % box_name
  7010. if box is None:
  7011. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  7012. (_("No object Box. Using instead"), obj))
  7013. box = obj
  7014. def make_black_film():
  7015. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7016. self.progress.emit(40)
  7017. # Change the attributes of the exported SVG
  7018. # We don't need stroke-width
  7019. # We set opacity to maximum
  7020. # We set the colour to WHITE
  7021. root = ET.fromstring(exported_svg)
  7022. for child in root:
  7023. child.set('fill', '#000000')
  7024. child.set('opacity', '1.0')
  7025. child.set('stroke', '#000000')
  7026. exported_svg = ET.tostring(root)
  7027. # Determine bounding area for svg export
  7028. bounds = box.bounds()
  7029. size = box.size()
  7030. # This contain the measure units
  7031. uom = obj.units.lower()
  7032. # Define a boundary around SVG of about 1.0mm (~39mils)
  7033. if uom in "mm":
  7034. boundary = 1.0
  7035. else:
  7036. boundary = 0.0393701
  7037. self.progress.emit(80)
  7038. # Convert everything to strings for use in the xml doc
  7039. svgwidth = str(size[0] + (2 * boundary))
  7040. svgheight = str(size[1] + (2 * boundary))
  7041. minx = str(bounds[0] - boundary)
  7042. miny = str(bounds[1] + boundary + size[1])
  7043. self.log.debug(minx)
  7044. self.log.debug(miny)
  7045. # Add a SVG Header and footer to the svg output from shapely
  7046. # The transform flips the Y Axis so that everything renders
  7047. # properly within svg apps such as inkscape
  7048. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7049. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7050. svg_header += 'width="' + svgwidth + uom + '" '
  7051. svg_header += 'height="' + svgheight + uom + '" '
  7052. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7053. svg_header += '>'
  7054. svg_header += '<g transform="scale(1,-1)">'
  7055. svg_footer = '</g> </svg>'
  7056. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  7057. self.progress.emit(90)
  7058. # Parse the xml through a xml parser just to add line feeds
  7059. # and to make it look more pretty for the output
  7060. doc = parse_xml_string(svg_elem)
  7061. try:
  7062. with open(filename, 'w') as fp:
  7063. fp.write(doc.toprettyxml())
  7064. except PermissionError:
  7065. self.inform.emit('[WARNING] %s' %
  7066. _("Permission denied, saving not possible.\n"
  7067. "Most likely another app is holding the file open and not accessible."))
  7068. return 'fail'
  7069. self.progress.emit(100)
  7070. if self.defaults["global_open_style"] is False:
  7071. self.file_opened.emit("SVG", filename)
  7072. self.file_saved.emit("SVG", filename)
  7073. self.inform.emit('[success] %s: %s' %
  7074. (_("SVG file exported to"), filename))
  7075. if use_thread is True:
  7076. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  7077. def job_thread_film(app_obj):
  7078. try:
  7079. make_black_film()
  7080. except Exception as e:
  7081. proc.done()
  7082. return
  7083. proc.done()
  7084. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  7085. else:
  7086. make_black_film()
  7087. def save_source_file(self, obj_name, filename, use_thread=True):
  7088. """
  7089. Exports a FlatCAM Object to an Gerber/Excellon file.
  7090. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7091. :param filename: Path to the Gerber file to save to.
  7092. :param use_thread: if to be run in a separate thread
  7093. :return:
  7094. """
  7095. self.report_usage("save source file()")
  7096. if filename is None:
  7097. filename = self.defaults["global_last_save_folder"]
  7098. self.log.debug("save source file()")
  7099. obj = self.collection.get_by_name(obj_name)
  7100. file_string = StringIO(obj.source_file)
  7101. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7102. try:
  7103. with open(filename, 'w') as file:
  7104. file.writelines('G04*\n')
  7105. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7106. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7107. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7108. file.writelines('G04 Created on : %s*\n' % time_string)
  7109. for line in file_string:
  7110. file.writelines(line)
  7111. except PermissionError:
  7112. self.inform.emit('[WARNING] %s' %
  7113. _("Permission denied, saving not possible.\n"
  7114. "Most likely another app is holding the file open and not accessible."))
  7115. return 'fail'
  7116. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7117. """
  7118. Exports a Excellon Object to an Excellon file.
  7119. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7120. :param filename: Path to the Excellon file to save to.
  7121. :param use_thread: if to be run in a separate thread
  7122. :return:
  7123. """
  7124. self.report_usage("export_excellon()")
  7125. if filename is None:
  7126. filename = self.defaults["global_last_save_folder"]
  7127. self.log.debug("export_excellon()")
  7128. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7129. self.defaults["excellon_exp_decimals"]
  7130. )
  7131. units = ''
  7132. if local_use is None:
  7133. try:
  7134. obj = self.collection.get_by_name(str(obj_name))
  7135. except:
  7136. # TODO: The return behavior has not been established... should raise exception?
  7137. return "Could not retrieve object: %s" % obj_name
  7138. else:
  7139. obj = local_use
  7140. # updated units
  7141. eunits = self.defaults["excellon_exp_units"]
  7142. ewhole = self.defaults["excellon_exp_integer"]
  7143. efract = self.defaults["excellon_exp_decimals"]
  7144. ezeros = self.defaults["excellon_exp_zeros"]
  7145. eformat = self.defaults["excellon_exp_format"]
  7146. slot_type = self.defaults["excellon_exp_slot_type"]
  7147. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7148. if fc_units == 'MM':
  7149. factor = 1 if eunits == 'METRIC' else 0.03937
  7150. else:
  7151. factor = 25.4 if eunits == 'METRIC' else 1
  7152. def make_excellon():
  7153. try:
  7154. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7155. header = 'M48\n'
  7156. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7157. (str(self.version), str(self.version_date))
  7158. header += ';Filename: %s' % str(obj_name) + '\n'
  7159. header += ';Created on : %s' % time_str + '\n'
  7160. if eformat == 'dec':
  7161. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7162. header += eunits + '\n'
  7163. for tool in obj.tools:
  7164. if eunits == 'METRIC':
  7165. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7166. tool=str(tool),
  7167. dec=2)
  7168. else:
  7169. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7170. tool=str(tool),
  7171. dec=4)
  7172. else:
  7173. if ezeros == 'LZ':
  7174. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7175. form='ndec', e_zeros='LZ', factor=factor,
  7176. slot_type=slot_type)
  7177. header += '%s,%s\n' % (eunits, 'LZ')
  7178. header += format_exc
  7179. for tool in obj.tools:
  7180. if eunits == 'METRIC':
  7181. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7182. tool=str(tool),
  7183. dec=2)
  7184. else:
  7185. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7186. tool=str(tool),
  7187. dec=4)
  7188. else:
  7189. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7190. form='ndec', e_zeros='TZ', factor=factor,
  7191. slot_type=slot_type)
  7192. header += '%s,%s\n' % (eunits, 'TZ')
  7193. header += format_exc
  7194. for tool in obj.tools:
  7195. if eunits == 'METRIC':
  7196. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7197. tool=str(tool),
  7198. dec=2)
  7199. else:
  7200. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7201. tool=str(tool),
  7202. dec=4)
  7203. header += '%\n'
  7204. footer = 'M30\n'
  7205. exported_excellon = header
  7206. exported_excellon += excellon_code
  7207. exported_excellon += footer
  7208. if local_use is None:
  7209. try:
  7210. with open(filename, 'w') as fp:
  7211. fp.write(exported_excellon)
  7212. except PermissionError:
  7213. self.inform.emit('[WARNING] %s' %
  7214. _("Permission denied, saving not possible.\n"
  7215. "Most likely another app is holding the file open and not accessible."))
  7216. return 'fail'
  7217. if self.defaults["global_open_style"] is False:
  7218. self.file_opened.emit("Excellon", filename)
  7219. self.file_saved.emit("Excellon", filename)
  7220. self.inform.emit('[success] %s: %s' %
  7221. (_("Excellon file exported to"), filename))
  7222. else:
  7223. return exported_excellon
  7224. except Exception as e:
  7225. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7226. return 'fail'
  7227. if use_thread is True:
  7228. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7229. def job_thread_exc(app_obj):
  7230. ret = make_excellon()
  7231. if ret == 'fail':
  7232. self.inform.emit('[ERROR_NOTCL] %s' %
  7233. _('Could not export Excellon file.'))
  7234. return
  7235. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7236. else:
  7237. ret = make_excellon()
  7238. if ret == 'fail':
  7239. self.inform.emit('[ERROR_NOTCL] %s' %
  7240. _('Could not export Excellon file.'))
  7241. return 'fail'
  7242. if local_use is not None:
  7243. return ret
  7244. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7245. """
  7246. Exports a Gerber Object to an Gerber file.
  7247. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7248. :param filename: Path to the Gerber file to save to.
  7249. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7250. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7251. :param use_thread: if to be run in a separate thread
  7252. :return:
  7253. """
  7254. self.report_usage("export_gerber()")
  7255. if filename is None:
  7256. filename = self.defaults["global_last_save_folder"]
  7257. self.log.debug("export_gerber()")
  7258. if local_use is None:
  7259. try:
  7260. obj = self.collection.get_by_name(str(obj_name))
  7261. except:
  7262. # TODO: The return behavior has not been established... should raise exception?
  7263. return "Could not retrieve object: %s" % obj_name
  7264. else:
  7265. obj = local_use
  7266. # updated units
  7267. gunits = self.defaults["gerber_exp_units"]
  7268. gwhole = self.defaults["gerber_exp_integer"]
  7269. gfract = self.defaults["gerber_exp_decimals"]
  7270. gzeros = self.defaults["gerber_exp_zeros"]
  7271. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7272. if fc_units == 'MM':
  7273. factor = 1 if gunits == 'MM' else 0.03937
  7274. else:
  7275. factor = 25.4 if gunits == 'MM' else 1
  7276. def make_gerber():
  7277. try:
  7278. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7279. header = 'G04*\n'
  7280. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7281. (str(self.version), str(self.version_date))
  7282. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7283. header += 'G04 Created on : %s*' % time_str + '\n'
  7284. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7285. header += "%MO{units}*%\n".format(units=gunits)
  7286. for apid in obj.apertures:
  7287. if obj.apertures[apid]['type'] == 'C':
  7288. header += "%ADD{apid}{type},{size}*%\n".format(
  7289. apid=str(apid),
  7290. type='C',
  7291. size=(factor * obj.apertures[apid]['size'])
  7292. )
  7293. elif obj.apertures[apid]['type'] == 'R':
  7294. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7295. apid=str(apid),
  7296. type='R',
  7297. width=(factor * obj.apertures[apid]['width']),
  7298. height=(factor * obj.apertures[apid]['height'])
  7299. )
  7300. elif obj.apertures[apid]['type'] == 'O':
  7301. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7302. apid=str(apid),
  7303. type='O',
  7304. width=(factor * obj.apertures[apid]['width']),
  7305. height=(factor * obj.apertures[apid]['height'])
  7306. )
  7307. header += '\n'
  7308. # obsolete units but some software may need it
  7309. if gunits == 'IN':
  7310. header += 'G70*\n'
  7311. else:
  7312. header += 'G71*\n'
  7313. # Absolute Mode
  7314. header += 'G90*\n'
  7315. header += 'G01*\n'
  7316. # positive polarity
  7317. header += '%LPD*%\n'
  7318. footer = 'M02*\n'
  7319. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7320. exported_gerber = header
  7321. exported_gerber += gerber_code
  7322. exported_gerber += footer
  7323. if local_use is None:
  7324. try:
  7325. with open(filename, 'w') as fp:
  7326. fp.write(exported_gerber)
  7327. except PermissionError:
  7328. self.inform.emit('[WARNING] %s' %
  7329. _("Permission denied, saving not possible.\n"
  7330. "Most likely another app is holding the file open and not accessible."))
  7331. return 'fail'
  7332. if self.defaults["global_open_style"] is False:
  7333. self.file_opened.emit("Gerber", filename)
  7334. self.file_saved.emit("Gerber", filename)
  7335. self.inform.emit('[success] %s: %s' %
  7336. (_("Gerber file exported to"), filename))
  7337. else:
  7338. return exported_gerber
  7339. except Exception as e:
  7340. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7341. return 'fail'
  7342. if use_thread is True:
  7343. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7344. def job_thread_grb(app_obj):
  7345. ret = make_gerber()
  7346. if ret == 'fail':
  7347. self.inform.emit('[ERROR_NOTCL] %s' %
  7348. _('Could not export Gerber file.'))
  7349. return
  7350. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7351. else:
  7352. ret = make_gerber()
  7353. if ret == 'fail':
  7354. self.inform.emit('[ERROR_NOTCL] %s' %
  7355. _('Could not export Gerber file.'))
  7356. return 'fail'
  7357. if local_use is not None:
  7358. return ret
  7359. def export_dxf(self, obj_name, filename, use_thread=True):
  7360. """
  7361. Exports a Geometry Object to an DXF file.
  7362. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7363. :param filename: Path to the DXF file to save to.
  7364. :param use_thread: if to be run in a separate thread
  7365. :return:
  7366. """
  7367. self.report_usage("export_dxf()")
  7368. if filename is None:
  7369. filename = self.defaults["global_last_save_folder"]
  7370. self.log.debug("export_dxf()")
  7371. format_exc = ''
  7372. units = ''
  7373. try:
  7374. obj = self.collection.get_by_name(str(obj_name))
  7375. except:
  7376. # TODO: The return behavior has not been established... should raise exception?
  7377. return "Could not retrieve object: %s" % obj_name
  7378. # updated units
  7379. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7380. if units == 'IN' or units == 'INCH':
  7381. units = 'INCH'
  7382. elif units == 'MM' or units == 'METIRC':
  7383. units ='METRIC'
  7384. def make_dxf():
  7385. try:
  7386. dxf_code = obj.export_dxf()
  7387. dxf_code.saveas(filename)
  7388. if self.defaults["global_open_style"] is False:
  7389. self.file_opened.emit("DXF", filename)
  7390. self.file_saved.emit("DXF", filename)
  7391. self.inform.emit('[success] %s: %s' %
  7392. (_("DXF file exported to"), filename))
  7393. except:
  7394. return 'fail'
  7395. if use_thread is True:
  7396. with self.proc_container.new(_("Exporting DXF")) as proc:
  7397. def job_thread_exc(app_obj):
  7398. ret = make_dxf()
  7399. if ret == 'fail':
  7400. app_obj.inform.emit('[WARNING_NOTCL] %s' %
  7401. _('Could not export DXF file.'))
  7402. return
  7403. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7404. else:
  7405. ret = make_dxf()
  7406. if ret == 'fail':
  7407. self.inform.emit('[WARNING_NOTCL] %s' %
  7408. _('Could not export DXF file.'))
  7409. return
  7410. def import_svg(self, filename, geo_type='geometry', outname=None):
  7411. """
  7412. Adds a new Geometry Object to the projects and populates
  7413. it with shapes extracted from the SVG file.
  7414. :param filename: Path to the SVG file.
  7415. :param outname:
  7416. :return:
  7417. """
  7418. self.report_usage("import_svg()")
  7419. obj_type = ""
  7420. if geo_type is None or geo_type == "geometry":
  7421. obj_type = "geometry"
  7422. elif geo_type == "gerber":
  7423. obj_type = geo_type
  7424. else:
  7425. self.inform.emit('[ERROR_NOTCL] %s' %
  7426. _("Not supported type is picked as parameter. "
  7427. "Only Geometry and Gerber are supported"))
  7428. return
  7429. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7430. def obj_init(geo_obj, app_obj):
  7431. geo_obj.import_svg(filename, obj_type, units=units)
  7432. geo_obj.multigeo = False
  7433. with self.proc_container.new(_("Importing SVG")) as proc:
  7434. # Object name
  7435. name = outname or filename.split('/')[-1].split('\\')[-1]
  7436. self.new_object(obj_type, name, obj_init, autoselected=False)
  7437. self.progress.emit(20)
  7438. # Register recent file
  7439. self.file_opened.emit("svg", filename)
  7440. # GUI feedback
  7441. self.inform.emit('[success] %s: %s' %
  7442. (_("Opened"), filename))
  7443. self.progress.emit(100)
  7444. def import_dxf(self, filename, geo_type='geometry', outname=None):
  7445. """
  7446. Adds a new Geometry Object to the projects and populates
  7447. it with shapes extracted from the DXF file.
  7448. :param filename: Path to the DXF file.
  7449. :param outname:
  7450. :type putname: str
  7451. :return:
  7452. """
  7453. self.report_usage("import_dxf()")
  7454. obj_type = ""
  7455. if geo_type is None or geo_type == "geometry":
  7456. obj_type = "geometry"
  7457. elif geo_type == "gerber":
  7458. obj_type = geo_type
  7459. else:
  7460. self.inform.emit('[ERROR_NOTCL] %s' %
  7461. _("Not supported type is picked as parameter. "
  7462. "Only Geometry and Gerber are supported"))
  7463. return
  7464. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7465. def obj_init(geo_obj, app_obj):
  7466. geo_obj.import_dxf(filename, obj_type, units=units)
  7467. geo_obj.multigeo = False
  7468. with self.proc_container.new(_("Importing DXF")) as proc:
  7469. # Object name
  7470. name = outname or filename.split('/')[-1].split('\\')[-1]
  7471. self.new_object(obj_type, name, obj_init, autoselected=False)
  7472. self.progress.emit(20)
  7473. # Register recent file
  7474. self.file_opened.emit("dxf", filename)
  7475. # GUI feedback
  7476. self.inform.emit('[success] %s: %s' %
  7477. (_("Opened"), filename))
  7478. self.progress.emit(100)
  7479. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  7480. """
  7481. Adds a new Geometry Object to the projects and populates
  7482. it with shapes extracted from the SVG file.
  7483. :param filename: Path to the SVG file.
  7484. :param o_type: type of FlatCAM objeect
  7485. :param dpi: dot per inch
  7486. :param mode: black or color
  7487. :param mask: dictate the level of detail
  7488. :param outname: name for the resulting file
  7489. :return:
  7490. """
  7491. self.report_usage("import_image()")
  7492. if o_type is None or o_type == "geometry":
  7493. obj_type = "geometry"
  7494. elif o_type == "gerber":
  7495. obj_type = o_type
  7496. else:
  7497. self.inform.emit('[ERROR_NOTCL] %s' %
  7498. _("Not supported type is picked as parameter. "
  7499. "Only Geometry and Gerber are supported"))
  7500. return
  7501. def obj_init(geo_obj, app_obj):
  7502. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  7503. geo_obj.multigeo = False
  7504. with self.proc_container.new(_("Importing Image")) as proc:
  7505. # Object name
  7506. name = outname or filename.split('/')[-1].split('\\')[-1]
  7507. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  7508. self.new_object(obj_type, name, obj_init)
  7509. self.progress.emit(20)
  7510. # Register recent file
  7511. self.file_opened.emit("image", filename)
  7512. # GUI feedback
  7513. self.inform.emit('[success] %s: %s' %
  7514. (_("Opened"), filename))
  7515. self.progress.emit(100)
  7516. def open_gerber(self, filename, outname=None):
  7517. """
  7518. Opens a Gerber file, parses it and creates a new object for
  7519. it in the program. Thread-safe.
  7520. :param outname: Name of the resulting object. None causes the
  7521. name to be that of the file.
  7522. :param filename: Gerber file filename
  7523. :type filename: str
  7524. :param follow: If true, the parser will not create polygons, just lines
  7525. following the gerber path.
  7526. :type follow: bool
  7527. :return: None
  7528. """
  7529. # How the object should be initialized
  7530. def obj_init(gerber_obj, app_obj):
  7531. assert isinstance(gerber_obj, FlatCAMGerber), \
  7532. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  7533. # Opening the file happens here
  7534. self.progress.emit(30)
  7535. try:
  7536. gerber_obj.parse_file(filename)
  7537. except IOError:
  7538. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7539. (_("Failed to open file"), filename))
  7540. app_obj.progress.emit(0)
  7541. return "fail"
  7542. except ParseError as err:
  7543. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' %
  7544. (_("Failed to parse file"), filename, str(err)))
  7545. app_obj.progress.emit(0)
  7546. self.log.error(str(err))
  7547. return "fail"
  7548. except Exception as e:
  7549. log.debug("App.open_gerber() --> %s" % str(e))
  7550. msg = '[ERROR] %s' % \
  7551. _("An internal error has occurred. See shell.\n")
  7552. msg += traceback.format_exc()
  7553. app_obj.inform.emit(msg)
  7554. return "fail"
  7555. if gerber_obj.is_empty():
  7556. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  7557. # self.collection.set_active(gerber_obj.options["name"])
  7558. # self.collection.delete_active()
  7559. self.inform.emit('[ERROR_NOTCL] %s' %
  7560. _("Object is not Gerber file or empty. Aborting object creation."))
  7561. return "fail"
  7562. # Further parsing
  7563. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  7564. App.log.debug("open_gerber()")
  7565. with self.proc_container.new(_("Opening Gerber")) as proc:
  7566. self.progress.emit(10)
  7567. # Object name
  7568. name = outname or filename.split('/')[-1].split('\\')[-1]
  7569. # # ## Object creation # ##
  7570. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  7571. if ret == 'fail':
  7572. self.inform.emit('[ERROR_NOTCL]%s' %
  7573. _(' Open Gerber failed. Probable not a Gerber file.'))
  7574. return
  7575. # Register recent file
  7576. self.file_opened.emit("gerber", filename)
  7577. self.progress.emit(100)
  7578. # GUI feedback
  7579. self.inform.emit('[success] %s: %s' %
  7580. (_("Opened"), filename))
  7581. def open_excellon(self, filename, outname=None):
  7582. """
  7583. Opens an Excellon file, parses it and creates a new object for
  7584. it in the program. Thread-safe.
  7585. :param outname: Name of the resulting object. None causes the
  7586. name to be that of the file.
  7587. :param filename: Excellon file filename
  7588. :type filename: str
  7589. :return: None
  7590. """
  7591. App.log.debug("open_excellon()")
  7592. # How the object should be initialized
  7593. def obj_init(excellon_obj, app_obj):
  7594. # self.progress.emit(20)
  7595. try:
  7596. ret = excellon_obj.parse_file(filename=filename)
  7597. if ret == "fail":
  7598. log.debug("Excellon parsing failed.")
  7599. self.inform.emit('[ERROR_NOTCL] %s' %
  7600. _("This is not Excellon file."))
  7601. return "fail"
  7602. except IOError:
  7603. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7604. (_("Cannot open file"), filename))
  7605. log.debug("Could not open Excellon object.")
  7606. self.progress.emit(0) # TODO: self and app_bjj mixed
  7607. return "fail"
  7608. except:
  7609. msg = '[ERROR_NOTCL] %s' % \
  7610. _("An internal error has occurred. See shell.\n")
  7611. msg += traceback.format_exc()
  7612. app_obj.inform.emit(msg)
  7613. return "fail"
  7614. ret = excellon_obj.create_geometry()
  7615. if ret == 'fail':
  7616. log.debug("Could not create geometry for Excellon object.")
  7617. return "fail"
  7618. for tool in excellon_obj.tools:
  7619. if excellon_obj.tools[tool]['solid_geometry']:
  7620. return
  7621. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7622. (_("No geometry found in file"), filename))
  7623. return "fail"
  7624. with self.proc_container.new(_("Opening Excellon.")):
  7625. # Object name
  7626. name = outname or filename.split('/')[-1].split('\\')[-1]
  7627. ret_val = self.new_object("excellon", name, obj_init, autoselected=False)
  7628. if ret_val == 'fail':
  7629. self.inform.emit('[ERROR_NOTCL] %s' %
  7630. _('Open Excellon file failed. Probable not an Excellon file.'))
  7631. return
  7632. # Register recent file
  7633. self.file_opened.emit("excellon", filename)
  7634. # GUI feedback
  7635. self.inform.emit('[success] %s: %s' %
  7636. (_("Opened"), filename))
  7637. def open_gcode(self, filename, outname=None):
  7638. """
  7639. Opens a G-gcode file, parses it and creates a new object for
  7640. it in the program. Thread-safe.
  7641. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7642. :param filename: G-code file filename
  7643. :type filename: str
  7644. :return: None
  7645. """
  7646. App.log.debug("open_gcode()")
  7647. # How the object should be initialized
  7648. def obj_init(job_obj, app_obj_):
  7649. """
  7650. :param job_obj: the resulting object
  7651. :type app_obj_: App
  7652. """
  7653. assert isinstance(app_obj_, App), \
  7654. "Initializer expected App, got %s" % type(app_obj_)
  7655. self.progress.emit(10)
  7656. try:
  7657. f = open(filename)
  7658. gcode = f.read()
  7659. f.close()
  7660. except IOError:
  7661. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  7662. (_("Failed to open"), filename))
  7663. self.progress.emit(0)
  7664. return "fail"
  7665. job_obj.gcode = gcode
  7666. self.progress.emit(20)
  7667. ret = job_obj.gcode_parse()
  7668. if ret == "fail":
  7669. self.inform.emit('[ERROR_NOTCL] %s' %
  7670. _("This is not GCODE"))
  7671. return "fail"
  7672. self.progress.emit(60)
  7673. job_obj.create_geometry()
  7674. with self.proc_container.new(_("Opening G-Code.")):
  7675. # Object name
  7676. name = outname or filename.split('/')[-1].split('\\')[-1]
  7677. # New object creation and file processing
  7678. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  7679. if ret == 'fail':
  7680. self.inform.emit('[ERROR_NOTCL] %s' %
  7681. _("Failed to create CNCJob Object. Probable not a GCode file.\n "
  7682. "Attempting to create a FlatCAM CNCJob Object from "
  7683. "G-Code file failed during processing"))
  7684. return "fail"
  7685. # Register recent file
  7686. self.file_opened.emit("cncjob", filename)
  7687. # GUI feedback
  7688. self.inform.emit('[success] %s: %s' %
  7689. (_("Opened"), filename))
  7690. self.progress.emit(100)
  7691. def open_config_file(self, filename, run_from_arg=None):
  7692. """
  7693. Loads a config file from the specified file.
  7694. :param filename: Name of the file from which to load.
  7695. :type filename: str
  7696. :return: None
  7697. """
  7698. App.log.debug("Opening config file: " + filename)
  7699. # add the tab if it was closed
  7700. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  7701. # first clear previous text in text editor (if any)
  7702. self.ui.code_editor.clear()
  7703. # Switch plot_area to CNCJob tab
  7704. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  7705. try:
  7706. if filename:
  7707. f = QtCore.QFile(filename)
  7708. if f.open(QtCore.QIODevice.ReadOnly):
  7709. stream = QtCore.QTextStream(f)
  7710. gcode_edited = stream.readAll()
  7711. self.ui.code_editor.setPlainText(gcode_edited)
  7712. f.close()
  7713. except IOError:
  7714. App.log.error("Failed to open config file: %s" % filename)
  7715. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7716. (_("Failed to open config file"), filename))
  7717. return
  7718. def open_project(self, filename, run_from_arg=None):
  7719. """
  7720. Loads a project from the specified file.
  7721. 1) Loads and parses file
  7722. 2) Registers the file as recently opened.
  7723. 3) Calls on_file_new()
  7724. 4) Updates options
  7725. 5) Calls new_object() with the object's from_dict() as init method.
  7726. 6) Calls plot_all()
  7727. :param filename: Name of the file from which to load.
  7728. :type filename: str
  7729. :param run_from_arg: True if run for arguments
  7730. :return: None
  7731. """
  7732. App.log.debug("Opening project: " + filename)
  7733. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7734. # Open and parse an uncompressed Project file
  7735. try:
  7736. f = open(filename, 'r')
  7737. except IOError:
  7738. App.log.error("Failed to open project file: %s" % filename)
  7739. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7740. (_("Failed to open project file"), filename))
  7741. return
  7742. try:
  7743. d = json.load(f, object_hook=dict2obj)
  7744. except Exception as e:
  7745. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7746. (filename, str(e)))
  7747. f.close()
  7748. # Open and parse a compressed Project file
  7749. try:
  7750. with lzma.open(filename) as f:
  7751. file_content = f.read().decode('utf-8')
  7752. d = json.loads(file_content, object_hook=dict2obj)
  7753. except Exception as e:
  7754. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7755. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7756. (_("Failed to open project file"), filename))
  7757. return
  7758. # Clear the current project
  7759. # # NOT THREAD SAFE # ##
  7760. if run_from_arg is True:
  7761. pass
  7762. else:
  7763. self.on_file_new()
  7764. # Project options
  7765. self.options.update(d['options'])
  7766. self.project_filename = filename
  7767. self.set_screen_units(self.options["units"])
  7768. # Re create objects
  7769. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7770. for obj in d['objs']:
  7771. def obj_init(obj_inst, app_inst):
  7772. obj_inst.from_dict(obj)
  7773. App.log.debug("Recreating from opened project an %s object: %s" %
  7774. (obj['kind'].capitalize(), obj['options']['name']))
  7775. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7776. obj['kind'].upper(),
  7777. obj['options']['name']
  7778. )
  7779. )
  7780. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  7781. # self.plot_all()
  7782. self.inform.emit('[success] %s: %s' %
  7783. (_("Project loaded from"), filename))
  7784. self.should_we_save = False
  7785. self.file_opened.emit("project", filename)
  7786. self.set_ui_title(name=self.project_filename)
  7787. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7788. def propagate_defaults(self, silent=False):
  7789. """
  7790. This method is used to set default values in classes. It's
  7791. an alternative to project options but allows the use
  7792. of values invisible to the user.
  7793. :return: None
  7794. """
  7795. if silent is False:
  7796. self.log.debug("propagate_defaults()")
  7797. # Which objects to update the given parameters.
  7798. routes = {
  7799. "global_zdownrate": CNCjob,
  7800. "excellon_zeros": Excellon,
  7801. "excellon_format_upper_in": Excellon,
  7802. "excellon_format_lower_in": Excellon,
  7803. "excellon_format_upper_mm": Excellon,
  7804. "excellon_format_lower_mm": Excellon,
  7805. "excellon_units": Excellon,
  7806. "gerber_use_buffer_for_union": Gerber,
  7807. "geometry_multidepth": Geometry
  7808. }
  7809. for param in routes:
  7810. if param in routes[param].defaults:
  7811. try:
  7812. routes[param].defaults[param] = self.defaults[param]
  7813. if silent is False:
  7814. self.log.debug(" " + param + " OK")
  7815. except KeyError:
  7816. if silent is False:
  7817. self.log.debug(" ERROR: " + param + " not in defaults.")
  7818. else:
  7819. # Try extracting the name:
  7820. # classname_param here is param in the object
  7821. if param.find(routes[param].__name__.lower() + "_") == 0:
  7822. p = param[len(routes[param].__name__) + 1:]
  7823. if p in routes[param].defaults:
  7824. routes[param].defaults[p] = self.defaults[param]
  7825. if silent is False:
  7826. self.log.debug(" " + param + " OK!")
  7827. def restore_main_win_geom(self):
  7828. try:
  7829. self.ui.setGeometry(self.defaults["global_def_win_x"],
  7830. self.defaults["global_def_win_y"],
  7831. self.defaults["global_def_win_w"],
  7832. self.defaults["global_def_win_h"])
  7833. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  7834. settings = QSettings("Open Source", "FlatCAM")
  7835. if settings.contains("maximized_gui"):
  7836. maximized_ui = settings.value('maximized_gui', type=bool)
  7837. if maximized_ui is True:
  7838. self.ui.showMaximized()
  7839. except KeyError as e:
  7840. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  7841. def plot_all(self, zoom=True):
  7842. """
  7843. Re-generates all plots from all objects.
  7844. :return: None
  7845. """
  7846. self.log.debug("Plot_all()")
  7847. for obj in self.collection.get_list():
  7848. def worker_task(obj):
  7849. with self.proc_container.new("Plotting"):
  7850. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7851. if zoom:
  7852. self.object_plotted.emit(obj)
  7853. # Send to worker
  7854. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  7855. def register_folder(self, filename):
  7856. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7857. def register_save_folder(self, filename):
  7858. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7859. def set_progress_bar(self, percentage, text=""):
  7860. self.ui.progress_bar.setValue(int(percentage))
  7861. def setup_shell(self):
  7862. """
  7863. Creates shell functions. Runs once at startup.
  7864. :return: None
  7865. """
  7866. self.log.debug("setup_shell()")
  7867. def shelp(p=None):
  7868. if not p:
  7869. return _("Available commands:\n") + \
  7870. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  7871. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  7872. if p not in commands:
  7873. return "Unknown command: %s" % p
  7874. return commands[p]["help"]
  7875. # --- Migrated to new architecture ---
  7876. # def options(name):
  7877. # ops = self.collection.get_by_name(str(name)).options
  7878. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  7879. def h(*args):
  7880. """
  7881. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  7882. and standalone parameters into list.
  7883. """
  7884. kwa = {}
  7885. a = []
  7886. n = len(args)
  7887. name = None
  7888. for i in range(n):
  7889. match = re.search(r'^-([a-zA-Z].*)', args[i])
  7890. if match:
  7891. assert name is None
  7892. name = match.group(1)
  7893. continue
  7894. if name is None:
  7895. a.append(args[i])
  7896. else:
  7897. kwa[name] = args[i]
  7898. name = None
  7899. return a, kwa
  7900. @contextmanager
  7901. def wait_signal(signal, timeout=10000):
  7902. """
  7903. Block loop until signal emitted, timeout (ms) elapses
  7904. or unhandled exception happens in a thread.
  7905. :param timeout: time after which the loop is exited
  7906. :param signal: Signal to wait for.
  7907. """
  7908. loop = QtCore.QEventLoop()
  7909. # Normal termination
  7910. signal.connect(loop.quit)
  7911. # Termination by exception in thread
  7912. self.thread_exception.connect(loop.quit)
  7913. status = {'timed_out': False}
  7914. def report_quit():
  7915. status['timed_out'] = True
  7916. loop.quit()
  7917. yield
  7918. # Temporarily change how exceptions are managed.
  7919. oeh = sys.excepthook
  7920. ex = []
  7921. def except_hook(type_, value, traceback_):
  7922. ex.append(value)
  7923. oeh(type_, value, traceback_)
  7924. sys.excepthook = except_hook
  7925. # Terminate on timeout
  7926. if timeout is not None:
  7927. QtCore.QTimer.singleShot(timeout, report_quit)
  7928. # # ## Block ## ##
  7929. loop.exec_()
  7930. # Restore exception management
  7931. sys.excepthook = oeh
  7932. if ex:
  7933. self.raiseTclError(str(ex[0]))
  7934. if status['timed_out']:
  7935. raise Exception('Timed out!')
  7936. def make_docs():
  7937. output = ''
  7938. import collections
  7939. od = collections.OrderedDict(sorted(commands.items()))
  7940. for cmd_, val in od.items():
  7941. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  7942. t = val['help']
  7943. usage_i = t.find('>')
  7944. if usage_i < 0:
  7945. expl = t
  7946. output += expl + '\n\n'
  7947. continue
  7948. expl = t[:usage_i - 1]
  7949. output += expl + '\n\n'
  7950. end_usage_i = t[usage_i:].find('\n')
  7951. if end_usage_i < 0:
  7952. end_usage_i = len(t[usage_i:])
  7953. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  7954. else:
  7955. extras = t[usage_i+end_usage_i+1:]
  7956. parts = [s.strip() for s in extras.split('\n')]
  7957. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  7958. for p in parts:
  7959. output += ' ' + p + '\n\n'
  7960. return output
  7961. '''
  7962. Howto implement TCL shell commands:
  7963. All parameters passed to command should be possible to set as None and test it afterwards.
  7964. This is because we need to see error caused in tcl,
  7965. if None value as default parameter is not allowed TCL will return empty error.
  7966. Use:
  7967. def mycommand(name=None,...):
  7968. Test it like this:
  7969. if name is None:
  7970. self.raise_tcl_error('Argument name is missing.')
  7971. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  7972. otherwise we will miss it and processing will silently continue.
  7973. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  7974. which is catched in exec_command and displayed in TCL shell console with red background.
  7975. Error in console is displayed with TCL trace.
  7976. This behavior works only within main thread,
  7977. errors with promissed tasks can be catched and detected only with log.
  7978. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  7979. TCL shell.
  7980. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  7981. '''
  7982. commands = {
  7983. 'help': {
  7984. 'fcn': shelp,
  7985. 'help': _("Shows list of commands.")
  7986. },
  7987. }
  7988. # Import/overwrite tcl commands as objects of TclCommand descendants
  7989. # This modifies the variable 'commands'.
  7990. tclCommands.register_all_commands(self, commands)
  7991. # Add commands to the tcl interpreter
  7992. for cmd in commands:
  7993. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  7994. # Make the tcl puts function return instead of print to stdout
  7995. self.tcl.eval('''
  7996. rename puts original_puts
  7997. proc puts {args} {
  7998. if {[llength $args] == 1} {
  7999. return "[lindex $args 0]"
  8000. } else {
  8001. eval original_puts $args
  8002. }
  8003. }
  8004. ''')
  8005. def setup_recent_items(self):
  8006. # TODO: Move this to constructor
  8007. icons = {
  8008. "gerber": "share/flatcam_icon16.png",
  8009. "excellon": "share/drill16.png",
  8010. 'geometry': "share/geometry16.png",
  8011. "cncjob": "share/cnc16.png",
  8012. "project": "share/project16.png",
  8013. "svg": "share/geometry16.png",
  8014. "dxf": "share/dxf16.png",
  8015. "pdf": "share/pdf32.png",
  8016. "image": "share/image16.png"
  8017. }
  8018. openers = {
  8019. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8020. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8021. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8022. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8023. 'project': self.open_project,
  8024. 'svg': self.import_svg,
  8025. 'dxf': self.import_dxf,
  8026. 'image': self.import_image,
  8027. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8028. }
  8029. # Open recent file for files
  8030. try:
  8031. f = open(self.data_path + '/recent.json')
  8032. except IOError:
  8033. App.log.error("Failed to load recent item list.")
  8034. self.inform.emit('[ERROR_NOTCL] %s' %
  8035. _("Failed to load recent item list."))
  8036. return
  8037. try:
  8038. self.recent = json.load(f)
  8039. except json.scanner.JSONDecodeError:
  8040. App.log.error("Failed to parse recent item list.")
  8041. self.inform.emit('[ERROR_NOTCL] %s' %
  8042. _("Failed to parse recent item list."))
  8043. f.close()
  8044. return
  8045. f.close()
  8046. # Open recent file for projects
  8047. try:
  8048. fp = open(self.data_path + '/recent_projects.json')
  8049. except IOError:
  8050. App.log.error("Failed to load recent project item list.")
  8051. self.inform.emit('[ERROR_NOTCL] %s' %
  8052. _("Failed to load recent projects item list."))
  8053. return
  8054. try:
  8055. self.recent_projects = json.load(fp)
  8056. except json.scanner.JSONDecodeError:
  8057. App.log.error("Failed to parse recent project item list.")
  8058. self.inform.emit('[ERROR_NOTCL] %s' %
  8059. _("Failed to parse recent project item list."))
  8060. fp.close()
  8061. return
  8062. fp.close()
  8063. # Closure needed to create callbacks in a loop.
  8064. # Otherwise late binding occurs.
  8065. def make_callback(func, fname):
  8066. def opener():
  8067. func(fname)
  8068. return opener
  8069. def reset_recent_files():
  8070. # Reset menu
  8071. self.ui.recent.clear()
  8072. self.recent = []
  8073. try:
  8074. f = open(self.data_path + '/recent.json', 'w')
  8075. except IOError:
  8076. App.log.error("Failed to open recent items file for writing.")
  8077. return
  8078. json.dump(self.recent, f)
  8079. def reset_recent_projects():
  8080. # Reset menu
  8081. self.ui.recent_projects.clear()
  8082. self.recent_projects = []
  8083. try:
  8084. fp = open(self.data_path + '/recent_projects.json', 'w')
  8085. except IOError:
  8086. App.log.error("Failed to open recent projects items file for writing.")
  8087. return
  8088. json.dump(self.recent, fp)
  8089. # Reset menu
  8090. self.ui.recent.clear()
  8091. self.ui.recent_projects.clear()
  8092. # Create menu items for projects
  8093. for recent in self.recent_projects:
  8094. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8095. if recent['kind'] == 'project':
  8096. try:
  8097. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8098. # Attach callback
  8099. o = make_callback(openers[recent["kind"]], recent['filename'])
  8100. action.triggered.connect(o)
  8101. self.ui.recent_projects.addAction(action)
  8102. except KeyError:
  8103. App.log.error("Unsupported file type: %s" % recent["kind"])
  8104. # Last action in Recent Files menu is one that Clear the content
  8105. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  8106. clear_action_proj.triggered.connect(reset_recent_projects)
  8107. self.ui.recent_projects.addSeparator()
  8108. self.ui.recent_projects.addAction(clear_action_proj)
  8109. # Create menu items for files
  8110. for recent in self.recent:
  8111. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8112. if recent['kind'] != 'project':
  8113. try:
  8114. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8115. # Attach callback
  8116. o = make_callback(openers[recent["kind"]], recent['filename'])
  8117. action.triggered.connect(o)
  8118. self.ui.recent.addAction(action)
  8119. except KeyError:
  8120. App.log.error("Unsupported file type: %s" % recent["kind"])
  8121. # Last action in Recent Files menu is one that Clear the content
  8122. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  8123. clear_action.triggered.connect(reset_recent_files)
  8124. self.ui.recent.addSeparator()
  8125. self.ui.recent.addAction(clear_action)
  8126. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8127. # self.ui.menufilerecent.set_submenu(recent_menu)
  8128. # recent_menu.show_all()
  8129. # self.ui.recent.show()
  8130. self.log.debug("Recent items list has been populated.")
  8131. def setup_component_editor(self):
  8132. # label = QtWidgets.QLabel("Choose an item from Project")
  8133. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8134. sel_title = QtWidgets.QTextEdit(
  8135. _('<b>Shortcut Key List</b>'))
  8136. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8137. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8138. settings = QSettings("Open Source", "FlatCAM")
  8139. if settings.contains("notebook_font_size"):
  8140. fsize = settings.value('notebook_font_size', type=int)
  8141. else:
  8142. fsize = 12
  8143. tsize = fsize + int(fsize / 2)
  8144. selected_text = (_('''
  8145. <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  8146. <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8147. The normal flow when working in FlatCAM is the following:</span></p>
  8148. <ol>
  8149. <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the menu&#39;s, toolbars, key shortcuts or even dragging and dropping the files on the GUI.<br />
  8150. <br />
  8151. You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  8152. &nbsp;</li>
  8153. <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  8154. <br />
  8155. If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong> is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate it even if it was out of focus.<br />
  8156. <br />
  8157. You can change the parameters in this screen and the flow direction is like this:<br />
  8158. <br />
  8159. <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  8160. </ol>
  8161. <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: <strng>F3</strong>.</span></p>
  8162. ''').format(fsize=fsize, tsize=tsize))
  8163. sel_title.setText(selected_text)
  8164. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8165. self.ui.selected_scroll_area.setWidget(sel_title)
  8166. def setup_obj_classes(self):
  8167. """
  8168. Sets up application specifics on the FlatCAMObj class.
  8169. :return: None
  8170. """
  8171. FlatCAMObj.app = self
  8172. ObjectCollection.app = self
  8173. Gerber.app = self
  8174. Excellon.app = self
  8175. Geometry.app = self
  8176. CNCjob.app = self
  8177. FCProcess.app = self
  8178. FCProcessContainer.app = self
  8179. def version_check(self):
  8180. """
  8181. Checks for the latest version of the program. Alerts the
  8182. user if theirs is outdated. This method is meant to be run
  8183. in a separate thread.
  8184. :return: None
  8185. """
  8186. self.log.debug("version_check()")
  8187. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8188. full_url = App.version_url + \
  8189. "?s=" + str(self.defaults['global_serial']) + \
  8190. "&v=" + str(self.version) + \
  8191. "&os=" + str(self.os) + \
  8192. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  8193. else:
  8194. # no_stats dict; just so it won't break things on website
  8195. no_ststs_dict = {}
  8196. no_ststs_dict["global_ststs"] = {}
  8197. full_url = App.version_url + \
  8198. "?s=" + str(self.defaults['global_serial']) + \
  8199. "&v=" + str(self.version) + \
  8200. "&os=" + str(self.os) + \
  8201. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8202. App.log.debug("Checking for updates @ %s" % full_url)
  8203. # ## Get the data
  8204. try:
  8205. f = urllib.request.urlopen(full_url)
  8206. except:
  8207. # App.log.warning("Failed checking for latest version. Could not connect.")
  8208. self.log.warning("Failed checking for latest version. Could not connect.")
  8209. self.inform.emit('[WARNING_NOTCL] %s' %
  8210. _("Failed checking for latest version. Could not connect."))
  8211. return
  8212. try:
  8213. data = json.load(f)
  8214. except Exception as e:
  8215. App.log.error("Could not parse information about latest version.")
  8216. self.inform.emit('[ERROR_NOTCL] %s' %
  8217. _("Could not parse information about latest version."))
  8218. App.log.debug("json.load(): %s" % str(e))
  8219. f.close()
  8220. return
  8221. f.close()
  8222. # ## Latest version?
  8223. if self.version >= data["version"]:
  8224. App.log.debug("FlatCAM is up to date!")
  8225. self.inform.emit('[success] %s' %
  8226. _("FlatCAM is up to date!"))
  8227. return
  8228. App.log.debug("Newer version available.")
  8229. self.message.emit(
  8230. _("Newer Version Available"),
  8231. _("There is a newer version of FlatCAM available for download:\n\n") +
  8232. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  8233. _("info")
  8234. )
  8235. def on_plotcanvas_setup(self, container=None):
  8236. """
  8237. This is doing the setup for the plot area (VisPy canvas)
  8238. :param container: widget where to install the canvas
  8239. :return: None
  8240. """
  8241. if container:
  8242. plot_container = container
  8243. else:
  8244. plot_container = self.ui.right_layout
  8245. self.plotcanvas = PlotCanvas(plot_container, self)
  8246. # So it can receive key presses
  8247. self.plotcanvas.native.setFocus()
  8248. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  8249. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  8250. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8251. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  8252. # Keys over plot enabled
  8253. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  8254. self.app_cursor = self.plotcanvas.new_cursor()
  8255. self.app_cursor.enabled = False
  8256. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8257. def on_zoom_fit(self, event):
  8258. """
  8259. Callback for zoom-out request. This can be either from the corresponding
  8260. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8261. with axes limits from the geometry bounds of all objects.
  8262. :param event: Ignored.
  8263. :return: None
  8264. """
  8265. self.plotcanvas.fit_view()
  8266. def on_zoom_in(self):
  8267. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8268. def on_zoom_out(self):
  8269. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8270. def disable_all_plots(self):
  8271. self.report_usage("disable_all_plots()")
  8272. self.disable_plots(self.collection.get_list())
  8273. self.inform.emit('[success] %s' %
  8274. _("All plots disabled."))
  8275. def disable_other_plots(self):
  8276. self.report_usage("disable_other_plots()")
  8277. self.disable_plots(self.collection.get_non_selected())
  8278. self.inform.emit('[success] %s' %
  8279. _("All non selected plots disabled."))
  8280. def enable_all_plots(self):
  8281. self.report_usage("enable_all_plots()")
  8282. self.enable_plots(self.collection.get_list())
  8283. self.inform.emit('[success] %s' %
  8284. _("All plots enabled."))
  8285. def on_enable_sel_plots(self):
  8286. log.debug("App.on_enable_sel_plot()")
  8287. object_list = self.collection.get_selected()
  8288. self.enable_plots(objects=object_list)
  8289. self.inform.emit('[success] %s' %
  8290. _("Selected plots enabled..."))
  8291. def on_disable_sel_plots(self):
  8292. log.debug("App.on_disable_sel_plot()")
  8293. # self.inform.emit(_("Disabling plots ..."))
  8294. object_list = self.collection.get_selected()
  8295. self.disable_plots(objects=object_list)
  8296. self.inform.emit('[success] %s' %
  8297. _("Selected plots disabled..."))
  8298. def enable_plots(self, objects):
  8299. """
  8300. Disables plots
  8301. :param objects: list of Objects to be enabled
  8302. :return:
  8303. """
  8304. log.debug("Enabling plots ...")
  8305. # self.inform.emit(_("Working ..."))
  8306. for obj in objects:
  8307. if obj.options['plot'] is False:
  8308. obj.options.set_change_callback(lambda x: None)
  8309. obj.options['plot'] = True
  8310. obj.options.set_change_callback(obj.on_options_change)
  8311. def worker_task(objects):
  8312. with self.proc_container.new(_("Enabling plots ...")):
  8313. for obj in objects:
  8314. # obj.options['plot'] = True
  8315. if isinstance(obj, FlatCAMCNCjob):
  8316. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8317. else:
  8318. obj.plot(visible=True)
  8319. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8320. # self.plots_updated.emit()
  8321. def disable_plots(self, objects):
  8322. """
  8323. Disables plots
  8324. :param objects: list of Objects to be disabled
  8325. :return:
  8326. """
  8327. # if no objects selected then do nothing
  8328. if not self.collection.get_selected():
  8329. return
  8330. log.debug("Disabling plots ...")
  8331. # self.inform.emit(_("Working ..."))
  8332. for obj in objects:
  8333. if obj.options['plot'] is True:
  8334. obj.options.set_change_callback(lambda x: None)
  8335. obj.options['plot'] = False
  8336. obj.options.set_change_callback(obj.on_options_change)
  8337. try:
  8338. self.delete_selection_shape()
  8339. except Exception as e:
  8340. log.debug("App.disable_plots() --> %s" % str(e))
  8341. # self.plots_updated.emit()
  8342. def worker_task(objects):
  8343. with self.proc_container.new(_("Disabling plots ...")):
  8344. for obj in objects:
  8345. # obj.options['plot'] = True
  8346. if isinstance(obj, FlatCAMCNCjob):
  8347. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8348. else:
  8349. obj.plot(visible=False)
  8350. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8351. def toggle_plots(self, objects):
  8352. """
  8353. Toggle plots visibility
  8354. :param objects: list of Objects for which to be toggled the visibility
  8355. :return:
  8356. """
  8357. # if no objects selected then do nothing
  8358. if not self.collection.get_selected():
  8359. return
  8360. log.debug("Toggling plots ...")
  8361. self.inform.emit(_("Working ..."))
  8362. for obj in objects:
  8363. if obj.options['plot'] is False:
  8364. obj.options['plot'] = True
  8365. else:
  8366. obj.options['plot'] = False
  8367. self.plots_updated.emit()
  8368. def clear_plots(self):
  8369. objects = self.collection.get_list()
  8370. for obj in objects:
  8371. obj.clear(obj == objects[-1])
  8372. # Clear pool to free memory
  8373. self.clear_pool()
  8374. def generate_cnc_job(self, objects):
  8375. self.report_usage("generate_cnc_job()")
  8376. # for obj in objects:
  8377. # obj.generatecncjob()
  8378. for obj in objects:
  8379. obj.on_generatecnc_button_click()
  8380. def save_project(self, filename, quit_action=False):
  8381. """
  8382. Saves the current project to the specified file.
  8383. :param filename: Name of the file in which to save.
  8384. :type filename: str
  8385. :param quit_action: if the project saving will be followed by an app quit; boolean
  8386. :return: None
  8387. """
  8388. self.log.debug("save_project()")
  8389. self.save_in_progress = True
  8390. with self.proc_container.new(_("Saving FlatCAM Project")) as proc:
  8391. # Capture the latest changes
  8392. # Current object
  8393. try:
  8394. self.collection.get_active().read_form()
  8395. except:
  8396. self.log.debug("There was no active object")
  8397. pass
  8398. # Project options
  8399. self.options_read_form()
  8400. # Serialize the whole project
  8401. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8402. "options": self.options,
  8403. "version": self.version}
  8404. if self.defaults["global_save_compressed"] is True:
  8405. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8406. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8407. # # Write
  8408. f.write(g)
  8409. self.inform.emit('[success] %s: %s' %
  8410. (_("Project saved to"), filename))
  8411. else:
  8412. # Open file
  8413. try:
  8414. f = open(filename, 'w')
  8415. except IOError:
  8416. App.log.error("Failed to open file for saving: %s", filename)
  8417. return
  8418. # Write
  8419. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8420. f.close()
  8421. # verification of the saved project
  8422. # Open and parse
  8423. try:
  8424. saved_f = open(filename, 'r')
  8425. except IOError:
  8426. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8427. (_("Failed to verify project file"), filename, _("Retry to save it."))
  8428. )
  8429. return
  8430. try:
  8431. saved_d = json.load(saved_f, object_hook=dict2obj)
  8432. except:
  8433. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8434. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  8435. )
  8436. f.close()
  8437. return
  8438. saved_f.close()
  8439. if 'version' in saved_d:
  8440. self.inform.emit('[success] %s: %s' %
  8441. (_("Project saved to"), filename))
  8442. else:
  8443. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8444. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  8445. )
  8446. settings = QSettings("Open Source", "FlatCAM")
  8447. lock_state = self.ui.lock_action.isChecked()
  8448. settings.setValue('toolbar_lock', lock_state)
  8449. # This will write the setting to the platform specific storage.
  8450. del settings
  8451. # if quit:
  8452. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8453. # t.start()
  8454. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8455. def start_delayed_quit(self, delay, filename, should_quit=None):
  8456. """
  8457. :param delay: period of checking if project file size is more than zero; in seconds
  8458. :param filename: the name of the project file to be checked periodically for size more than zero
  8459. :param should_quit: if the task finished will be followed by an app quit; boolean
  8460. :return:
  8461. """
  8462. to_quit = should_quit
  8463. self.save_timer = QtCore.QTimer()
  8464. self.save_timer.setInterval(delay)
  8465. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8466. self.save_timer.start()
  8467. def check_project_file_size(self, filename, should_quit=None):
  8468. """
  8469. :param filename: the name of the project file to be checked periodically for size more than zero
  8470. :param should_quit: will quit the app if True; boolean
  8471. :return:
  8472. """
  8473. try:
  8474. if os.stat(filename).st_size > 0:
  8475. self.save_in_progress = False
  8476. self.save_timer.stop()
  8477. if should_quit:
  8478. self.app_quit.emit()
  8479. except Exception as e:
  8480. traceback.print_exc()
  8481. def on_options_app2project(self):
  8482. """
  8483. Callback for Options->Transfer Options->App=>Project. Copies options
  8484. from application defaults to project defaults.
  8485. :return: None
  8486. """
  8487. self.report_usage("on_options_app2project")
  8488. self.defaults_read_form()
  8489. self.options.update(self.defaults)
  8490. self.options_write_form()
  8491. def on_options_project2app(self):
  8492. """
  8493. Callback for Options->Transfer Options->Project=>App. Copies options
  8494. from project defaults to application defaults.
  8495. :return: None
  8496. """
  8497. self.report_usage("on_options_project2app")
  8498. self.options_read_form()
  8499. self.defaults.update(self.options)
  8500. self.defaults_write_form()
  8501. def on_options_project2object(self):
  8502. """
  8503. Callback for Options->Transfer Options->Project=>Object. Copies options
  8504. from project defaults to the currently selected object.
  8505. :return: None
  8506. """
  8507. self.report_usage("on_options_project2object")
  8508. self.options_read_form()
  8509. obj = self.collection.get_active()
  8510. if obj is None:
  8511. self.inform.emit('[WARNING_NOTCL] %s' %
  8512. _("No object selected."))
  8513. return
  8514. for option in self.options:
  8515. if option.find(obj.kind + "_") == 0:
  8516. oname = option[len(obj.kind) + 1:]
  8517. obj.options[oname] = self.options[option]
  8518. obj.to_form() # Update UI
  8519. def on_options_object2project(self):
  8520. """
  8521. Callback for Options->Transfer Options->Object=>Project. Copies options
  8522. from the currently selected object to project defaults.
  8523. :return: None
  8524. """
  8525. self.report_usage("on_options_object2project")
  8526. obj = self.collection.get_active()
  8527. if obj is None:
  8528. self.inform.emit('[WARNING_NOTCL] %s' %
  8529. _("No object selected."))
  8530. return
  8531. obj.read_form()
  8532. for option in obj.options:
  8533. if option in ['name']: # TODO: Handle this better...
  8534. continue
  8535. self.options[obj.kind + "_" + option] = obj.options[option]
  8536. self.options_write_form()
  8537. def on_options_object2app(self):
  8538. """
  8539. Callback for Options->Transfer Options->Object=>App. Copies options
  8540. from the currently selected object to application defaults.
  8541. :return: None
  8542. """
  8543. self.report_usage("on_options_object2app")
  8544. obj = self.collection.get_active()
  8545. if obj is None:
  8546. self.inform.emit('[WARNING_NOTCL] %s' %
  8547. _("No object selected."))
  8548. return
  8549. obj.read_form()
  8550. for option in obj.options:
  8551. if option in ['name']: # TODO: Handle this better...
  8552. continue
  8553. self.defaults[obj.kind + "_" + option] = obj.options[option]
  8554. self.defaults_write_form()
  8555. def on_options_app2object(self):
  8556. """
  8557. Callback for Options->Transfer Options->App=>Object. Copies options
  8558. from application defaults to the currently selected object.
  8559. :return: None
  8560. """
  8561. self.report_usage("on_options_app2object")
  8562. self.defaults_read_form()
  8563. obj = self.collection.get_active()
  8564. if obj is None:
  8565. self.inform.emit('[WARNING_NOTCL] %s' %
  8566. _("No object selected."))
  8567. return
  8568. for option in self.defaults:
  8569. if option.find(obj.kind + "_") == 0:
  8570. oname = option[len(obj.kind) + 1:]
  8571. obj.options[oname] = self.defaults[option]
  8572. obj.to_form() # Update UI
  8573. class ArgsThread(QtCore.QObject):
  8574. open_signal = pyqtSignal(list)
  8575. start = pyqtSignal()
  8576. if sys.platform == 'win32':
  8577. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8578. else:
  8579. address = ('/tmp/testipc', 'AF_UNIX')
  8580. def __init__(self):
  8581. super(ArgsThread, self).__init__()
  8582. self.start.connect(self.run)
  8583. def my_loop(self, address):
  8584. try:
  8585. listener = Listener(*address)
  8586. while True:
  8587. conn = listener.accept()
  8588. self.serve(conn)
  8589. except socket.error as e:
  8590. conn = Client(*address)
  8591. conn.send(sys.argv)
  8592. conn.send('close')
  8593. # close the current instance only if there are args
  8594. if len(sys.argv) > 1:
  8595. sys.exit()
  8596. def serve(self, conn):
  8597. while True:
  8598. msg = conn.recv()
  8599. if msg == 'close':
  8600. break
  8601. self.open_signal.emit(msg)
  8602. conn.close()
  8603. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8604. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8605. @pyqtSlot()
  8606. def run(self):
  8607. self.my_loop(self.address)
  8608. class GracefulException(Exception):
  8609. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  8610. def __init__(self):
  8611. super().__init__()
  8612. def __str__(self):
  8613. return ('\n\n%s' % _("The user requested a graceful exit of the current task."))
  8614. # end of file