FlatCAMApp.py 508 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ###########################################################
  8. import urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import threading
  16. import shutil
  17. from stat import S_IREAD, S_IRGRP, S_IROTH
  18. import subprocess
  19. import ctypes
  20. import tkinter as tk
  21. from PyQt5 import QtPrintSupport
  22. from contextlib import contextmanager
  23. import gc
  24. from xml.dom.minidom import parseString as parse_xml_string
  25. from multiprocessing.connection import Listener, Client
  26. from multiprocessing import Pool
  27. import socket
  28. from array import array
  29. # #######################################
  30. # # Imports part of FlatCAM ##
  31. # #######################################
  32. from ObjectCollection import *
  33. from FlatCAMObj import *
  34. from flatcamGUI.PlotCanvas import *
  35. from flatcamGUI.FlatCAMGUI import *
  36. from FlatCAMCommon import LoudDict
  37. from FlatCAMPostProc import load_postprocessors
  38. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  39. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  40. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  41. from FlatCAMProcess import *
  42. from FlatCAMWorkerStack import WorkerStack
  43. from flatcamGUI.VisPyVisuals import Color
  44. from vispy.gloo.util import _screenshot
  45. from vispy.io import write_png
  46. from flatcamTools import *
  47. import tclCommands
  48. import gettext
  49. import FlatCAMTranslation as fcTranslate
  50. import builtins
  51. if sys.platform == 'win32':
  52. import winreg
  53. fcTranslate.apply_language('strings')
  54. if '_' not in builtins.__dict__:
  55. _ = gettext.gettext
  56. # ########################################
  57. # # App ###
  58. # ########################################
  59. class App(QtCore.QObject):
  60. """
  61. The main application class. The constructor starts the GUI.
  62. """
  63. # Get Cmd Line Options
  64. cmd_line_shellfile = ''
  65. cmd_line_shellvar = ''
  66. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\nFlatCam.py --shellvar=<1,'C:\\path',23>"
  67. try:
  68. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  69. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  70. "shellvar=",
  71. "multiprocessing-fork="])
  72. except getopt.GetoptError:
  73. print(cmd_line_help)
  74. sys.exit(2)
  75. for opt, arg in cmd_line_options:
  76. if opt == '-h':
  77. print(cmd_line_help)
  78. sys.exit()
  79. elif opt == '--shellfile':
  80. cmd_line_shellfile = arg
  81. elif opt == '--shellvar':
  82. cmd_line_shellvar = arg
  83. # ## Logging ###
  84. log = logging.getLogger('base')
  85. log.setLevel(logging.DEBUG)
  86. # log.setLevel(logging.WARNING)
  87. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  88. handler = logging.StreamHandler()
  89. handler.setFormatter(formatter)
  90. log.addHandler(handler)
  91. # ##########################################################################
  92. # ################## Version and VERSION DATE ##############################
  93. # ##########################################################################
  94. version = 8.97
  95. version_date = "2019/09/20"
  96. beta = True
  97. # current date now
  98. date = str(datetime.today()).rpartition('.')[0]
  99. date = ''.join(c for c in date if c not in ':-')
  100. date = date.replace(' ', '_')
  101. # URL for update checks and statistics
  102. version_url = "http://flatcam.org/version"
  103. # App URL
  104. app_url = "http://flatcam.org"
  105. # Manual URL
  106. manual_url = "http://flatcam.org/manual/index.html"
  107. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  108. gerber_spec_url ="https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  109. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  110. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  111. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  112. # this variable will hold the project status
  113. # if True it will mean that the project was modified and not saved
  114. should_we_save = False
  115. # flag is True if saving action has been triggered
  116. save_in_progress = False
  117. # ###########################################################################
  118. # ############################# Signals ################################
  119. # ###########################################################################
  120. # Inform the user
  121. # Handled by:
  122. # * App.info() --> Print on the status bar
  123. inform = QtCore.pyqtSignal(str)
  124. app_quit = QtCore.pyqtSignal()
  125. # General purpose background task
  126. worker_task = QtCore.pyqtSignal(dict)
  127. # File opened
  128. # Handled by:
  129. # * register_folder()
  130. # * register_recent()
  131. # Note: Setting the parameters to unicode does not seem
  132. # to have an effect. Then are received as Qstring
  133. # anyway.
  134. # File type and filename
  135. file_opened = QtCore.pyqtSignal(str, str)
  136. # File type and filename
  137. file_saved = QtCore.pyqtSignal(str, str)
  138. # Percentage of progress
  139. progress = QtCore.pyqtSignal(int)
  140. plots_updated = QtCore.pyqtSignal()
  141. # Emitted by new_object() and passes the new object as argument, plot flag.
  142. # on_object_created() adds the object to the collection, plots on appropriate flag
  143. # and emits new_object_available.
  144. object_created = QtCore.pyqtSignal(object, bool, bool)
  145. # Emitted when a object has been changed (like scaled, mirrored)
  146. object_changed = QtCore.pyqtSignal(object)
  147. # Emitted after object has been plotted.
  148. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  149. object_plotted = QtCore.pyqtSignal(object)
  150. # Emitted when a new object has been added or deleted from/to the collection
  151. object_status_changed = QtCore.pyqtSignal(object, str)
  152. message = QtCore.pyqtSignal(str, str, str)
  153. # Emmited when shell command is finished(one command only)
  154. shell_command_finished = QtCore.pyqtSignal(object)
  155. # Emitted when multiprocess pool has been recreated
  156. pool_recreated = QtCore.pyqtSignal(object)
  157. # Emitted when an unhandled exception happens
  158. # in the worker task.
  159. thread_exception = QtCore.pyqtSignal(object)
  160. # used to signal that there are arguments for the app
  161. args_at_startup = QtCore.pyqtSignal(list)
  162. # a reusable signal to replot a list of objects
  163. # should be disconnected after use so it can be reused
  164. replot_signal = pyqtSignal(list)
  165. def __init__(self, user_defaults=True, post_gui=None):
  166. """
  167. Starts the application.
  168. :return: app
  169. :rtype: App
  170. """
  171. App.log.info("FlatCAM Starting...")
  172. self.main_thread = QtWidgets.QApplication.instance().thread()
  173. # ############################################################################
  174. # # ################# OS-specific ############################################
  175. # ############################################################################
  176. portable = False
  177. # Folder for user settings.
  178. if sys.platform == 'win32':
  179. # #########################################################################
  180. # Setup the listening thread for another instance launching with args #####
  181. # #########################################################################
  182. # make sure the thread is stored by using a self. otherwise it's garbage collected
  183. self.th = QtCore.QThread()
  184. self.th.start(priority=QtCore.QThread.LowestPriority)
  185. self.new_launch = ArgsThread()
  186. self.new_launch.open_signal[list].connect(self.on_startup_args)
  187. self.new_launch.moveToThread(self.th)
  188. self.new_launch.start.emit()
  189. from win32com.shell import shell, shellcon
  190. if platform.architecture()[0] == '32bit':
  191. App.log.debug("Win32!")
  192. else:
  193. App.log.debug("Win64!")
  194. # #########################################################################
  195. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  196. # #########################################################################
  197. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  198. try:
  199. with open(config_file, 'r') as f:
  200. try:
  201. for line in f:
  202. param = str(line).rpartition('=')
  203. if param[0] == 'portable':
  204. try:
  205. portable = eval(param[2])
  206. except NameError:
  207. portable = False
  208. except Exception as e:
  209. log.debug('App.__init__() -->%s' % str(e))
  210. return
  211. except FileNotFoundError:
  212. pass
  213. if portable is False:
  214. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  215. else:
  216. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  217. self.os = 'windows'
  218. else: # Linux/Unix/MacOS
  219. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  220. self.os = 'unix'
  221. # ##########################################################################
  222. # ################## Setup folders and files ###############################
  223. # ##########################################################################
  224. if not os.path.exists(self.data_path):
  225. os.makedirs(self.data_path)
  226. App.log.debug('Created data folder: ' + self.data_path)
  227. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  228. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  229. self.postprocessorpaths = os.path.join(self.data_path, 'postprocessors')
  230. if not os.path.exists(self.postprocessorpaths):
  231. os.makedirs(self.postprocessorpaths)
  232. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  233. # create current_defaults.FlatConfig file if there is none
  234. try:
  235. f = open(self.data_path + '/current_defaults.FlatConfig')
  236. f.close()
  237. except IOError:
  238. App.log.debug('Creating empty current_defaults.FlatConfig')
  239. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  240. json.dump({}, f)
  241. f.close()
  242. # create factory_defaults.FlatConfig file if there is none
  243. try:
  244. f = open(self.data_path + '/factory_defaults.FlatConfig')
  245. f.close()
  246. except IOError:
  247. App.log.debug('Creating empty factory_defaults.FlatConfig')
  248. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  249. json.dump({}, f)
  250. f.close()
  251. # create a recent files json file if there is none
  252. try:
  253. f = open(self.data_path + '/recent.json')
  254. f.close()
  255. except IOError:
  256. App.log.debug('Creating empty recent.json')
  257. f = open(self.data_path + '/recent.json', 'w')
  258. json.dump([], f)
  259. f.close()
  260. # create a recent projects json file if there is none
  261. try:
  262. fp = open(self.data_path + '/recent_projects.json')
  263. fp.close()
  264. except IOError:
  265. App.log.debug('Creating empty recent_projects.json')
  266. fp = open(self.data_path + '/recent_projects.json', 'w')
  267. json.dump([], fp)
  268. fp.close()
  269. # Application directory. CHDIR to it. Otherwise, trying to load
  270. # GUI icons will fail as their path is relative.
  271. # This will fail under cx_freeze ...
  272. self.app_home = os.path.dirname(os.path.realpath(__file__))
  273. App.log.debug("Application path is " + self.app_home)
  274. App.log.debug("Started in " + os.getcwd())
  275. # cx_freeze workaround
  276. if os.path.isfile(self.app_home):
  277. self.app_home = os.path.dirname(self.app_home)
  278. os.chdir(self.app_home)
  279. # #############################################################################
  280. # ##################### CREATE MULTIPROCESSING POOL ###########################
  281. # #############################################################################
  282. self.pool = Pool()
  283. # ##########################################################################
  284. # ################## Setting the Splash Screen #############################
  285. # ##########################################################################
  286. settings = QSettings("Open Source", "FlatCAM")
  287. if settings.contains("splash_screen"):
  288. show_splash = settings.value("splash_screen")
  289. else:
  290. settings.setValue('splash_screen', 1)
  291. # This will write the setting to the platform specific storage.
  292. del settings
  293. show_splash = 1
  294. if show_splash:
  295. splash_pix = QtGui.QPixmap('share/splash.png')
  296. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  297. # self.splash.setMask(splash_pix.mask())
  298. # move splashscreen to the current monitor
  299. desktop = QtWidgets.QApplication.desktop()
  300. screen = desktop.screenNumber(QtGui.QCursor.pos())
  301. current_screen_center = desktop.availableGeometry(screen).center()
  302. self.splash.move(current_screen_center - self.splash.rect().center())
  303. self.splash.show()
  304. self.splash.showMessage(_("FlatCAM is initializing ..."),
  305. alignment=Qt.AlignBottom | Qt.AlignLeft,
  306. color=QtGui.QColor("gray"))
  307. # #############################################################################
  308. # ##################### Initialize GUI ########################################
  309. # #############################################################################
  310. # FlatCAM colors used in plotting
  311. self.FC_light_green = '#BBF268BF'
  312. self.FC_dark_green = '#006E20BF'
  313. self.FC_light_blue = '#a5a5ffbf'
  314. self.FC_dark_blue = '#0000ffbf'
  315. QtCore.QObject.__init__(self)
  316. self.ui = FlatCAMGUI(self.version, self.beta, self)
  317. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  318. self.ui.final_save.connect(self.final_save)
  319. # #############################################################################
  320. # ############################## Data #########################################
  321. # #############################################################################
  322. self.recent = []
  323. self.recent_projects = []
  324. self.clipboard = QtWidgets.QApplication.clipboard()
  325. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  326. self.project_filename = None
  327. self.toggle_units_ignore = False
  328. # self.defaults_form = PreferencesUI()
  329. # when adding entries here read the comments in the method found bellow named:
  330. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  331. self.defaults_form_fields = {
  332. # General App
  333. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  334. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  335. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  336. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  337. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  338. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  339. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  340. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  341. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  342. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  343. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  344. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  345. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  346. # General GUI Preferences
  347. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  348. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  349. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  350. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  351. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  352. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  353. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  354. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  355. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  356. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  357. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  358. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  359. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  360. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  361. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  362. # General GUI Settings
  363. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  364. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  365. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  366. "global_systray_icon": self.ui.general_defaults_form.general_gui_set_group.systray_cb,
  367. "global_shell_at_startup": self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb,
  368. "global_project_at_startup": self.ui.general_defaults_form.general_gui_set_group.project_startup_cb,
  369. "global_project_autohide": self.ui.general_defaults_form.general_gui_set_group.project_autohide_cb,
  370. "global_toggle_tooltips": self.ui.general_defaults_form.general_gui_set_group.toggle_tooltips_cb,
  371. "global_delete_confirmation": self.ui.general_defaults_form.general_gui_set_group.delete_conf_cb,
  372. # Gerber General
  373. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  374. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  375. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  376. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  377. # Gerber Options
  378. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  379. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  380. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  381. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  382. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  383. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  384. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  385. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  386. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  387. # Gerber Advanced Options
  388. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  389. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  390. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  391. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  392. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  393. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  394. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  395. # Gerber Export
  396. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  397. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  398. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  399. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  400. # Gerber Editor
  401. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  402. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  403. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  404. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  405. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  406. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  407. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  408. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  409. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  410. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  411. "gerber_editor_circ_angle":
  412. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  413. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  414. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  415. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  416. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  417. # Excellon General
  418. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  419. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  420. "excellon_format_upper_in":
  421. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  422. "excellon_format_lower_in":
  423. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  424. "excellon_format_upper_mm":
  425. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  426. "excellon_format_lower_mm":
  427. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  428. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  429. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  430. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  431. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  432. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  433. # Excellon Options
  434. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  435. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  436. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.eendz_entry,
  437. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  438. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  439. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  440. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  441. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  442. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  443. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  444. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  445. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  446. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  447. # Excellon Advanced Options
  448. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  449. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  450. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  451. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  452. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  453. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  454. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  455. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  456. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  457. # Excellon Export
  458. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  459. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  460. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  461. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  462. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  463. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  464. # Excellon Editor
  465. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  466. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  467. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  468. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  469. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  470. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  471. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  472. "excellon_editor_circ_angle":
  473. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  474. # Excellon Slots
  475. "excellon_editor_slot_direction":
  476. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  477. "excellon_editor_slot_angle":
  478. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  479. "excellon_editor_slot_length":
  480. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  481. # Excellon Slots
  482. "excellon_editor_slot_array_size":
  483. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  484. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  485. "excellon_editor_slot_lin_pitch":
  486. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  487. "excellon_editor_slot_lin_angle":
  488. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  489. "excellon_editor_slot_circ_dir":
  490. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  491. "excellon_editor_slot_circ_angle":
  492. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  493. # Geometry General
  494. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  495. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  496. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  497. # Geometry Options
  498. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  499. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  500. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  501. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  502. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  503. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  504. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  505. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  506. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  507. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  508. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.gendz_entry,
  509. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  510. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  511. # Geometry Advanced Options
  512. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  513. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  514. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  515. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  516. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  517. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  518. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  519. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  520. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  521. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  522. # Geometry Editor
  523. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  524. # CNCJob General
  525. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  526. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  527. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  528. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  529. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  530. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  531. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  532. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  533. # CNC Job Options
  534. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  535. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  536. # CNC Job Advanced Options
  537. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  538. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  539. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  540. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  541. # NCC Tool
  542. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  543. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  544. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  545. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  546. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  547. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  548. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  549. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  550. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  551. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  552. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  553. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  554. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  555. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  556. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  557. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  558. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  559. # CutOut Tool
  560. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  561. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  562. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  563. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  564. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  565. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  566. # Paint Area Tool
  567. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  568. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  569. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  570. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  571. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  572. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  573. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  574. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  575. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  576. # 2-sided Tool
  577. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  578. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  579. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  580. # Film Tool
  581. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  582. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  583. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  584. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  585. # Panelize Tool
  586. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  587. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  588. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  589. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  590. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  591. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  592. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  593. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  594. # Calculators Tool
  595. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  596. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  597. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  598. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  599. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  600. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  601. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  602. # Transformations Tool
  603. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  604. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  605. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  606. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  607. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  608. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  609. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  610. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  611. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  612. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  613. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  614. # SolderPaste Dispensing Tool
  615. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  616. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  617. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  618. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  619. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  620. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  621. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  622. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  623. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  624. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  625. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  626. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  627. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  628. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  629. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  630. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  631. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  632. # Utilities
  633. # File associations
  634. "fa_excellon": self.ui.util_defaults_form.fa_excellon_group.exc_list_text,
  635. "fa_gcode": self.ui.util_defaults_form.fa_gcode_group.gco_list_text,
  636. # "fa_geometry": self.ui.util_defaults_form.fa_geometry_group.close_paths_cb,
  637. "fa_gerber": self.ui.util_defaults_form.fa_gerber_group.grb_list_text,
  638. "util_autocomplete_keywords": self.ui.util_defaults_form.kw_group.kw_list_text,
  639. }
  640. # ############################
  641. # ### LOAD POSTPROCESSORS ####
  642. # ############################
  643. self.postprocessors = load_postprocessors(self)
  644. for name in list(self.postprocessors.keys()):
  645. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  646. if name.partition('_')[0] == 'Paste':
  647. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  648. continue
  649. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  650. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  651. if name == 'hpgl':
  652. continue
  653. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  654. # ############################
  655. # ### LOAD LANGUAGES ####
  656. # ############################
  657. self.languages = fcTranslate.load_languages()
  658. for name in sorted(self.languages.values()):
  659. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  660. self.defaults = LoudDict()
  661. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  662. self.defaults.update({
  663. # Global APP Preferences
  664. "first_run": True,
  665. "units": "IN",
  666. "global_serial": 0,
  667. "global_stats": {},
  668. "global_tabs_detachable": True,
  669. "global_app_level": 'b',
  670. "global_portable": False,
  671. "global_language": 'English',
  672. "global_version_check": True,
  673. "global_send_stats": True,
  674. "global_pan_button": '2',
  675. "global_mselect_key": 'Control',
  676. "global_project_at_startup": False,
  677. "global_systray_icon": True,
  678. "global_project_autohide": True,
  679. "global_toggle_tooltips": True,
  680. "global_worker_number": 2,
  681. "global_tolerance": 0.005,
  682. "global_open_style": True,
  683. "global_delete_confirmation": True,
  684. "global_compression_level": 3,
  685. "global_save_compressed": True,
  686. # Global GUI Preferences
  687. "global_gridx": 0.0393701,
  688. "global_gridy": 0.0393701,
  689. "global_snap_max": 0.001968504,
  690. "global_workspace": False,
  691. "global_workspaceT": "A4P",
  692. "global_grid_context_menu": {
  693. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  694. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  695. },
  696. "global_plot_fill": '#BBF268BF',
  697. "global_plot_line": '#006E20BF',
  698. "global_sel_fill": '#a5a5ffbf',
  699. "global_sel_line": '#0000ffbf',
  700. "global_alt_sel_fill": '#BBF268BF',
  701. "global_alt_sel_line": '#006E20BF',
  702. "global_draw_color": '#FF0000',
  703. "global_sel_draw_color": '#0000FF',
  704. "global_proj_item_color": '#000000',
  705. "global_proj_item_dis_color": '#b7b7cb',
  706. "global_toolbar_view": 511,
  707. "global_background_timeout": 300000, # Default value is 5 minutes
  708. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  709. # (python trace only for unknown errors),
  710. # 1 = show trace(show trace always),
  711. # 2 = (For the future).
  712. # Persistence
  713. "global_last_folder": None,
  714. "global_last_save_folder": None,
  715. # Default window geometry
  716. "global_def_win_x": 100,
  717. "global_def_win_y": 100,
  718. "global_def_win_w": 1024,
  719. "global_def_win_h": 650,
  720. "global_def_notebook_width": 1,
  721. # Constants...
  722. "global_defaults_save_period_ms": 20000, # Time between default saves.
  723. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  724. "global_shell_at_startup": False, # Show the shell at startup.
  725. "global_recent_limit": 10, # Max. items in recent list.
  726. "fit_key": 'V',
  727. "zoom_out_key": '-',
  728. "zoom_in_key": '=',
  729. "grid_toggle_key": 'G',
  730. "global_zoom_ratio": 1.5,
  731. "global_point_clipboard_format": "(%.4f, %.4f)",
  732. "global_zdownrate": None,
  733. # General GUI Settings
  734. "global_hover": False,
  735. "global_selection_shape": True,
  736. "global_layout": "compact",
  737. # Gerber General
  738. "gerber_plot": True,
  739. "gerber_solid": True,
  740. "gerber_multicolored": False,
  741. "gerber_circle_steps": 128,
  742. "gerber_use_buffer_for_union": True,
  743. # Gerber Options
  744. "gerber_isotooldia": 0.00787402,
  745. "gerber_isopasses": 1,
  746. "gerber_isooverlap": 0.00393701,
  747. "gerber_milling_type": "cl",
  748. "gerber_combine_passes": False,
  749. "gerber_noncoppermargin": 0.00393701,
  750. "gerber_noncopperrounded": False,
  751. "gerber_bboxmargin": 0.00393701,
  752. "gerber_bboxrounded": False,
  753. # Gerber Advanced Options
  754. "gerber_aperture_display": False,
  755. "gerber_aperture_scale_factor": 1.0,
  756. "gerber_aperture_buffer_factor": 0.0,
  757. "gerber_follow": False,
  758. "gerber_buffering": "full",
  759. "gerber_simplification": False,
  760. "gerber_simp_tolerance": 0.0005,
  761. # Gerber Export
  762. "gerber_exp_units": 'IN',
  763. "gerber_exp_integer": 2,
  764. "gerber_exp_decimals": 4,
  765. "gerber_exp_zeros": 'L',
  766. # Gerber Editor
  767. "gerber_editor_sel_limit": 30,
  768. "gerber_editor_newcode": 10,
  769. "gerber_editor_newsize": 0.8,
  770. "gerber_editor_newtype": 'C',
  771. "gerber_editor_newdim": "0.5, 0.5",
  772. "gerber_editor_array_size": 5,
  773. "gerber_editor_lin_axis": 'X',
  774. "gerber_editor_lin_pitch": 1,
  775. "gerber_editor_lin_angle": 0.0,
  776. "gerber_editor_circ_dir": 'CW',
  777. "gerber_editor_circ_angle": 0.0,
  778. "gerber_editor_scale_f": 1.0,
  779. "gerber_editor_buff_f": 0.1,
  780. "gerber_editor_ma_low": 0.0,
  781. "gerber_editor_ma_high": 1.0,
  782. # Excellon General
  783. "excellon_plot": True,
  784. "excellon_solid": True,
  785. "excellon_format_upper_in": 2,
  786. "excellon_format_lower_in": 4,
  787. "excellon_format_upper_mm": 3,
  788. "excellon_format_lower_mm": 3,
  789. "excellon_zeros": "L",
  790. "excellon_units": "INCH",
  791. "excellon_update": True,
  792. "excellon_optimization_type": 'B',
  793. "excellon_search_time": 3,
  794. # Excellon Options
  795. "excellon_drillz": -0.0590551,
  796. "excellon_travelz": 0.0787402,
  797. "excellon_endz": 0.5,
  798. "excellon_feedrate": 3.14961,
  799. "excellon_spindlespeed": None,
  800. "excellon_dwell": False,
  801. "excellon_dwelltime": 1,
  802. "excellon_toolchange": False,
  803. "excellon_toolchangez": 0.5,
  804. "excellon_ppname_e": 'default',
  805. "excellon_tooldia": 0.0314961,
  806. "excellon_slot_tooldia": 0.0708661,
  807. "excellon_gcode_type": "drills",
  808. # Excellon Advanced Options
  809. "excellon_offset": 0.0,
  810. "excellon_toolchangexy": "0.0, 0.0",
  811. "excellon_startz": None,
  812. "excellon_feedrate_rapid": 31.4961,
  813. "excellon_z_pdepth": -0.02,
  814. "excellon_feedrate_probe": 3.14961,
  815. "excellon_spindledir": 'CW',
  816. "excellon_f_plunge": False,
  817. "excellon_f_retract": False,
  818. # Excellon Export
  819. "excellon_exp_units": 'INCH',
  820. "excellon_exp_format": 'ndec',
  821. "excellon_exp_integer": 2,
  822. "excellon_exp_decimals": 4,
  823. "excellon_exp_zeros": 'LZ',
  824. "excellon_exp_slot_type": 'routing',
  825. # Excellon Editor
  826. "excellon_editor_sel_limit": 30,
  827. "excellon_editor_newdia": 0.039,
  828. "excellon_editor_array_size": 5,
  829. "excellon_editor_lin_dir": 'X',
  830. "excellon_editor_lin_pitch": 0.1,
  831. "excellon_editor_lin_angle": 0.0,
  832. "excellon_editor_circ_dir": 'CW',
  833. "excellon_editor_circ_angle": 12,
  834. # Excellon Slots
  835. "excellon_editor_slot_direction": 'X',
  836. "excellon_editor_slot_angle": 0.0,
  837. "excellon_editor_slot_length": 5.0,
  838. # Excellon Slot Array
  839. "excellon_editor_slot_array_size": 5,
  840. "excellon_editor_slot_lin_dir": 'X',
  841. "excellon_editor_slot_lin_pitch": 0.1,
  842. "excellon_editor_slot_lin_angle": 0.0,
  843. "excellon_editor_slot_circ_dir": 'CW',
  844. "excellon_editor_slot_circ_angle": 0.0,
  845. # Geometry General
  846. "geometry_plot": True,
  847. "geometry_circle_steps": 128,
  848. "geometry_cnctooldia": "0.0944882",
  849. # Geometry Options
  850. "geometry_cutz": -0.0944882,
  851. "geometry_vtipdia": 0.1,
  852. "geometry_vtipangle": 30,
  853. "geometry_multidepth": False,
  854. "geometry_depthperpass": 0.0314961,
  855. "geometry_travelz": 0.0787402,
  856. "geometry_toolchange": False,
  857. "geometry_toolchangez": 0.5,
  858. "geometry_endz": 0.5,
  859. "geometry_feedrate": 3.14961,
  860. "geometry_feedrate_z": 3.14961,
  861. "geometry_spindlespeed": None,
  862. "geometry_dwell": False,
  863. "geometry_dwelltime": 1,
  864. "geometry_ppname_g": 'default',
  865. # Geometry Advanced Options
  866. "geometry_toolchangexy": "0.0, 0.0",
  867. "geometry_startz": None,
  868. "geometry_feedrate_rapid": 3.14961,
  869. "geometry_extracut": False,
  870. "geometry_z_pdepth": -0.02,
  871. "geometry_f_plunge": False,
  872. "geometry_spindledir": 'CW',
  873. "geometry_feedrate_probe": 3.14961,
  874. "geometry_segx": 0.0,
  875. "geometry_segy": 0.0,
  876. # Geometry Editor
  877. "geometry_editor_sel_limit": 30,
  878. # CNC Job General
  879. "cncjob_plot": True,
  880. "cncjob_plot_kind": 'all',
  881. "cncjob_annotation": True,
  882. "cncjob_tooldia": 0.0393701,
  883. "cncjob_coords_type": "G90",
  884. "cncjob_coords_decimals": 4,
  885. "cncjob_fr_decimals": 2,
  886. "cncjob_steps_per_circle": 128,
  887. # CNC Job Options
  888. "cncjob_prepend": "",
  889. "cncjob_append": "",
  890. # CNC Job Advanced Options
  891. "cncjob_toolchange_macro": "",
  892. "cncjob_toolchange_macro_enable": False,
  893. "cncjob_annotation_fontsize": 9,
  894. "cncjob_annotation_fontcolor": '#990000',
  895. # NCC Tool
  896. "tools_ncctools": "0.0393701, 0.019685",
  897. "tools_nccorder": 'rev',
  898. "tools_nccoverlap": 0.015748,
  899. "tools_nccmargin": 0.0393701,
  900. "tools_nccmethod": "seed",
  901. "tools_nccconnect": True,
  902. "tools_ncccontour": True,
  903. "tools_nccrest": False,
  904. "tools_ncc_offset_choice": False,
  905. "tools_ncc_offset_value": 0.0000,
  906. "tools_nccref": 'itself',
  907. "tools_ncc_plotting": 'normal',
  908. "tools_nccmilling_type": 'cl',
  909. "tools_ncctool_type": 'V',
  910. "tools_ncccutz": -0.001968504,
  911. "tools_ncctipdia": 0.00393701,
  912. "tools_ncctipangle": 30,
  913. # Cutout Tool
  914. "tools_cutouttooldia": 0.0944882,
  915. "tools_cutoutkind": "single",
  916. "tools_cutoutmargin": 0.00393701,
  917. "tools_cutoutgapsize": 0.15748,
  918. "tools_gaps_ff": "4",
  919. "tools_cutout_convexshape": False,
  920. # Paint Tool
  921. "tools_painttooldia": 0.023622,
  922. "tools_paintorder": 'rev',
  923. "tools_paintoverlap": 0.015748,
  924. "tools_paintmargin": 0.0,
  925. "tools_paintmethod": "seed",
  926. "tools_selectmethod": "single",
  927. "tools_pathconnect": True,
  928. "tools_paintcontour": True,
  929. "tools_paint_plotting": 'normal',
  930. # 2-Sided Tool
  931. "tools_2sided_mirror_axis": "X",
  932. "tools_2sided_axis_loc": "point",
  933. "tools_2sided_drilldia": 0.11811,
  934. # Film Tool
  935. "tools_film_type": 'neg',
  936. "tools_film_boundary": 0.0393701,
  937. "tools_film_scale": 0,
  938. "tools_film_color": '#000000',
  939. # Panel Tool
  940. "tools_panelize_spacing_columns": 0,
  941. "tools_panelize_spacing_rows": 0,
  942. "tools_panelize_columns": 1,
  943. "tools_panelize_rows": 1,
  944. "tools_panelize_constrain": False,
  945. "tools_panelize_constrainx": 0.0,
  946. "tools_panelize_constrainy": 0.0,
  947. "tools_panelize_panel_type": 'gerber',
  948. # Calculators Tool
  949. "tools_calc_vshape_tip_dia": 0.007874,
  950. "tools_calc_vshape_tip_angle": 30,
  951. "tools_calc_vshape_cut_z": 0.000787,
  952. "tools_calc_electro_length": 10.0,
  953. "tools_calc_electro_width": 10.0,
  954. "tools_calc_electro_cdensity": 13.0,
  955. "tools_calc_electro_growth": 10.0,
  956. # Transform Tool
  957. "tools_transform_rotate": 90,
  958. "tools_transform_skew_x": 0.0,
  959. "tools_transform_skew_y": 0.0,
  960. "tools_transform_scale_x": 1.0,
  961. "tools_transform_scale_y": 1.0,
  962. "tools_transform_scale_link": True,
  963. "tools_transform_scale_reference": True,
  964. "tools_transform_offset_x": 0.0,
  965. "tools_transform_offset_y": 0.0,
  966. "tools_transform_mirror_reference": False,
  967. "tools_transform_mirror_point": (0, 0),
  968. # SolderPaste Tool
  969. "tools_solderpaste_tools": "0.0393701, 0.011811",
  970. "tools_solderpaste_new": 0.011811,
  971. "tools_solderpaste_z_start": 0.00019685039,
  972. "tools_solderpaste_z_dispense": 0.00393701,
  973. "tools_solderpaste_z_stop": 0.00019685039,
  974. "tools_solderpaste_z_travel": 0.00393701,
  975. "tools_solderpaste_z_toolchange": 0.0393701,
  976. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  977. "tools_solderpaste_frxy": 3.0,
  978. "tools_solderpaste_frz": 3.0,
  979. "tools_solderpaste_frz_dispense": 0.0393701,
  980. "tools_solderpaste_speedfwd": 20,
  981. "tools_solderpaste_dwellfwd": 1,
  982. "tools_solderpaste_speedrev": 10,
  983. "tools_solderpaste_dwellrev": 1,
  984. "tools_solderpaste_pp": 'Paste_1',
  985. # Subtract Tool
  986. "tools_sub_close_paths": True,
  987. # Utilities
  988. # file associations
  989. "fa_excellon": 'drd, drl, exc, ncd, tap, xln',
  990. "fa_gcode": 'cnc, din, dnc, ecs, eia, fan, fgc, fnc, gc, gcd, gcode, h, hnc, i, min, mpf, mpr, nc, ncc, '
  991. 'ncg, ncp, out, plt, ply, rol, sbp, tap, xpi',
  992. "fa_gerber": 'art, bot, bsm, cmp, crc, crs, dim, g4, gb0, gb1, gb2, gb3, gb5, gb6, gb7, gb8, gb9, gbd, '
  993. 'gbl, gbo, gbp, gbr, gbs, gdo, ger, gko, gm1, gm2, gm3, grb, gtl, gto, gtp, gts, ly15, ly2, '
  994. 'mil, pho, plc, pls, smb, smt, sol, spb, spt, ssb, sst, stc, sts, top, tsm',
  995. # Keyword list
  996. "util_autocomplete_keywords": 'Desktop, Documents, FlatConfig, FlatPrj, Marius, My Documents, Paste_1, '
  997. 'Repetier, Roland_MDX_20, Toolchange_Custom, Toolchange_Probe_MACH3, '
  998. 'Toolchange_manual, Users, all, angle_x, angle_y, axis, axisoffset, box, '
  999. 'center_x, center_y, columns, combine, connect, contour, default, '
  1000. 'depthperpass, dia, diatol, dist, drilled_dias, drillz, dwell, dwelltime, '
  1001. 'feedrate_z, grbl_11, grbl_laser, gridoffsety, gridx, gridy, has_offset, '
  1002. 'holes, hpgl, iso_type, line_xyz, margin, marlin, method, milled_dias, '
  1003. 'minoffset, multidepth, name, offset, opt_type, order, outname, overlap, '
  1004. 'passes, postamble, pp, ppname_e, ppname_g, preamble, radius, ref, rest, '
  1005. 'rows, shellvar_, scale_factor, spacing_columns, spacing_rows, spindlespeed, '
  1006. 'toolchange_xy, use_threads, value, x, x0, x1, y, y0, y1, z_cut, z_move'
  1007. ,
  1008. })
  1009. # ############################################################
  1010. # ############### Load defaults from file ####################
  1011. # ############################################################
  1012. if user_defaults:
  1013. self.load_defaults(filename='current_defaults')
  1014. # #############################################################
  1015. # ############## APPLY APP LANGUAGE ###########################
  1016. # #############################################################
  1017. ret_val = fcTranslate.apply_language('strings')
  1018. if ret_val == "no language":
  1019. self.inform.emit('[ERROR] %s' %
  1020. _("Could not find the Language files. The App strings are missing."))
  1021. log.debug("Could not find the Language files. The App strings are missing.")
  1022. else:
  1023. # make the current language the current selection on the language combobox
  1024. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1025. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1026. # ##############################################################
  1027. # ################# CREATE UNIQUE SERIAL NUMBER ################
  1028. # ##############################################################
  1029. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1030. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1031. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  1032. self.save_defaults(silent=True)
  1033. self.propagate_defaults(silent=True)
  1034. self.restore_main_win_geom()
  1035. def auto_save_defaults():
  1036. try:
  1037. self.save_defaults(silent=True)
  1038. self.propagate_defaults(silent=True)
  1039. finally:
  1040. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1041. # the following lines activates automatic defaults save
  1042. # if user_defaults:
  1043. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1044. # self.options_form = PreferencesUI()
  1045. self.options_form_fields = {
  1046. "units": self.ui.general_options_form.general_app_group.units_radio,
  1047. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  1048. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  1049. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  1050. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  1051. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  1052. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  1053. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  1054. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  1055. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  1056. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  1057. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  1058. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  1059. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  1060. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  1061. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  1062. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  1063. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  1064. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  1065. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  1066. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  1067. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  1068. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  1069. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  1070. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  1071. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  1072. "excellon_endz": self.ui.excellon_options_form.excellon_opt_group.eendz_entry,
  1073. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  1074. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  1075. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  1076. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  1077. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  1078. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  1079. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  1080. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  1081. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1082. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  1083. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  1084. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  1085. "excellon_spindledir": self.ui.excellon_options_form.excellon_adv_opt_group.spindledir_radio,
  1086. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  1087. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  1088. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  1089. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  1090. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  1091. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  1092. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  1093. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  1094. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  1095. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  1096. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  1097. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  1098. "geometry_endz": self.ui.geometry_options_form.geometry_opt_group.gendz_entry,
  1099. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  1100. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  1101. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  1102. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  1103. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1104. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  1105. "geometry_spindledir": self.ui.geometry_options_form.geometry_adv_opt_group.spindledir_radio,
  1106. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  1107. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  1108. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  1109. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  1110. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  1111. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  1112. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  1113. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  1114. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  1115. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  1116. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  1117. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  1118. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  1119. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  1120. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  1121. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  1122. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  1123. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  1124. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  1125. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  1126. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  1127. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  1128. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  1129. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  1130. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  1131. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  1132. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  1133. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  1134. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  1135. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  1136. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  1137. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  1138. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  1139. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  1140. }
  1141. for name in list(self.postprocessors.keys()):
  1142. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1143. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1144. self.options = LoudDict()
  1145. self.options.set_change_callback(self.on_options_dict_change)
  1146. self.options.update({
  1147. "units": "IN",
  1148. "global_gridx": 1.0,
  1149. "global_gridy": 1.0,
  1150. "global_snap_max": 0.05,
  1151. "global_background_timeout": 300000, # Default value is 5 minutes
  1152. "global_verbose_error_level": 0, # Shell verbosity:
  1153. # 0 = default(python trace only for unknown errors),
  1154. # 1 = show trace(show trace allways), 2 = (For the future).
  1155. "gerber_plot": True,
  1156. "gerber_solid": True,
  1157. "gerber_multicolored": False,
  1158. "gerber_isotooldia": 0.016,
  1159. "gerber_isopasses": 1,
  1160. "gerber_isooverlap": 0.15,
  1161. "gerber_combine_passes": True,
  1162. "gerber_noncoppermargin": 0.0,
  1163. "gerber_noncopperrounded": False,
  1164. "gerber_bboxmargin": 0.0,
  1165. "gerber_bboxrounded": False,
  1166. "excellon_plot": True,
  1167. "excellon_solid": False,
  1168. "excellon_format_upper_in": 2,
  1169. "excellon_format_lower_in": 4,
  1170. "excellon_format_upper_mm": 3,
  1171. "excellon_format_lower_mm": 3,
  1172. "excellon_units": 'INCH',
  1173. "excellon_optimization_type": 'B',
  1174. "excellon_search_time": 3,
  1175. "excellon_zeros": "L",
  1176. "excellon_drillz": -0.1,
  1177. "excellon_travelz": 0.1,
  1178. "excellon_feedrate": 3.0,
  1179. "excellon_feedrate_rapid": 3.0,
  1180. "excellon_spindlespeed": None,
  1181. "excellon_spindledir": 'CW',
  1182. "excellon_dwell": True,
  1183. "excellon_dwelltime": 1000,
  1184. "excellon_toolchange": False,
  1185. "excellon_toolchangez": 1.0,
  1186. "excellon_toolchangexy": "0.0, 0.0",
  1187. "excellon_tooldia": 0.016,
  1188. "excellon_ppname_e": 'default',
  1189. "excellon_f_plunge": False,
  1190. "excellon_startz": None,
  1191. "excellon_endz": 2.0,
  1192. "geometry_plot": True,
  1193. "geometry_segx": 0.0,
  1194. "geometry_segy": 0.0,
  1195. "geometry_cutz": -0.002,
  1196. "geometry_vtipdia": 0.1,
  1197. "geometry_vtipangle": 30,
  1198. "geometry_travelz": 0.1,
  1199. "geometry_feedrate": 3.0,
  1200. "geometry_feedrate_z": 3.0,
  1201. "geometry_feedrate_rapid": 3.0,
  1202. "geometry_spindlespeed": None,
  1203. "geometry_spindledir": 'CW',
  1204. "geometry_dwell": True,
  1205. "geometry_dwelltime": 1000,
  1206. "geometry_cnctooldia": 0.016,
  1207. "geometry_toolchange": False,
  1208. "geometry_toolchangez": 2.0,
  1209. "geometry_toolchangexy": "0.0, 0.0",
  1210. "geometry_startz": None,
  1211. "geometry_endz": 2.0,
  1212. "geometry_ppname_g": "default",
  1213. "geometry_f_plunge": False,
  1214. "geometry_depthperpass": 0.002,
  1215. "geometry_multidepth": False,
  1216. "geometry_extracut": False,
  1217. "cncjob_plot": True,
  1218. "cncjob_tooldia": 0.016,
  1219. "cncjob_prepend": "",
  1220. "cncjob_append": "",
  1221. "tools_ncctools": "1.0, 0.5",
  1222. "tools_nccoverlap": 0.4,
  1223. "tools_nccmargin": 1,
  1224. "tools_cutouttooldia": 0.07,
  1225. "tools_cutoutmargin": 0.1,
  1226. "tools_cutoutgapsize": 0.15,
  1227. "tools_gaps_ff": "8",
  1228. "tools_painttooldia": 0.07,
  1229. "tools_paintoverlap": 0.15,
  1230. "tools_paintmargin": 0.0,
  1231. "tools_paintmethod": "seed",
  1232. "tools_selectmethod": "single",
  1233. "tools_pathconnect": True,
  1234. "tools_paintcontour": True,
  1235. "tools_2sided_mirror_axis": "X",
  1236. "tools_2sided_axis_loc": 'point',
  1237. "tools_2sided_drilldia": 1,
  1238. "tools_film_type": 'neg',
  1239. "tools_film_boundary": 1,
  1240. "tools_film_scale": 0,
  1241. "tools_panelize_spacing_columns": 0,
  1242. "tools_panelize_spacing_rows": 0,
  1243. "tools_panelize_columns": 1,
  1244. "tools_panelize_rows": 1,
  1245. "tools_panelize_constrain": False,
  1246. "tools_panelize_constrainx": 0.0,
  1247. "tools_panelize_constrainy": 0.0
  1248. })
  1249. self.options.update(self.defaults) # Copy app defaults to project options
  1250. self.gen_form = None
  1251. self.ger_form = None
  1252. self.exc_form = None
  1253. self.geo_form = None
  1254. self.cnc_form = None
  1255. self.tools_form = None
  1256. self.fa_form = None
  1257. self.on_options_combo_change(0) # Will show the initial form
  1258. # ################################
  1259. # ### Initialize the color box's color in Preferences -> Global -> Color
  1260. # Init Plot Colors
  1261. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  1262. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  1263. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  1264. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  1265. int(self.defaults['global_plot_fill'][7:9], 16))
  1266. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  1267. int(self.defaults['global_plot_fill'][7:9], 16))
  1268. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  1269. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  1270. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  1271. # Init Left-Right Selection colors
  1272. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  1273. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  1274. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  1275. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1276. int(self.defaults['global_sel_fill'][7:9], 16))
  1277. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1278. int(self.defaults['global_sel_fill'][7:9], 16))
  1279. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1280. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1281. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  1282. # Init Right-Left Selection colors
  1283. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1284. self.defaults['global_alt_sel_fill'])
  1285. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1286. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  1287. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1288. int(self.defaults['global_sel_fill'][7:9], 16))
  1289. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1290. int(self.defaults['global_sel_fill'][7:9], 16))
  1291. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1292. self.defaults['global_alt_sel_line'])
  1293. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1294. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  1295. # Init Draw color and Selection Draw Color
  1296. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1297. self.defaults['global_draw_color'])
  1298. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1299. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1300. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1301. self.defaults['global_sel_draw_color'])
  1302. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1303. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1304. # Init Project Items color
  1305. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1306. self.defaults['global_proj_item_color'])
  1307. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1308. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1309. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1310. self.defaults['global_proj_item_dis_color'])
  1311. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1312. "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1313. # Init the Annotation CNC Job color
  1314. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  1315. self.defaults['cncjob_annotation_fontcolor'])
  1316. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  1317. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  1318. # Init the Tool Film color
  1319. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  1320. self.defaults['tools_film_color'])
  1321. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  1322. "background-color:%s" % str(self.defaults['tools_film_color'])[:7])
  1323. # ### End of Data ####
  1324. # ###############################################
  1325. # ############# SETUP Plot Area #################
  1326. # ###############################################
  1327. if show_splash:
  1328. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1329. "Canvas initialization started."),
  1330. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1331. color=QtGui.QColor("gray"))
  1332. start_plot_time = time.time() # debug
  1333. self.plotcanvas = None
  1334. self.app_cursor = None
  1335. self.hover_shapes = None
  1336. self.on_plotcanvas_setup()
  1337. end_plot_time = time.time()
  1338. self.used_time = end_plot_time - start_plot_time
  1339. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1340. if show_splash:
  1341. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1342. "Canvas initialization started.\n"
  1343. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1344. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1345. color=QtGui.QColor("gray"))
  1346. self.ui.splitter.setStretchFactor(1, 2)
  1347. # #################################################################
  1348. # ####################### SYS TRAY ################################
  1349. # #################################################################
  1350. if self.defaults["global_systray_icon"]:
  1351. self.parent_w = QtWidgets.QWidget()
  1352. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1353. parent=self.parent_w)
  1354. # ##############################################
  1355. # ######### SETUP OBJECT COLLECTION ############
  1356. # ##############################################
  1357. self.collection = ObjectCollection(self)
  1358. self.ui.project_tab_layout.addWidget(self.collection.view)
  1359. # ### Adjust tabs width ## ##
  1360. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1361. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1362. self.collection.view.setMinimumWidth(290)
  1363. self.log.debug("Finished creating Object Collection.")
  1364. # ###############################################
  1365. # ############# Worker SETUP ####################
  1366. # ###############################################
  1367. if self.defaults["global_worker_number"]:
  1368. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1369. else:
  1370. self.workers = WorkerStack(workers_number=2)
  1371. self.worker_task.connect(self.workers.add_task)
  1372. self.log.debug("Finished creating Workers crew.")
  1373. # ################################################
  1374. # ############### Signal handling ################
  1375. # ################################################
  1376. # ############# Custom signals ##################
  1377. # signal for displaying messages in status bar
  1378. self.inform.connect(self.info)
  1379. # signal to be called when the app is quiting
  1380. self.app_quit.connect(self.quit_application)
  1381. self.message.connect(self.message_dialog)
  1382. self.progress.connect(self.set_progress_bar)
  1383. # signals that are emitted when object state changes
  1384. self.object_created.connect(self.on_object_created)
  1385. self.object_changed.connect(self.on_object_changed)
  1386. self.object_plotted.connect(self.on_object_plotted)
  1387. self.plots_updated.connect(self.on_plots_updated)
  1388. # signals emitted when file state change
  1389. self.file_opened.connect(self.register_recent)
  1390. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1391. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1392. # ############# Standard signals ###################
  1393. # ### Menu
  1394. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1395. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1396. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1397. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1398. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1399. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1400. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1401. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1402. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1403. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1404. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1405. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1406. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1407. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1408. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1409. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1410. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1411. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1412. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1413. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1414. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1415. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1416. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1417. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1418. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1419. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1420. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1421. self.ui.menufile_exit.triggered.connect(self.final_save)
  1422. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1423. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1424. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1425. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1426. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1427. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1428. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1429. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1430. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1431. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1432. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1433. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1434. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1435. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1436. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1437. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1438. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1439. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1440. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1441. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1442. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1443. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1444. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1445. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1446. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1447. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1448. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1449. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1450. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1451. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1452. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1453. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1454. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1455. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1456. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1457. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1458. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1459. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1460. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1461. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1462. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1463. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1464. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1465. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1466. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1467. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1468. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1469. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1470. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1471. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1472. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1473. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1474. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1475. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1476. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1477. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1478. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1479. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1480. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1481. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1482. # ToolBar signals
  1483. self.connect_toolbar_signals()
  1484. # Notebook signals
  1485. # make the right click on the notebook tab connect to a function
  1486. self.ui.notebook.setupContextMenu()
  1487. self.ui.notebook.addContextMenu(
  1488. _("Detachable Tabs"), self.on_notebook_tab_rmb_click,
  1489. initial_checked=self.defaults["global_tabs_detachable"])
  1490. # activate initial state
  1491. self.on_notebook_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1492. # Context Menu
  1493. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1494. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1495. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1496. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1497. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1498. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1499. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1500. self.ui.clearplot.triggered.connect(self.clear_plots)
  1501. self.ui.replot.triggered.connect(self.plot_all)
  1502. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1503. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1504. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1505. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1506. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1507. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1508. # Preferences Plot Area TAB
  1509. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1510. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1511. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1512. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1513. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1514. # ##############################
  1515. # ### GUI PREFERENCES SIGNALS ##
  1516. # ##############################
  1517. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1518. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1519. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1520. )
  1521. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1522. lambda: self.on_toggle_units(no_pref=False))
  1523. # ###############################################################
  1524. # ################### GUI COLORS SIGNALS ########################
  1525. # ###############################################################
  1526. # Setting plot colors signals
  1527. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1528. self.on_pf_color_entry)
  1529. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1530. self.on_pf_color_button)
  1531. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1532. self.on_pf_color_spinner)
  1533. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1534. self.on_pf_color_slider)
  1535. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1536. self.on_pl_color_entry)
  1537. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1538. self.on_pl_color_button)
  1539. # Setting selection (left - right) colors signals
  1540. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1541. self.on_sf_color_entry)
  1542. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1543. self.on_sf_color_button)
  1544. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1545. self.on_sf_color_spinner)
  1546. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1547. self.on_sf_color_slider)
  1548. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1549. self.on_sl_color_entry)
  1550. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1551. self.on_sl_color_button)
  1552. # Setting selection (right - left) colors signals
  1553. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1554. self.on_alt_sf_color_entry)
  1555. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1556. self.on_alt_sf_color_button)
  1557. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1558. self.on_alt_sf_color_spinner)
  1559. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1560. self.on_alt_sf_color_slider)
  1561. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1562. self.on_alt_sl_color_entry)
  1563. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1564. self.on_alt_sl_color_button)
  1565. # Setting Editor Draw colors signals
  1566. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1567. self.on_draw_color_entry)
  1568. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1569. self.on_draw_color_button)
  1570. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1571. self.on_sel_draw_color_entry)
  1572. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1573. self.on_sel_draw_color_button)
  1574. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1575. self.on_proj_color_entry)
  1576. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1577. self.on_proj_color_button)
  1578. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1579. self.on_proj_color_dis_entry)
  1580. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1581. self.on_proj_color_dis_button)
  1582. # ########## workspace setting signals ###########
  1583. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1584. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1585. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1586. # ########## CNC Job related signals #############
  1587. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1588. self.on_cnc_custom_parameters)
  1589. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.editingFinished.connect(
  1590. self.on_annotation_fontcolor_entry)
  1591. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.clicked.connect(
  1592. self.on_annotation_fontcolor_button)
  1593. # ########## Tools related signals #############
  1594. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1595. self.on_film_color_entry)
  1596. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1597. self.on_film_color_button)
  1598. # ########## Modify G-CODE Plot Area TAB ###########
  1599. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1600. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1601. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1602. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1603. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1604. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1605. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1606. # portability changed signal
  1607. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1608. # Object list
  1609. self.collection.view.activated.connect(self.on_row_activated)
  1610. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1611. self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1612. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1613. # Export Excellon parameters.
  1614. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1615. self.on_update_exc_export
  1616. )
  1617. # call it once to make sure it is updated at startup
  1618. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1619. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1620. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1621. self.on_excellon_defaults_button)
  1622. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1623. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1624. self.on_excellon_options_button)
  1625. # when there are arguments at application startup this get launched
  1626. self.args_at_startup[list].connect(self.on_startup_args)
  1627. # ##############################################################
  1628. # ############### FILE ASSOCIATIONS SIGNALS ####################
  1629. # ##############################################################
  1630. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1631. lambda: self.restore_extensions(ext_type='excellon'))
  1632. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1633. lambda: self.restore_extensions(ext_type='gcode'))
  1634. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1635. lambda: self.restore_extensions(ext_type='gerber'))
  1636. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1637. lambda: self.delete_all_extensions(ext_type='excellon'))
  1638. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1639. lambda: self.delete_all_extensions(ext_type='gcode'))
  1640. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1641. lambda: self.delete_all_extensions(ext_type='gerber'))
  1642. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1643. lambda: self.add_extension(ext_type='excellon'))
  1644. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1645. lambda: self.add_extension(ext_type='gcode'))
  1646. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1647. lambda: self.add_extension(ext_type='gerber'))
  1648. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1649. lambda: self.del_extension(ext_type='excellon'))
  1650. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1651. lambda: self.del_extension(ext_type='gcode'))
  1652. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1653. lambda: self.del_extension(ext_type='gerber'))
  1654. # connect the 'Apply' buttons from the Preferences/File Associations
  1655. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1656. lambda: self.on_register_files(obj_type='excellon'))
  1657. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1658. lambda: self.on_register_files(obj_type='gcode'))
  1659. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1660. lambda: self.on_register_files(obj_type='gerber'))
  1661. # ##############################################################
  1662. # ###################### KEYWORDS SIGNALS ######################
  1663. # ##############################################################
  1664. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1665. lambda: self.restore_extensions(ext_type='keyword'))
  1666. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1667. lambda: self.delete_all_extensions(ext_type='keyword'))
  1668. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1669. lambda: self.add_extension(ext_type='keyword'))
  1670. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1671. lambda: self.del_extension(ext_type='keyword'))
  1672. # splash screen button signal
  1673. self.ui.general_defaults_form.general_gui_set_group.splash_cb.stateChanged.connect(self.on_splash_changed)
  1674. # connect the abort_all_tasks related slots to the related signals
  1675. self.proc_container.idle_flag.connect(self.app_is_idle)
  1676. # #####################################################################################
  1677. # ########### FINISHED CONNECTING SIGNALS #############################################
  1678. # #####################################################################################
  1679. self.log.debug("Finished connecting Signals.")
  1680. # #####################################################################################
  1681. # ########################## Other setups #############################################
  1682. # #####################################################################################
  1683. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  1684. # depending on from where those tools are called different actions can be done
  1685. self.call_source = 'app'
  1686. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1687. self.tool_tab_locked = False
  1688. # decide if to show or hide the Notebook side of the screen at startup
  1689. if self.defaults["global_project_at_startup"] is True:
  1690. self.ui.splitter.setSizes([1, 1])
  1691. else:
  1692. self.ui.splitter.setSizes([0, 1])
  1693. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1694. self.setup_obj_classes()
  1695. self.setup_recent_items()
  1696. self.setup_component_editor()
  1697. # #####################################################################################
  1698. # ######################### Auto-complete KEYWORDS ####################################
  1699. # #####################################################################################
  1700. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1701. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1702. 'delete', 'drillcncjob', 'export_gcode', 'export_svg', 'ext', 'exteriors', 'follow',
  1703. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1704. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1705. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1706. 'mirror', 'ncc',
  1707. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1708. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'paint',
  1709. 'pan', 'panel', 'panelize', 'plot_all', 'plot_objects', 'save', 'save_project',
  1710. 'save_sys', 'scale',
  1711. 'set_active', 'set_sys', 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1712. 'version', 'write_gcode'
  1713. ]
  1714. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'Marius', 'My Documents', 'Paste_1',
  1715. 'Repetier', 'Roland_MDX_20', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  1716. 'Toolchange_manual', 'Users', 'all', 'angle_x', 'angle_y', 'axis', 'axisoffset',
  1717. 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect', 'contour', 'default',
  1718. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dwell',
  1719. 'dwelltime', 'feedrate_z', 'grbl_11', 'grbl_laser', 'gridoffsety', 'gridx', 'gridy',
  1720. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  1721. 'milled_dias', 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order',
  1722. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  1723. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  1724. 'spacing_columns',
  1725. 'spacing_rows', 'spindlespeed', 'toolchange_xy', 'use_threads', 'value', 'x',
  1726. 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1727. ]
  1728. self.tcl_keywords = [
  1729. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1730. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1731. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1732. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1733. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1734. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1735. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1736. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1737. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1738. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1739. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1740. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1741. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1742. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1743. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1744. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1745. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1746. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1747. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1748. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1749. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1750. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1751. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1752. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1753. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1754. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1755. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1756. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1757. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1758. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1759. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1760. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1761. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1762. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1763. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1764. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1765. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1766. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1767. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1768. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1769. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1770. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1771. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1772. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1773. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1774. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1775. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1776. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1777. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1778. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1779. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1780. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1781. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1782. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1783. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1784. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1785. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1786. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1787. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1788. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1789. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1790. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1791. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1792. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1793. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1794. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1795. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1796. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1797. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1798. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1799. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1800. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1801. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1802. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1803. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1804. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1805. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1806. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1807. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1808. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1809. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1810. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1811. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1812. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1813. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1814. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1815. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1816. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1817. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1818. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1819. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1820. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1821. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1822. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1823. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1824. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1825. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1826. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1827. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1828. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1829. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1830. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1831. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1832. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1833. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1834. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1835. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1836. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1837. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1838. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1839. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1840. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1841. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1842. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1843. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1844. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1845. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1846. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1847. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1848. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1849. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1850. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1851. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1852. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1853. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1854. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1855. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1856. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1857. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1858. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1859. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1860. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1861. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1862. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1863. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1864. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1865. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1866. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1867. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1868. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1869. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1870. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1871. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1872. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1873. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1874. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1875. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1876. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1877. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1878. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1879. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1880. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1881. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1882. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1883. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1884. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1885. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1886. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1887. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1888. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1889. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1890. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1891. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1892. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1893. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1894. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1895. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1896. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1897. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1898. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1899. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1900. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1901. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1902. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1903. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1904. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1905. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1906. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1907. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1908. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1909. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1910. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1911. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1912. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1913. ]
  1914. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1915. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1916. # ####################################################################################
  1917. # ####################### Shell SETUP ################################################
  1918. # ####################################################################################
  1919. self.shell = FCShell(self, version=self.version)
  1920. self.shell._edit.set_model_data(self.myKeywords)
  1921. self.ui.code_editor.set_model_data(self.myKeywords)
  1922. self.shell.setWindowIcon(self.ui.app_icon)
  1923. self.shell.setWindowTitle("FlatCAM Shell")
  1924. self.shell.resize(*self.defaults["global_shell_shape"])
  1925. self.shell.append_output("FlatCAM %s - " % self.version)
  1926. self.shell.append_output(_("Open Source Software - Type help to get started\n\n"))
  1927. self.init_tcl()
  1928. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1929. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1930. self.ui.shell_dock.setWidget(self.shell)
  1931. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1932. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1933. QtWidgets.QDockWidget.DockWidgetFloatable |
  1934. QtWidgets.QDockWidget.DockWidgetClosable)
  1935. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1936. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1937. if self.defaults["global_shell_at_startup"]:
  1938. self.ui.shell_dock.show()
  1939. else:
  1940. self.ui.shell_dock.hide()
  1941. # ##################################################################################
  1942. # ###################### Tools and Plugins #########################################
  1943. # ##################################################################################
  1944. self.dblsidedtool = None
  1945. self.measurement_tool = None
  1946. self.panelize_tool = None
  1947. self.film_tool = None
  1948. self.paste_tool = None
  1949. self.calculator_tool = None
  1950. self.sub_tool = None
  1951. self.move_tool = None
  1952. self.cutout_tool = None
  1953. self.ncclear_tool = None
  1954. self.paint_tool = None
  1955. self.transform_tool = None
  1956. self.properties_tool = None
  1957. self.pdf_tool = None
  1958. self.image_tool = None
  1959. self.pcb_wizard_tool = None
  1960. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1961. self.install_tools()
  1962. # ### System Font Parsing ###
  1963. # self.f_parse = ParseFont(self)
  1964. # self.parse_system_fonts()
  1965. # #####################################################################################
  1966. # ######################## Check for updates ##########################################
  1967. # #####################################################################################
  1968. # Separate thread (Not worker)
  1969. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1970. if (self.beta is False or self.beta is None) and \
  1971. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1972. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1973. self.thr2 = QtCore.QThread()
  1974. self.worker_task.emit({'fcn': self.version_check,
  1975. 'params': []})
  1976. self.thr2.start(QtCore.QThread.LowPriority)
  1977. # #####################################################################################
  1978. # ######################### Register files with FlatCAM; #############################
  1979. # ######################### It works only for Windows for now ########################
  1980. # #####################################################################################
  1981. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1982. self.on_register_files()
  1983. # #####################################################################################
  1984. # ###################### Variables for global usage ###################################
  1985. # #####################################################################################
  1986. # coordinates for relative position display
  1987. self.rel_point1 = (0, 0)
  1988. self.rel_point2 = (0, 0)
  1989. # variable to store coordinates
  1990. self.pos = (0, 0)
  1991. self.pos_jump = (0, 0)
  1992. # variable to store mouse coordinates
  1993. self.mouse = [0, 0]
  1994. # decide if we have a double click or single click
  1995. self.doubleclick = False
  1996. # variable to store if a command is active (then the var is not None) and which one it is
  1997. self.command_active = None
  1998. # variable to store the status of moving selection action
  1999. # None value means that it's not an selection action
  2000. # True value = a selection from left to right
  2001. # False value = a selection from right to left
  2002. self.selection_type = None
  2003. # List to store the objects that are currently loaded in FlatCAM
  2004. # This list is updated on each object creation or object delete
  2005. self.all_objects_list = list()
  2006. # List to store the objects that are selected
  2007. self.sel_objects_list = list()
  2008. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  2009. self.key_modifiers = None
  2010. # Variable to hold the status of the axis
  2011. self.toggle_axis = True
  2012. # Variable to store the status of the fullscreen event
  2013. self.toggle_fscreen = False
  2014. # Variable to store the status of the code editor
  2015. self.toggle_codeeditor = False
  2016. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  2017. self.click_noproject = False
  2018. self.cursor = None
  2019. # Variable to store the GCODE that was edited
  2020. self.gcode_edited = ""
  2021. # reference for the self.ui.code_editor
  2022. self.reference_code_editor = None
  2023. self.script_code = ''
  2024. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  2025. self.preferences_changed_flag = False
  2026. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  2027. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  2028. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'pho',
  2029. 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top', 'tsm']
  2030. self.exc_list = ['drd', 'drl', 'exc', 'ncd', 'tap', 'txt', 'xln']
  2031. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  2032. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ncp', 'out', 'plt', 'ply', 'rol', 'sbp',
  2033. 'tap', 'xpi']
  2034. self.svg_list = ['svg']
  2035. self.dxf_list = ['dxf']
  2036. self.pdf_list = ['pdf']
  2037. self.prj_list = ['flatprj']
  2038. self.conf_list = ['flatconfig']
  2039. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  2040. # flag for polygons not cleared
  2041. self.poly_not_cleared = False
  2042. # VisPy visuals
  2043. self.isHovering = False
  2044. self.notHovering = True
  2045. # when True, the app has to return from any thread
  2046. self.abort_flag = False
  2047. # ###############################################################################
  2048. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  2049. # ############# It's done only once after install ###############
  2050. # ###############################################################################
  2051. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  2052. fac_def_from_file = factory_file.read()
  2053. factory_defaults = json.loads(fac_def_from_file)
  2054. # if the file contain an empty dictionary then save the factory defaults into the file
  2055. if not factory_defaults:
  2056. self.save_factory_defaults(silent=False)
  2057. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  2058. initial_lay = 'compact'
  2059. self.on_layout(lay=initial_lay)
  2060. # Set the combobox in Preferences to the current layout
  2061. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  2062. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  2063. factory_file.close()
  2064. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  2065. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  2066. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  2067. # after the first run, this object should be False
  2068. self.defaults["first_run"] = False
  2069. # ###############################################################################
  2070. # ################# ADDING FlatCAM EDITORS section ##############################
  2071. # ###############################################################################
  2072. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2073. # at the first launch of the App , the editors will not be functional.
  2074. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  2075. self.exc_editor = FlatCAMExcEditor(self)
  2076. self.grb_editor = FlatCAMGrbEditor(self)
  2077. self.log.debug("Finished adding FlatCAM Editor's.")
  2078. self.set_ui_title(name=_("New Project - Not saved"))
  2079. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2080. current_platform = platform.architecture()[0]
  2081. if current_platform != '64bit':
  2082. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2083. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2084. # ###############################################################################
  2085. # ####################### Finished the CONSTRUCTOR ##############################
  2086. # ###############################################################################
  2087. App.log.debug("END of constructor. Releasing control.")
  2088. # #####################################################################################
  2089. # ########################## SHOW GUI #################################################
  2090. # #####################################################################################
  2091. # finish the splash
  2092. self.splash.finish(self.ui)
  2093. settings = QSettings("Open Source", "FlatCAM")
  2094. if settings.contains("maximized_gui"):
  2095. maximized_ui = settings.value('maximized_gui', type=bool)
  2096. if maximized_ui is True:
  2097. self.ui.showMaximized()
  2098. else:
  2099. self.ui.show()
  2100. else:
  2101. self.ui.show()
  2102. if self.defaults["global_systray_icon"]:
  2103. self.trayIcon.show()
  2104. # #####################################################################################
  2105. # ########################## START-UP ARGUMENTS #######################################
  2106. # #####################################################################################
  2107. # test if the program was started with a script as parameter
  2108. if self.cmd_line_shellvar:
  2109. try:
  2110. cnt = 0
  2111. command_tcl = 0
  2112. for i in self.cmd_line_shellvar.split(','):
  2113. if i is not None:
  2114. try:
  2115. command_tcl = eval(i)
  2116. except:
  2117. command_tcl = i
  2118. command_tcl_formatted = 'set shellvar_{nr} {cmd}'.format(cmd=str(command_tcl), nr=str(cnt))
  2119. cnt += 1
  2120. # if there are Windows paths then replace the path separator with a Unix like one
  2121. if sys.platform == 'win32':
  2122. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  2123. self.shell._sysShell.exec_command(command_tcl_formatted, no_echo=True)
  2124. except Exception as ext:
  2125. print("ERROR: ", ext)
  2126. sys.exit(2)
  2127. if self.cmd_line_shellfile:
  2128. try:
  2129. if self.ui.shell_dock.isHidden():
  2130. self.ui.shell_dock.show()
  2131. with open(self.cmd_line_shellfile, "r") as myfile:
  2132. if show_splash:
  2133. self.splash.showMessage('%s: %ssec\n%s' % (
  2134. _("Canvas initialization started.\n"
  2135. "Canvas initialization finished in"), '%.2f' % self.used_time,
  2136. _("Executing Tcl Script ...")),
  2137. alignment=Qt.AlignBottom | Qt.AlignLeft,
  2138. color=QtGui.QColor("gray"))
  2139. cmd_line_shellfile_text = myfile.read()
  2140. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  2141. except Exception as ext:
  2142. print("ERROR: ", ext)
  2143. sys.exit(2)
  2144. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2145. # the path/file_name must be enclosed in quotes if it contain spaces
  2146. if App.args:
  2147. self.args_at_startup.emit(App.args)
  2148. @staticmethod
  2149. def copy_and_overwrite(from_path, to_path):
  2150. """
  2151. From here:
  2152. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2153. :param from_path: source path
  2154. :param to_path: destination path
  2155. :return: None
  2156. """
  2157. if os.path.exists(to_path):
  2158. shutil.rmtree(to_path)
  2159. try:
  2160. shutil.copytree(from_path, to_path)
  2161. except FileNotFoundError:
  2162. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2163. shutil.copytree(from_new_path, to_path)
  2164. def on_startup_args(self, args, silent=False):
  2165. """
  2166. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2167. :param args: a list containing the application args at startup
  2168. :return: None
  2169. """
  2170. if args is not None:
  2171. args_to_process = args
  2172. else:
  2173. args_to_process = App.args
  2174. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2175. for argument in args_to_process:
  2176. if '.FlatPrj'.lower() in argument.lower():
  2177. try:
  2178. project_name = str(argument)
  2179. if project_name == "":
  2180. if silent is False:
  2181. self.inform.emit(_("Open cancelled."))
  2182. else:
  2183. # self.open_project(project_name)
  2184. run_from_arg = True
  2185. # self.worker_task.emit({'fcn': self.open_project,
  2186. # 'params': [project_name, run_from_arg]})
  2187. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2188. except Exception as e:
  2189. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2190. elif '.FlatConfig'.lower() in argument.lower():
  2191. try:
  2192. file_name = str(argument)
  2193. if file_name == "":
  2194. if silent is False:
  2195. self.inform.emit(_("Open Config file failed."))
  2196. else:
  2197. run_from_arg = True
  2198. # self.worker_task.emit({'fcn': self.open_config_file,
  2199. # 'params': [file_name, run_from_arg]})
  2200. self.open_config_file(file_name, run_from_arg=run_from_arg)
  2201. except Exception as e:
  2202. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2203. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  2204. try:
  2205. file_name = str(argument)
  2206. if file_name == "":
  2207. if silent is False:
  2208. self.inform.emit(_("Open Script file failed."))
  2209. else:
  2210. if silent is False:
  2211. self.on_fileopenscript(name=file_name)
  2212. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  2213. self.on_filerunscript(name=file_name)
  2214. except Exception as e:
  2215. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2216. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  2217. log.debug("App.on_startup_args() --> Quit event.")
  2218. sys.exit()
  2219. elif 'save'.lower() in argument.lower():
  2220. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  2221. self.save_defaults()
  2222. else:
  2223. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2224. proc_arg = argument.lower()
  2225. for ext in exc_list:
  2226. proc_ext = ext.replace(' ', '')
  2227. proc_ext = '.%s' % proc_ext
  2228. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2229. file_name = str(argument)
  2230. if file_name == "":
  2231. if silent is False:
  2232. self.inform.emit(_("Open Excellon file failed."))
  2233. else:
  2234. self.on_fileopenexcellon(name=file_name)
  2235. return
  2236. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2237. for ext in gco_list:
  2238. proc_ext = ext.replace(' ', '')
  2239. proc_ext = '.%s' % proc_ext
  2240. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2241. print(proc_ext, proc_arg)
  2242. file_name = str(argument)
  2243. if file_name == "":
  2244. if silent is False:
  2245. self.inform.emit(_("Open GCode file failed."))
  2246. else:
  2247. self.on_fileopengcode(name=file_name)
  2248. return
  2249. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2250. for ext in grb_list:
  2251. proc_ext = ext.replace(' ', '')
  2252. proc_ext = '.%s' % proc_ext
  2253. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2254. file_name = str(argument)
  2255. if file_name == "":
  2256. if silent is False:
  2257. self.inform.emit(_("Open Gerber file failed."))
  2258. else:
  2259. self.on_fileopengerber(name=file_name)
  2260. return
  2261. # if it reached here without already returning then the app was registered with a file that it does not
  2262. # recognize therefore we must quit
  2263. sys.exit(2)
  2264. def set_ui_title(self, name):
  2265. """
  2266. Sets the title of the main window.
  2267. :param name: String that store the project path and project name
  2268. :return: None
  2269. """
  2270. self.ui.setWindowTitle('FlatCAM %s %s - %s %s' %
  2271. (self.version,
  2272. ('BETA' if self.beta else ''),
  2273. platform.architecture()[0],
  2274. name)
  2275. )
  2276. def defaults_read_form(self):
  2277. """
  2278. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2279. :return: None
  2280. """
  2281. for option in self.defaults_form_fields:
  2282. try:
  2283. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2284. except Exception as e:
  2285. log.debug("App.defaults_read_form() --> %s" % str(e))
  2286. def defaults_write_form(self, factor=None, fl_units=None):
  2287. """
  2288. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2289. self.defaults dictionary.
  2290. :param factor: will apply a factor to the values that written in the GUI elements
  2291. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2292. :return: None
  2293. """
  2294. for option in self.defaults:
  2295. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2296. # try:
  2297. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2298. # except KeyError:
  2299. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2300. # # TODO: Rethink this?
  2301. # pass
  2302. def defaults_write_form_field(self, field, factor=None, units=None):
  2303. """
  2304. Basically it is the worker in the self.defaults_write_form()
  2305. :param field: the GUI element in Preferences GUI to be updated
  2306. :param factor: factor to be applied to the field parameter
  2307. :param units: current FLatCAM measuring units
  2308. :return: None, it updates GUI elements
  2309. """
  2310. try:
  2311. if factor is None:
  2312. if units is None:
  2313. self.defaults_form_fields[field].set_value(self.defaults[field])
  2314. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2315. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=6)
  2316. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2317. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=4)
  2318. else:
  2319. if units is None:
  2320. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2321. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2322. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=6)
  2323. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2324. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=4)
  2325. except KeyError:
  2326. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2327. # TODO: Rethink this?
  2328. pass
  2329. except AttributeError:
  2330. log.debug(field)
  2331. def clear_pool(self):
  2332. """
  2333. Clear the multiprocessing pool and calls garbage collector.
  2334. :return: None
  2335. """
  2336. self.pool.close()
  2337. self.pool = Pool()
  2338. self.pool_recreated.emit(self.pool)
  2339. gc.collect()
  2340. def install_tools(self):
  2341. """
  2342. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2343. Instantiation of the Tools classes.
  2344. The order that the tools are installed is important as they can depend on each other install position.
  2345. :return: None
  2346. """
  2347. self.dblsidedtool = DblSidedTool(self)
  2348. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2349. self.measurement_tool = Measurement(self)
  2350. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  2351. self.panelize_tool = Panelize(self)
  2352. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  2353. self.film_tool = Film(self)
  2354. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2355. self.paste_tool = SolderPaste(self)
  2356. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2357. self.calculator_tool = ToolCalculator(self)
  2358. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'), separator=True)
  2359. self.sub_tool = ToolSub(self)
  2360. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2361. self.move_tool = ToolMove(self)
  2362. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2363. before=self.ui.menueditorigin)
  2364. self.cutout_tool = CutOut(self)
  2365. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2366. before=self.measurement_tool.menuAction)
  2367. self.ncclear_tool = NonCopperClear(self)
  2368. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2369. before=self.measurement_tool.menuAction, separator=True)
  2370. self.paint_tool = ToolPaint(self)
  2371. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2372. before=self.measurement_tool.menuAction, separator=True)
  2373. self.transform_tool = ToolTransform(self)
  2374. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2375. self.properties_tool = Properties(self)
  2376. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2377. self.pdf_tool = ToolPDF(self)
  2378. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2379. separator=True)
  2380. self.image_tool = ToolImage(self)
  2381. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2382. separator=True)
  2383. self.pcb_wizard_tool = PcbWizard(self)
  2384. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2385. self.log.debug("Tools are installed.")
  2386. def remove_tools(self):
  2387. """
  2388. Will remove all the actions in the Tool menu.
  2389. :return: None
  2390. """
  2391. for act in self.ui.menutool.actions():
  2392. self.ui.menutool.removeAction(act)
  2393. def init_tools(self):
  2394. """
  2395. Initialize the Tool tab in the notebook side of the central widget.
  2396. Remove the actions in the Tools menu.
  2397. Instantiate again the FlatCAM tools (plugins).
  2398. All this is required when changing the layout: standard, compact etc.
  2399. :return: None
  2400. """
  2401. log.debug("init_tools()")
  2402. # delete the data currently in the Tools Tab and the Tab itself
  2403. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2404. if widget is not None:
  2405. widget.deleteLater()
  2406. self.ui.notebook.removeTab(2)
  2407. # rebuild the Tools Tab
  2408. self.ui.tool_tab = QtWidgets.QWidget()
  2409. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2410. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2411. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2412. self.ui.tool_scroll_area = VerticalScrollArea()
  2413. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2414. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2415. # first remove all of them
  2416. self.remove_tools()
  2417. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2418. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2419. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2420. # third install all of them
  2421. self.install_tools()
  2422. self.log.debug("Tools are initialized.")
  2423. # def parse_system_fonts(self):
  2424. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2425. # 'params': []})
  2426. def connect_toolbar_signals(self):
  2427. """
  2428. Reconnect the signals to the actions in the toolbar.
  2429. This has to be done each time after the FlatCAM tools are removed/installed.
  2430. :return: None
  2431. """
  2432. # Toolbar
  2433. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2434. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2435. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2436. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2437. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2438. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2439. self.ui.replot_btn.triggered.connect(self.plot_all)
  2440. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2441. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2442. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2443. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2444. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2445. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2446. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2447. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2448. self.ui.delete_btn.triggered.connect(self.on_delete)
  2449. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2450. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2451. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2452. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2453. # Tools Toolbar Signals
  2454. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2455. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2456. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2457. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2458. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2459. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2460. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2461. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2462. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2463. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2464. def object2editor(self):
  2465. """
  2466. Send the current Geometry or Excellon object (if any) into the it's editor.
  2467. :return: None
  2468. """
  2469. self.report_usage("object2editor()")
  2470. edited_object = self.collection.get_active()
  2471. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2472. isinstance(edited_object, FlatCAMExcellon):
  2473. pass
  2474. else:
  2475. self.inform.emit('[WARNING_NOTCL] %s' %
  2476. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2477. return
  2478. if isinstance(edited_object, FlatCAMGeometry):
  2479. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2480. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2481. # we set the notebook to hidden
  2482. self.ui.splitter.setSizes([0, 1])
  2483. if edited_object.multigeo is True:
  2484. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  2485. if len(edited_tools) > 1:
  2486. self.inform.emit('[WARNING_NOTCL] %s' %
  2487. _("Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  2488. "is not possible.\n"
  2489. "Edit only one geometry at a time."))
  2490. # determine the tool dia of the selected tool
  2491. selected_tooldia = float(edited_object.ui.geo_tools_table.item((edited_tools[0] - 1), 1).text())
  2492. # now find the key in the edited_object.tools that has this tooldia
  2493. multi_tool = 1
  2494. for tool in edited_object.tools:
  2495. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2496. multi_tool = tool
  2497. break
  2498. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2499. else:
  2500. self.geo_editor.edit_fcgeometry(edited_object)
  2501. # set call source to the Editor we go into
  2502. self.call_source = 'geo_editor'
  2503. elif isinstance(edited_object, FlatCAMExcellon):
  2504. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2505. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2506. if self.ui.splitter.sizes()[0] == 0:
  2507. self.ui.splitter.setSizes([1, 1])
  2508. self.exc_editor.edit_fcexcellon(edited_object)
  2509. # set call source to the Editor we go into
  2510. self.call_source = 'exc_editor'
  2511. elif isinstance(edited_object, FlatCAMGerber):
  2512. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2513. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2514. if self.ui.splitter.sizes()[0] == 0:
  2515. self.ui.splitter.setSizes([1, 1])
  2516. self.grb_editor.edit_fcgerber(edited_object)
  2517. # set call source to the Editor we go into
  2518. self.call_source = 'grb_editor'
  2519. # make sure that we can't select another object while in Editor Mode:
  2520. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2521. self.ui.project_frame.setDisabled(True)
  2522. # delete any selection shape that might be active as they are not relevant in Editor
  2523. self.delete_selection_shape()
  2524. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2525. self.ui.plot_tab_area.protectTab(0)
  2526. self.inform.emit('[WARNING_NOTCL] %s' %
  2527. _("Editor is activated ..."))
  2528. self.should_we_save = True
  2529. def editor2object(self, cleanup=None):
  2530. """
  2531. Transfers the Geometry or Excellon from it's editor to the current object.
  2532. :return: None
  2533. """
  2534. self.report_usage("editor2object()")
  2535. # do not update a geometry or excellon object unless it comes out of an editor
  2536. if self.call_source != 'app':
  2537. edited_obj = self.collection.get_active()
  2538. if cleanup is None:
  2539. msgbox = QtWidgets.QMessageBox()
  2540. msgbox.setText(_("Do you want to save the edited object?"))
  2541. msgbox.setWindowTitle(_("Close Editor"))
  2542. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2543. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2544. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2545. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2546. msgbox.setDefaultButton(bt_yes)
  2547. msgbox.exec_()
  2548. response = msgbox.clickedButton()
  2549. if response == bt_yes:
  2550. # clean the Tools Tab
  2551. self.ui.tool_scroll_area.takeWidget()
  2552. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2553. self.ui.notebook.setTabText(2, "Tool")
  2554. if isinstance(edited_obj, FlatCAMGeometry):
  2555. obj_type = "Geometry"
  2556. if cleanup is None:
  2557. self.geo_editor.update_fcgeometry(edited_obj)
  2558. self.geo_editor.update_options(edited_obj)
  2559. self.geo_editor.deactivate()
  2560. # update the geo object options so it is including the bounding box values
  2561. try:
  2562. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2563. edited_obj.options['xmin'] = xmin
  2564. edited_obj.options['ymin'] = ymin
  2565. edited_obj.options['xmax'] = xmax
  2566. edited_obj.options['ymax'] = ymax
  2567. except AttributeError as e:
  2568. self.inform.emit('[WARNING] %s' %
  2569. _("Object empty after edit."))
  2570. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2571. elif isinstance(edited_obj, FlatCAMGerber):
  2572. obj_type = "Gerber"
  2573. if cleanup is None:
  2574. self.grb_editor.update_fcgerber()
  2575. self.grb_editor.update_options(edited_obj)
  2576. self.grb_editor.deactivate_grb_editor()
  2577. # delete the old object (the source object) if it was an empty one
  2578. if len(edited_obj.solid_geometry) == 0:
  2579. old_name = edited_obj.options['name']
  2580. self.collection.set_active(old_name)
  2581. self.collection.delete_active()
  2582. elif isinstance(edited_obj, FlatCAMExcellon):
  2583. obj_type = "Excellon"
  2584. if cleanup is None:
  2585. self.exc_editor.update_fcexcellon(edited_obj)
  2586. self.exc_editor.update_options(edited_obj)
  2587. self.exc_editor.deactivate()
  2588. else:
  2589. self.inform.emit('[WARNING_NOTCL] %s' %
  2590. _("Select a Gerber, Geometry or Excellon Object to update."))
  2591. return
  2592. self.inform.emit('[selected] %s %s' %
  2593. (obj_type, _("is updated, returning to App...")))
  2594. elif response == bt_no:
  2595. # clean the Tools Tab
  2596. self.ui.tool_scroll_area.takeWidget()
  2597. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2598. self.ui.notebook.setTabText(2, "Tool")
  2599. if isinstance(edited_obj, FlatCAMGeometry):
  2600. self.geo_editor.deactivate()
  2601. elif isinstance(edited_obj, FlatCAMGerber):
  2602. self.grb_editor.deactivate_grb_editor()
  2603. elif isinstance(edited_obj, FlatCAMExcellon):
  2604. self.exc_editor.deactivate()
  2605. # set focus on the project tab
  2606. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  2607. else:
  2608. self.inform.emit('[WARNING_NOTCL] %s' %
  2609. _("Select a Gerber, Geometry or Excellon Object to update."))
  2610. return
  2611. elif response == bt_cancel:
  2612. return
  2613. else:
  2614. if isinstance(edited_obj, FlatCAMGeometry):
  2615. self.geo_editor.deactivate()
  2616. elif isinstance(edited_obj, FlatCAMGerber):
  2617. self.grb_editor.deactivate_grb_editor()
  2618. elif isinstance(edited_obj, FlatCAMExcellon):
  2619. self.exc_editor.deactivate()
  2620. else:
  2621. self.inform.emit('[WARNING_NOTCL] %s' %
  2622. _("Select a Gerber, Geometry or Excellon Object to update."))
  2623. return
  2624. # if notebook is hidden we show it
  2625. if self.ui.splitter.sizes()[0] == 0:
  2626. self.ui.splitter.setSizes([1, 1])
  2627. # restore the call_source to app
  2628. self.call_source = 'app'
  2629. edited_obj.plot()
  2630. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2631. self.ui.plot_tab_area.protectTab(0)
  2632. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2633. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2634. self.ui.project_frame.setDisabled(False)
  2635. def get_last_folder(self):
  2636. """
  2637. Get the folder path from where the last file was opened.
  2638. :return: String, last opened folder path
  2639. """
  2640. return self.defaults["global_last_folder"]
  2641. def get_last_save_folder(self):
  2642. """
  2643. Get the folder path from where the last file was saved.
  2644. :return: String, last saved folder path
  2645. """
  2646. loc = self.defaults["global_last_save_folder"]
  2647. if loc is None:
  2648. loc = self.defaults["global_last_folder"]
  2649. if loc is None:
  2650. loc = os.path.dirname(__file__)
  2651. return loc
  2652. def report_usage(self, resource):
  2653. """
  2654. Increments usage counter for the given resource
  2655. in self.defaults['global_stats'].
  2656. :param resource: Name of the resource.
  2657. :return: None
  2658. """
  2659. if resource in self.defaults['global_stats']:
  2660. self.defaults['global_stats'][resource] += 1
  2661. else:
  2662. self.defaults['global_stats'][resource] = 1
  2663. def init_tcl(self):
  2664. """
  2665. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2666. :return: None
  2667. """
  2668. if hasattr(self, 'tcl'):
  2669. # self.tcl = None
  2670. # TODO we need to clean non default variables and procedures here
  2671. # new object cannot be used here as it will not remember values created for next passes,
  2672. # because tcl was execudted in old instance of TCL
  2673. pass
  2674. else:
  2675. self.tcl = tk.Tcl()
  2676. self.setup_shell()
  2677. self.log.debug("TCL Shell has been initialized.")
  2678. # TODO: This shouldn't be here.
  2679. class TclErrorException(Exception):
  2680. """
  2681. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2682. """
  2683. pass
  2684. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2685. """
  2686. Shows a message on the FlatCAM Shell
  2687. :param msg: Message to display.
  2688. :param show: Opens the shell.
  2689. :param error: Shows the message as an error.
  2690. :param warning: Shows the message as an warning.
  2691. :param success: Shows the message as an success.
  2692. :param selected: Indicate that something was selected on canvas
  2693. :return: None
  2694. """
  2695. if show:
  2696. self.ui.shell_dock.show()
  2697. try:
  2698. if error:
  2699. self.shell.append_error(msg + "\n")
  2700. elif warning:
  2701. self.shell.append_warning(msg + "\n")
  2702. elif success:
  2703. self.shell.append_success(msg + "\n")
  2704. elif selected:
  2705. self.shell.append_selected(msg + "\n")
  2706. else:
  2707. self.shell.append_output(msg + "\n")
  2708. except AttributeError:
  2709. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2710. def raise_tcl_unknown_error(self, unknownException):
  2711. """
  2712. Raise exception if is different type than TclErrorException
  2713. this is here mainly to show unknown errors inside TCL shell console.
  2714. :param unknownException:
  2715. :return:
  2716. """
  2717. if not isinstance(unknownException, self.TclErrorException):
  2718. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2719. else:
  2720. raise unknownException
  2721. def display_tcl_error(self, error, error_info=None):
  2722. """
  2723. Escape bracket [ with '\' otherwise there is error
  2724. "ERROR: missing close-bracket" instead of real error
  2725. :param error: it may be text or exception
  2726. :param error_info: Some informations about the error
  2727. :return: None
  2728. """
  2729. if isinstance(error, Exception):
  2730. exc_type, exc_value, exc_traceback = error_info
  2731. if not isinstance(error, self.TclErrorException):
  2732. show_trace = 1
  2733. else:
  2734. show_trace = int(self.defaults['global_verbose_error_level'])
  2735. if show_trace > 0:
  2736. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2737. trc_formated = []
  2738. for a in reversed(trc):
  2739. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2740. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2741. else:
  2742. text = "%s" % error
  2743. else:
  2744. text = error
  2745. text = text.replace('[', '\\[').replace('"', '\\"')
  2746. self.tcl.eval('return -code error "%s"' % text)
  2747. def raise_tcl_error(self, text):
  2748. """
  2749. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2750. :param text: text of error
  2751. :return: raise exception
  2752. """
  2753. self.display_tcl_error(text)
  2754. raise self.TclErrorException(text)
  2755. def exec_command(self, text, no_echo=False):
  2756. """
  2757. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2758. Also handles execution in separated threads
  2759. :param text: FlatCAM TclCommand with parameters
  2760. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2761. will create crashes of the _Expandable_Edit widget
  2762. :return: output if there was any
  2763. """
  2764. self.report_usage('exec_command')
  2765. result = self.exec_command_test(text, False, no_echo=no_echo)
  2766. # MS: added this method call so the geometry is updated once the TCL command is executed
  2767. # if no_plot is None:
  2768. # self.plot_all()
  2769. return result
  2770. def exec_command_test(self, text, reraise=True, no_echo=False):
  2771. """
  2772. Same as exec_command(...) with additional control over exceptions.
  2773. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2774. :param text: Input command
  2775. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2776. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2777. will create crashes of the _Expandable_Edit widget
  2778. :return: Output from the command
  2779. """
  2780. tcl_command_string = str(text)
  2781. try:
  2782. if no_echo is False:
  2783. self.shell.open_proccessing() # Disables input box.
  2784. result = self.tcl.eval(str(tcl_command_string))
  2785. if result != 'None' and no_echo is False:
  2786. self.shell.append_output(result + '\n')
  2787. except tk.TclError as e:
  2788. # This will display more precise answer if something in TCL shell fails
  2789. result = self.tcl.eval("set errorInfo")
  2790. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2791. if no_echo is False:
  2792. self.shell.append_error('ERROR: ' + result + '\n')
  2793. # Show error in console and just return or in test raise exception
  2794. if reraise:
  2795. raise e
  2796. finally:
  2797. if no_echo is False:
  2798. self.shell.close_proccessing()
  2799. pass
  2800. return result
  2801. # """
  2802. # Code below is unsused. Saved for later.
  2803. # """
  2804. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2805. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2806. # self.log.debug(parts)
  2807. # try:
  2808. # if parts[0] not in commands:
  2809. # self.shell.append_error("Unknown command\n")
  2810. # return
  2811. #
  2812. # #import inspect
  2813. # #inspect.getargspec(someMethod)
  2814. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2815. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2816. # self.shell.append_error(
  2817. # "Command %s takes %d arguments. %d given.\n" %
  2818. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2819. # )
  2820. # return
  2821. #
  2822. # cmdfcn = commands[parts[0]]["fcn"]
  2823. # cmdconv = commands[parts[0]]["converters"]
  2824. # if len(parts) - 1 > 0:
  2825. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2826. # else:
  2827. # retval = cmdfcn()
  2828. # retfcn = commands[parts[0]]["retfcn"]
  2829. # if retval and retfcn(retval):
  2830. # self.shell.append_output(retfcn(retval) + "\n")
  2831. #
  2832. # except Exception as e:
  2833. # #self.shell.append_error(''.join(traceback.format_exc()))
  2834. # #self.shell.append_error("?\n")
  2835. # self.shell.append_error(str(e) + "\n")
  2836. def info(self, msg):
  2837. """
  2838. Informs the user. Normally on the status bar, optionally
  2839. also on the shell.
  2840. :param msg: Text to write.
  2841. :return: None
  2842. """
  2843. # Type of message in brackets at the beginning of the message.
  2844. match = re.search("\[([^\]]+)\](.*)", msg)
  2845. if match:
  2846. level = match.group(1)
  2847. msg_ = match.group(2)
  2848. self.ui.fcinfo.set_status(str(msg_), level=level)
  2849. if level.lower() == "error":
  2850. self.shell_message(msg, error=True, show=True)
  2851. elif level.lower() == "warning":
  2852. self.shell_message(msg, warning=True, show=True)
  2853. elif level.lower() == "error_notcl":
  2854. self.shell_message(msg, error=True, show=False)
  2855. elif level.lower() == "warning_notcl":
  2856. self.shell_message(msg, warning=True, show=False)
  2857. elif level.lower() == "success":
  2858. self.shell_message(msg, success=True, show=False)
  2859. elif level.lower() == "selected":
  2860. self.shell_message(msg, selected=True, show=False)
  2861. else:
  2862. self.shell_message(msg, show=False)
  2863. else:
  2864. self.ui.fcinfo.set_status(str(msg), level="info")
  2865. # make sure that if the message is to clear the infobar with a space
  2866. # is not printed over and over on the shell
  2867. if msg != '':
  2868. self.shell_message(msg)
  2869. def restore_toolbar_view(self):
  2870. """
  2871. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  2872. was saved in the defaults dictionary.
  2873. :return: None
  2874. """
  2875. tb = self.defaults["global_toolbar_view"]
  2876. if tb & 1:
  2877. self.ui.toolbarfile.setVisible(True)
  2878. else:
  2879. self.ui.toolbarfile.setVisible(False)
  2880. if tb & 2:
  2881. self.ui.toolbargeo.setVisible(True)
  2882. else:
  2883. self.ui.toolbargeo.setVisible(False)
  2884. if tb & 4:
  2885. self.ui.toolbarview.setVisible(True)
  2886. else:
  2887. self.ui.toolbarview.setVisible(False)
  2888. if tb & 8:
  2889. self.ui.toolbartools.setVisible(True)
  2890. else:
  2891. self.ui.toolbartools.setVisible(False)
  2892. if tb & 16:
  2893. self.ui.exc_edit_toolbar.setVisible(True)
  2894. else:
  2895. self.ui.exc_edit_toolbar.setVisible(False)
  2896. if tb & 32:
  2897. self.ui.geo_edit_toolbar.setVisible(True)
  2898. else:
  2899. self.ui.geo_edit_toolbar.setVisible(False)
  2900. if tb & 64:
  2901. self.ui.grb_edit_toolbar.setVisible(True)
  2902. else:
  2903. self.ui.grb_edit_toolbar.setVisible(False)
  2904. if tb & 128:
  2905. self.ui.snap_toolbar.setVisible(True)
  2906. else:
  2907. self.ui.snap_toolbar.setVisible(False)
  2908. if tb & 256:
  2909. self.ui.toolbarshell.setVisible(True)
  2910. else:
  2911. self.ui.toolbarshell.setVisible(False)
  2912. def load_defaults(self, filename):
  2913. """
  2914. Loads the aplication's default settings from current_defaults.FlatConfig into
  2915. ``self.defaults``.
  2916. :return: None
  2917. """
  2918. try:
  2919. f = open(self.data_path + "/" + filename + ".FlatConfig")
  2920. options = f.read()
  2921. f.close()
  2922. except IOError:
  2923. self.log.error("Could not load defaults file.")
  2924. self.inform.emit('[ERROR] %s' %
  2925. _("Could not load defaults file."))
  2926. # in case the defaults file can't be loaded, show all toolbars
  2927. self.defaults["global_toolbar_view"] = 511
  2928. return
  2929. try:
  2930. defaults = json.loads(options)
  2931. except:
  2932. # in case the defaults file can't be loaded, show all toolbars
  2933. self.defaults["global_toolbar_view"] = 511
  2934. e = sys.exc_info()[0]
  2935. App.log.error(str(e))
  2936. self.inform.emit('[ERROR] %s' %
  2937. _("Failed to parse defaults file."))
  2938. return
  2939. self.defaults.update(defaults)
  2940. log.debug("FlatCAM defaults loaded from: %s" % filename)
  2941. # restore the toolbar view
  2942. self.restore_toolbar_view()
  2943. def on_import_preferences(self):
  2944. """
  2945. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  2946. ``self.defaults``.
  2947. :return: None
  2948. """
  2949. self.report_usage("on_import_preferences")
  2950. App.log.debug("on_import_preferences()")
  2951. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2952. try:
  2953. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2954. directory=self.data_path,
  2955. filter=filter_)
  2956. except TypeError:
  2957. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2958. filter=filter_)
  2959. filename = str(filename)
  2960. if filename == "":
  2961. self.inform.emit('[WARNING_NOTCL] %s' %
  2962. _("FlatCAM preferences import cancelled."))
  2963. else:
  2964. try:
  2965. f = open(filename)
  2966. options = f.read()
  2967. f.close()
  2968. except IOError:
  2969. self.log.error("Could not load defaults file.")
  2970. self.inform.emit('[ERROR_NOTCL] %s' %
  2971. _("Could not load defaults file."))
  2972. return
  2973. try:
  2974. defaults_from_file = json.loads(options)
  2975. except Exception as e:
  2976. e = sys.exc_info()[0]
  2977. App.log.error(str(e))
  2978. self.inform.emit('[ERROR_NOTCL] %s' %
  2979. _("Failed to parse defaults file."))
  2980. return
  2981. self.defaults.update(defaults_from_file)
  2982. self.on_preferences_edited()
  2983. self.inform.emit('[success] %s: %s' %
  2984. (_("Imported Defaults from"), filename))
  2985. def on_export_preferences(self):
  2986. """
  2987. Save the defaults dictionary to a file.
  2988. :return: None
  2989. """
  2990. self.report_usage("on_export_preferences")
  2991. App.log.debug("on_export_preferences()")
  2992. defaults_file_content = None
  2993. self.date = str(datetime.today()).rpartition('.')[0]
  2994. self.date = ''.join(c for c in self.date if c not in ':-')
  2995. self.date = self.date.replace(' ', '_')
  2996. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  2997. try:
  2998. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  2999. caption=_("Export FlatCAM Preferences"),
  3000. directory=self.data_path + '/preferences_' + self.date,
  3001. filter=filter__
  3002. )
  3003. except TypeError:
  3004. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  3005. filter=filter__)
  3006. filename = str(filename)
  3007. defaults_from_file = {}
  3008. if filename == "":
  3009. self.inform.emit('[WARNING_NOTCL] %s' %
  3010. _("FlatCAM preferences export cancelled."))
  3011. return
  3012. else:
  3013. try:
  3014. f = open(filename, 'w')
  3015. defaults_file_content = f.read()
  3016. f.close()
  3017. except PermissionError:
  3018. self.inform.emit('[WARNING] %s' %
  3019. _("Permission denied, saving not possible.\n"
  3020. "Most likely another app is holding the file open and not accessible."))
  3021. return
  3022. except IOError:
  3023. App.log.debug('Creating a new preferences file ...')
  3024. f = open(filename, 'w')
  3025. json.dump({}, f)
  3026. f.close()
  3027. except:
  3028. e = sys.exc_info()[0]
  3029. App.log.error("Could not load defaults file.")
  3030. App.log.error(str(e))
  3031. self.inform.emit('[ERROR_NOTCL] %s' %
  3032. _("Could not load preferences file."))
  3033. return
  3034. try:
  3035. defaults_from_file = json.loads(defaults_file_content)
  3036. except:
  3037. App.log.warning("Trying to read an empty Preferences file. Continue.")
  3038. # Update options
  3039. self.defaults_read_form()
  3040. defaults_from_file.update(self.defaults)
  3041. self.propagate_defaults(silent=True)
  3042. # Save update options
  3043. try:
  3044. f = open(filename, "w")
  3045. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  3046. f.close()
  3047. except:
  3048. self.inform.emit('[ERROR_NOTCL] %s' %
  3049. _("Failed to write defaults to file."))
  3050. return
  3051. if self.defaults["global_open_style"] is False:
  3052. self.file_opened.emit("preferences", filename)
  3053. self.file_saved.emit("preferences", filename)
  3054. self.inform.emit('[success] %s: %s' %
  3055. (_("Exported preferences to"), filename))
  3056. def on_preferences_open_folder(self):
  3057. """
  3058. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  3059. :return: None
  3060. """
  3061. self.report_usage("on_preferences_open_folder()")
  3062. if sys.platform == 'win32':
  3063. subprocess.Popen('explorer %s' % self.data_path)
  3064. elif sys.platform == 'darwin':
  3065. os.system('open "%s"' % self.data_path)
  3066. else:
  3067. subprocess.Popen(['xdg-open', self.data_path])
  3068. self.inform.emit('[success] %s' %
  3069. _("FlatCAM Preferences Folder opened."))
  3070. def save_geometry(self, x, y, width, height, notebook_width):
  3071. """
  3072. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  3073. launch of the application.
  3074. :param x: X position of the main window
  3075. :param y: Y position of the main window
  3076. :param width: width of the main window
  3077. :param height: height of the main window
  3078. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  3079. :return: None
  3080. """
  3081. self.defaults["global_def_win_x"] = x
  3082. self.defaults["global_def_win_y"] = y
  3083. self.defaults["global_def_win_w"] = width
  3084. self.defaults["global_def_win_h"] = height
  3085. self.defaults["global_def_notebook_width"] = notebook_width
  3086. self.save_defaults()
  3087. def message_dialog(self, title, message, kind="info"):
  3088. """
  3089. Builds and show a custom QMessageBox to be used in FlatCAM.
  3090. :param title: title of the QMessageBox
  3091. :param message: message to be displayed
  3092. :param kind: type of QMessageBox; will display a specific icon.
  3093. :return:
  3094. """
  3095. icon = {"info": QtWidgets.QMessageBox.Information,
  3096. "warning": QtWidgets.QMessageBox.Warning,
  3097. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3098. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  3099. dlg.setText(message)
  3100. dlg.exec_()
  3101. def register_recent(self, kind, filename):
  3102. """
  3103. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  3104. dictionary.
  3105. :param kind: type of file that was opened
  3106. :param filename: the path and file name for the file that was opened
  3107. :return:
  3108. """
  3109. self.log.debug("register_recent()")
  3110. self.log.debug(" %s" % kind)
  3111. self.log.debug(" %s" % filename)
  3112. record = {'kind': str(kind), 'filename': str(filename)}
  3113. if record in self.recent:
  3114. return
  3115. if record in self.recent_projects:
  3116. return
  3117. if record['kind'] == 'project':
  3118. self.recent_projects.insert(0, record)
  3119. else:
  3120. self.recent.insert(0, record)
  3121. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3122. self.recent.pop()
  3123. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3124. self.recent_projects.pop()
  3125. try:
  3126. f = open(self.data_path + '/recent.json', 'w')
  3127. except IOError:
  3128. App.log.error("Failed to open recent items file for writing.")
  3129. self.inform.emit('[ERROR_NOTCL] %s' %
  3130. _('Failed to open recent files file for writing.'))
  3131. return
  3132. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3133. f.close()
  3134. try:
  3135. fp = open(self.data_path + '/recent_projects.json', 'w')
  3136. except IOError:
  3137. App.log.error("Failed to open recent items file for writing.")
  3138. self.inform.emit('[ERROR_NOTCL] %s' %
  3139. _('Failed to open recent projects file for writing.'))
  3140. return
  3141. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3142. fp.close()
  3143. # Re-build the recent items menu
  3144. self.setup_recent_items()
  3145. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3146. """
  3147. Creates a new specialized FlatCAMObj and attaches it to the application,
  3148. this is, updates the GUI accordingly, any other records and plots it.
  3149. This method is thread-safe.
  3150. Notes:
  3151. * If the name is in use, the self.collection will modify it
  3152. when appending it to the collection. There is no need to handle
  3153. name conflicts here.
  3154. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3155. :type kind: str
  3156. :param name: Name for the object.
  3157. :type name: str
  3158. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3159. The function is called with 2 parameters: the new object and the App instance.
  3160. :type initialize: function
  3161. :param active:
  3162. :param fit:
  3163. :param plot: If to plot the resulting object
  3164. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3165. self.colleaction
  3166. :return: None
  3167. :rtype: None
  3168. """
  3169. App.log.debug("new_object()")
  3170. obj_plot = plot
  3171. obj_autoselected = autoselected
  3172. t0 = time.time() # Debug
  3173. # ## Create object
  3174. classdict = {
  3175. "gerber": FlatCAMGerber,
  3176. "excellon": FlatCAMExcellon,
  3177. "cncjob": FlatCAMCNCjob,
  3178. "geometry": FlatCAMGeometry
  3179. }
  3180. App.log.debug("Calling object constructor...")
  3181. obj = classdict[kind](name)
  3182. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3183. # Set options from "Project options" form
  3184. self.options_read_form()
  3185. # IMPORTANT
  3186. # The key names in defaults and options dictionary's are not random:
  3187. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3188. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  3189. # the options from project options form into the self.options. After that, below, depending on the type of
  3190. # object that is created, it will strip the name of the object and the underline (if the original key was
  3191. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3192. # "toolchange"
  3193. for option in self.options:
  3194. if option.find(kind + "_") == 0:
  3195. oname = option[len(kind) + 1:]
  3196. obj.options[oname] = self.options[option]
  3197. obj.isHovering = False
  3198. obj.notHovering = True
  3199. # Initialize as per user request
  3200. # User must take care to implement initialize
  3201. # in a thread-safe way as is is likely that we
  3202. # have been invoked in a separate thread.
  3203. t1 = time.time()
  3204. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3205. try:
  3206. return_value = initialize(obj, self)
  3207. except Exception as e:
  3208. msg = '[ERROR_NOTCL] %s' % \
  3209. _("An internal error has ocurred. See shell.\n")
  3210. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3211. msg += traceback.format_exc()
  3212. self.inform.emit(msg)
  3213. # if str(e) == "Empty Geometry":
  3214. # self.inform.emit("[ERROR_NOTCL] )
  3215. # else:
  3216. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  3217. return "fail"
  3218. t2 = time.time()
  3219. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3220. if return_value == 'fail':
  3221. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3222. return "fail"
  3223. # Check units and convert if necessary
  3224. # This condition CAN be true because initialize() can change obj.units
  3225. if self.options["units"].upper() != obj.units.upper():
  3226. self.inform.emit('%s: %s' %
  3227. (_("Converting units to "), self.options["units"]))
  3228. obj.convert_units(self.options["units"])
  3229. t3 = time.time()
  3230. self.log.debug("%f seconds converting units." % (t3 - t2))
  3231. # Create the bounding box for the object and then add the results to the obj.options
  3232. try:
  3233. xmin, ymin, xmax, ymax = obj.bounds()
  3234. obj.options['xmin'] = xmin
  3235. obj.options['ymin'] = ymin
  3236. obj.options['xmax'] = xmax
  3237. obj.options['ymax'] = ymax
  3238. except Exception as e:
  3239. log.warning("The object has no bounds properties. %s" % str(e))
  3240. return "fail"
  3241. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3242. # Move the object to the main thread and let the app know that it is available.
  3243. obj.moveToThread(self.main_thread)
  3244. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3245. return obj
  3246. def new_excellon_object(self):
  3247. """
  3248. Creates a new, blank Excellon object.
  3249. :return: None
  3250. """
  3251. self.report_usage("new_excellon_object()")
  3252. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3253. def new_geometry_object(self):
  3254. """
  3255. Creates a new, blank and single-tool Geometry object.
  3256. :return: None
  3257. """
  3258. self.report_usage("new_geometry_object()")
  3259. def initialize(obj, self):
  3260. obj.multitool = False
  3261. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3262. def new_gerber_object(self):
  3263. """
  3264. Creates a new, blank Gerber object.
  3265. :return: None
  3266. """
  3267. self.report_usage("new_gerber_object()")
  3268. def initialize(grb_obj, self):
  3269. grb_obj.multitool = False
  3270. grb_obj.source_file = []
  3271. grb_obj.multigeo = False
  3272. grb_obj.follow = False
  3273. grb_obj.apertures = {}
  3274. grb_obj.solid_geometry = []
  3275. try:
  3276. grb_obj.options['xmin'] = 0
  3277. grb_obj.options['ymin'] = 0
  3278. grb_obj.options['xmax'] = 0
  3279. grb_obj.options['ymax'] = 0
  3280. except KeyError:
  3281. pass
  3282. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3283. def on_object_created(self, obj, plot, autoselect):
  3284. """
  3285. Event callback for object creation.
  3286. It will add the new object to the collection. After that it will plot the object in a threaded way
  3287. :param obj: The newly created FlatCAM object.
  3288. :param plot: if the newly create object t obe plotted
  3289. :param autoselect: if the newly created object to be autoselected after creation
  3290. :return: None
  3291. """
  3292. t0 = time.time() # DEBUG
  3293. self.log.debug("on_object_created()")
  3294. # The Collection might change the name if there is a collision
  3295. self.collection.append(obj)
  3296. # after adding the object to the collection always update the list of objects that are in the collection
  3297. self.all_objects_list = self.collection.get_list()
  3298. # self.inform.emit('[selected] %s created & selected: %s' %
  3299. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3300. if obj.kind == 'gerber':
  3301. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3302. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3303. elif obj.kind == 'excellon':
  3304. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3305. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3306. elif obj.kind == 'cncjob':
  3307. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3308. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3309. elif obj.kind == 'geometry':
  3310. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3311. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3312. # update the SHELL auto-completer model with the name of the new object
  3313. self.myKeywords.append(obj.options['name'])
  3314. self.shell._edit.set_model_data(self.myKeywords)
  3315. self.ui.code_editor.set_model_data(self.myKeywords)
  3316. if autoselect:
  3317. # select the just opened object but deselect the previous ones
  3318. self.collection.set_all_inactive()
  3319. self.collection.set_active(obj.options["name"])
  3320. else:
  3321. self.collection.set_all_inactive()
  3322. # here it is done the object plotting
  3323. def worker_task(t_obj):
  3324. with self.proc_container.new(_("Plotting")):
  3325. if isinstance(t_obj, FlatCAMCNCjob):
  3326. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3327. else:
  3328. t_obj.plot()
  3329. t1 = time.time() # DEBUG
  3330. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3331. self.object_plotted.emit(t_obj)
  3332. # Send to worker
  3333. # self.worker.add_task(worker_task, [self])
  3334. if plot is True:
  3335. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3336. def on_object_changed(self, obj):
  3337. """
  3338. Called whenever the geometry of the object was changed in some way.
  3339. This require the update of it's bounding values so it can be the selected on canvas.
  3340. Update the bounding box data from obj.options
  3341. :param obj: the object that was changed
  3342. :return: None
  3343. """
  3344. xmin, ymin, xmax, ymax = obj.bounds()
  3345. obj.options['xmin'] = xmin
  3346. obj.options['ymin'] = ymin
  3347. obj.options['xmax'] = xmax
  3348. obj.options['ymax'] = ymax
  3349. log.debug("Object changed, updating the bounding box data on self.options")
  3350. # delete the old selection shape
  3351. self.delete_selection_shape()
  3352. self.should_we_save = True
  3353. def on_object_plotted(self, obj):
  3354. """
  3355. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3356. :param obj: object to be fit into view
  3357. :return: None
  3358. """
  3359. self.on_zoom_fit(None)
  3360. def options_read_form(self):
  3361. """
  3362. Same as it's equivalent from the defaults.
  3363. self.options use to store the preferences per project. No longer used.
  3364. :return: None
  3365. """
  3366. for option in self.options_form_fields:
  3367. self.options[option] = self.options_form_fields[option].get_value()
  3368. def options_write_form(self):
  3369. """
  3370. Same as it's equivalent from the defaults.
  3371. self.options use to store the preferences per project. No longer used.
  3372. :return: None
  3373. """
  3374. for option in self.options:
  3375. self.options_write_form_field(option)
  3376. def options_write_form_field(self, field):
  3377. """
  3378. Same as it's equivalent from the defaults.
  3379. self.options use to store the preferences per project. No longer used.
  3380. :return: None
  3381. """
  3382. try:
  3383. self.options_form_fields[field].set_value(self.options[field])
  3384. except KeyError:
  3385. # Changed from error to debug. This allows to have data stored
  3386. # which is not user-editable.
  3387. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  3388. pass
  3389. def on_about(self):
  3390. """
  3391. Displays the "about" dialog found in the Menu --> Help.
  3392. :return: None
  3393. """
  3394. self.report_usage("on_about")
  3395. version = self.version
  3396. version_date = self.version_date
  3397. beta = self.beta
  3398. class AboutDialog(QtWidgets.QDialog):
  3399. def __init__(self, parent=None):
  3400. QtWidgets.QDialog.__init__(self, parent)
  3401. # Icon and title
  3402. self.setWindowIcon(parent.app_icon)
  3403. self.setWindowTitle(_("About FlatCAM"))
  3404. self.resize(600, 200)
  3405. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3406. # self.setStyleSheet(
  3407. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3408. # "background-attachment: fixed"
  3409. # )
  3410. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3411. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3412. # palette = QtGui.QPalette()
  3413. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3414. # self.setPalette(palette)
  3415. logo = QtWidgets.QLabel()
  3416. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3417. title = QtWidgets.QLabel(
  3418. "<font size=8><B>FlatCAM</B></font><BR>"
  3419. "{title}<BR>"
  3420. "<BR>"
  3421. "<BR>"
  3422. # "<B>{devel}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3423. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3424. # "<b>{down}</B> area &nbsp;&nbsp;&nbsp;&nbsp;"
  3425. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3426. # "<b> {issue}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3427. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3428. "<B>{issue}</B></a><BR>".format(
  3429. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3430. devel=_("Development"),
  3431. down=_("DOWNLOAD"),
  3432. issue=_("Issue tracker"))
  3433. )
  3434. title.setOpenExternalLinks(True)
  3435. closebtn = QtWidgets.QPushButton(_("Close"))
  3436. tab_widget = QtWidgets.QTabWidget()
  3437. description_label = QtWidgets.QLabel(
  3438. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3439. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3440. version=version,
  3441. beta=('BETA' if beta else ''),
  3442. date=version_date,
  3443. arch=platform.architecture()[0])
  3444. )
  3445. description_label.setOpenExternalLinks(True)
  3446. license_label = QtWidgets.QLabel(
  3447. _(
  3448. '(c) Copyright 2014 Juan Pablo Caram.\n\n'
  3449. 'Licensed under the MIT license:\n'
  3450. 'http://www.opensource.org/licenses/mit-license.php\n\n'
  3451. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3452. 'of this software and associated documentation files (the "Software"), to deal\n'
  3453. 'in the Software without restriction, including without limitation the rights\n'
  3454. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3455. 'copies of the Software, and to permit persons to whom the Software is\n'
  3456. ' furnished to do so, subject to the following conditions:\n\n'
  3457. 'The above copyright notice and this permission notice shall be included in\n'
  3458. 'all copies or substantial portions of the Software.\n\n'
  3459. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3460. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3461. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3462. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3463. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3464. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3465. 'THE SOFTWARE.'
  3466. )
  3467. )
  3468. license_label.setOpenExternalLinks(True)
  3469. # layouts
  3470. layout1 = QtWidgets.QVBoxLayout()
  3471. layout1_1 = QtWidgets.QHBoxLayout()
  3472. layout1_2 = QtWidgets.QHBoxLayout()
  3473. layout2 = QtWidgets.QHBoxLayout()
  3474. layout3 = QtWidgets.QHBoxLayout()
  3475. self.setLayout(layout1)
  3476. layout1.addLayout(layout1_1)
  3477. layout1.addLayout(layout1_2)
  3478. layout1.addLayout(layout2)
  3479. layout1.addLayout(layout3)
  3480. layout1_1.addStretch()
  3481. layout1_1.addWidget(description_label)
  3482. layout1_2.addWidget(tab_widget)
  3483. self.splash_tab = QtWidgets.QWidget()
  3484. self.splash_tab.setObjectName("splash_about")
  3485. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3486. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3487. tab_widget.addTab(self.splash_tab, _("Splash"))
  3488. self.programmmers_tab = QtWidgets.QWidget()
  3489. self.programmmers_tab.setObjectName("programmers_about")
  3490. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3491. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3492. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3493. self.translators_tab = QtWidgets.QWidget()
  3494. self.translators_tab.setObjectName("translators_about")
  3495. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3496. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3497. tab_widget.addTab(self.translators_tab, _("Translators"))
  3498. self.license_tab = QtWidgets.QWidget()
  3499. self.license_tab.setObjectName("license_about")
  3500. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3501. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3502. tab_widget.addTab(self.license_tab, _("License"))
  3503. self.splash_tab_layout.addWidget(logo, stretch=0)
  3504. self.splash_tab_layout.addWidget(title, stretch=1)
  3505. pal = QtGui.QPalette()
  3506. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3507. self.prog_form_lay = QtWidgets.QFormLayout()
  3508. self.prog_form_lay.setHorizontalSpacing(20)
  3509. prog_widget = QtWidgets.QWidget()
  3510. prog_widget.setLayout(self.prog_form_lay)
  3511. prog_scroll = QtWidgets.QScrollArea()
  3512. prog_scroll.setWidget(prog_widget)
  3513. prog_scroll.setWidgetResizable(True)
  3514. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3515. prog_scroll.setPalette(pal)
  3516. self.programmmers_tab_layout.addWidget(prog_scroll)
  3517. self.prog_form_lay.addRow(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")),
  3518. QtWidgets.QLabel('<b>%s</b>' % _("Status")))
  3519. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Juan Pablo Caram"),
  3520. QtWidgets.QLabel('%s' % _("Program Author")))
  3521. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Denis Hayrullin"))
  3522. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Kamil Sopko"))
  3523. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marius Stanciu"),
  3524. QtWidgets.QLabel('%s' % _("Maintainer >=2019")))
  3525. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3526. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Alexandru Lazar"))
  3527. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Matthieu Berthomé"))
  3528. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Evans"))
  3529. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Victor Benso"))
  3530. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3531. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Barnaby Walters"))
  3532. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"))
  3533. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lei Zheng"))
  3534. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marco A Quezada"))
  3535. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3536. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Cedric Dussud"))
  3537. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Chris Hemingway"))
  3538. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Damian Wrobel"))
  3539. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Daniel Sallin"))
  3540. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3541. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Bruno Vunderl"))
  3542. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Gonzalo Lopez"))
  3543. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jakob Staudt"))
  3544. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Smith"))
  3545. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3546. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lubos Medovarsky"))
  3547. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Steve Martina"))
  3548. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Thomas Duffin"))
  3549. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3550. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Idechix"))
  3551. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@SM"))
  3552. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@grbf"))
  3553. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Symonty"))
  3554. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@mgix"))
  3555. self.translator_grid_lay = QtWidgets.QGridLayout()
  3556. # trans_widget = QtWidgets.QWidget()
  3557. # trans_widget.setLayout(self.translator_grid_lay)
  3558. # self.translators_tab_layout.addWidget(trans_widget)
  3559. # self.translators_tab_layout.addStretch()
  3560. trans_widget = QtWidgets.QWidget()
  3561. trans_widget.setLayout(self.translator_grid_lay)
  3562. trans_scroll = QtWidgets.QScrollArea()
  3563. trans_scroll.setWidget(trans_widget)
  3564. trans_scroll.setWidgetResizable(True)
  3565. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3566. trans_scroll.setPalette(pal)
  3567. self.translators_tab_layout.addWidget(trans_scroll)
  3568. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  3569. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  3570. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3571. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Brasilian - Portuguese"), 1, 0)
  3572. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  3573. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 1, 2)
  3574. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 2, 0)
  3575. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 2, 1)
  3576. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 2)
  3577. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 3, 0)
  3578. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 3, 1)
  3579. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  3580. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 4, 0)
  3581. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 4, 1)
  3582. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 4, 2)
  3583. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 5, 0)
  3584. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 5, 1)
  3585. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 2)
  3586. self.translator_grid_lay.setColumnStretch(0, 0)
  3587. self.translators_tab_layout.addStretch()
  3588. self.license_tab_layout.addWidget(license_label)
  3589. self.license_tab_layout.addStretch()
  3590. layout3.addStretch()
  3591. layout3.addWidget(closebtn)
  3592. closebtn.clicked.connect(self.accept)
  3593. AboutDialog(self.ui).exec_()
  3594. def on_file_savedefaults(self):
  3595. """
  3596. Callback for menu item File->Save Defaults. Saves application default options
  3597. ``self.defaults`` to current_defaults.FlatConfig.
  3598. :return: None
  3599. """
  3600. self.save_defaults()
  3601. # def on_app_exit(self):
  3602. # self.report_usage("on_app_exit()")
  3603. #
  3604. # if self.collection.get_list():
  3605. # msgbox = QtWidgets.QMessageBox()
  3606. # # msgbox.setText("<B>Save changes ...</B>")
  3607. # msgbox.setText("There are files/objects opened in FlatCAM. "
  3608. # "\n"
  3609. # "Do you want to Save the project?")
  3610. # msgbox.setWindowTitle("Save changes")
  3611. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3612. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  3613. # QtWidgets.QMessageBox.Cancel)
  3614. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  3615. #
  3616. # response = msgbox.exec_()
  3617. #
  3618. # if response == QtWidgets.QMessageBox.Yes:
  3619. # self.on_file_saveprojectas(thread=False)
  3620. # elif response == QtWidgets.QMessageBox.Cancel:
  3621. # return
  3622. # self.save_defaults()
  3623. # else:
  3624. # self.save_defaults()
  3625. # log.debug("Application defaults saved ... Exit event.")
  3626. # QtWidgets.qApp.quit()
  3627. def save_defaults(self, silent=False, data_path=None):
  3628. """
  3629. Saves application default options
  3630. ``self.defaults`` to current_defaults.FlatConfig file.
  3631. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  3632. used at the next launch of the application.
  3633. :param silent: whether to display a message in status bar or not; boolean
  3634. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  3635. When the application is portable it should be a mobile location.
  3636. :return: None
  3637. """
  3638. self.report_usage("save_defaults")
  3639. if data_path is None:
  3640. data_path = self.data_path
  3641. # Read options from file
  3642. try:
  3643. f = open(data_path + "/current_defaults.FlatConfig")
  3644. defaults_file_content = f.read()
  3645. f.close()
  3646. except:
  3647. e = sys.exc_info()[0]
  3648. App.log.error("Could not load defaults file.")
  3649. App.log.error(str(e))
  3650. self.inform.emit('[ERROR_NOTCL] %s' %
  3651. _("Could not load defaults file."))
  3652. return
  3653. try:
  3654. defaults = json.loads(defaults_file_content)
  3655. except:
  3656. e = sys.exc_info()[0]
  3657. App.log.error("Failed to parse defaults file.")
  3658. App.log.error(str(e))
  3659. self.inform.emit('[ERROR_NOTCL] %s' %
  3660. _("Failed to parse defaults file."))
  3661. return
  3662. # Update options
  3663. self.defaults_read_form()
  3664. defaults.update(self.defaults)
  3665. self.propagate_defaults(silent=True)
  3666. # Save the toolbar view
  3667. tb_status = 0
  3668. if self.ui.toolbarfile.isVisible():
  3669. tb_status += 1
  3670. if self.ui.toolbargeo.isVisible():
  3671. tb_status += 2
  3672. if self.ui.toolbarview.isVisible():
  3673. tb_status += 4
  3674. if self.ui.toolbartools.isVisible():
  3675. tb_status += 8
  3676. if self.ui.exc_edit_toolbar.isVisible():
  3677. tb_status += 16
  3678. if self.ui.geo_edit_toolbar.isVisible():
  3679. tb_status += 32
  3680. if self.ui.grb_edit_toolbar.isVisible():
  3681. tb_status += 64
  3682. if self.ui.snap_toolbar.isVisible():
  3683. tb_status += 128
  3684. if self.ui.toolbarshell.isVisible():
  3685. tb_status += 256
  3686. self.defaults["global_toolbar_view"] = tb_status
  3687. # Save update options
  3688. try:
  3689. f = open(data_path + "/current_defaults.FlatConfig", "w")
  3690. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  3691. f.close()
  3692. except:
  3693. self.inform.emit('[ERROR_NOTCL] %s' %
  3694. _("Failed to write defaults to file."))
  3695. return
  3696. if not silent:
  3697. self.inform.emit('[success] %s' %
  3698. _("Preferences saved."))
  3699. def save_factory_defaults(self, silent=False, data_path=None):
  3700. """
  3701. Saves application factory default options
  3702. ``self.defaults`` to factory_defaults.FlatConfig.
  3703. It's a one time job done just after the first install.
  3704. :param silent: whether to display a message in status bar or not; boolean
  3705. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  3706. When the application is portable it should be a mobile location.
  3707. :return: None
  3708. """
  3709. self.report_usage("save_factory_defaults")
  3710. if data_path is None:
  3711. data_path = self.data_path
  3712. # Read options from file
  3713. try:
  3714. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  3715. factory_defaults_file_content = f_f_def.read()
  3716. f_f_def.close()
  3717. except:
  3718. e = sys.exc_info()[0]
  3719. App.log.error("Could not load factory defaults file.")
  3720. App.log.error(str(e))
  3721. self.inform.emit('[ERROR_NOTCL] %s' %
  3722. _("Could not load factory defaults file."))
  3723. return
  3724. try:
  3725. factory_defaults = json.loads(factory_defaults_file_content)
  3726. except:
  3727. e = sys.exc_info()[0]
  3728. App.log.error("Failed to parse factory defaults file.")
  3729. App.log.error(str(e))
  3730. self.inform.emit('[ERROR_NOTCL] %s' %
  3731. _("Failed to parse factory defaults file."))
  3732. return
  3733. # Update options
  3734. self.defaults_read_form()
  3735. factory_defaults.update(self.defaults)
  3736. self.propagate_defaults(silent=True)
  3737. # Save update options
  3738. try:
  3739. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  3740. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3741. f_f_def_s.close()
  3742. except:
  3743. self.inform.emit('[ERROR_NOTCL] %s' %
  3744. _("Failed to write factory defaults to file."))
  3745. return
  3746. if silent is False:
  3747. self.inform.emit(_("Factory defaults saved."))
  3748. def final_save(self):
  3749. """
  3750. Callback for doing a preferences save to file whenever the application is about to quit.
  3751. If the project has changes, it will ask the user to save the project.
  3752. :return: None
  3753. """
  3754. if self.save_in_progress:
  3755. self.inform.emit('[WARNING_NOTCL] %s' %
  3756. _("Application is saving the project. Please wait ..."))
  3757. return
  3758. if self.should_we_save and self.collection.get_list():
  3759. msgbox = QtWidgets.QMessageBox()
  3760. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  3761. "\n"
  3762. "Do you want to Save the project?"))
  3763. msgbox.setWindowTitle(_("Save changes"))
  3764. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3765. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  3766. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  3767. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3768. msgbox.setDefaultButton(bt_yes)
  3769. msgbox.exec_()
  3770. response = msgbox.clickedButton()
  3771. if response == bt_yes:
  3772. try:
  3773. self.trayIcon.hide()
  3774. except:
  3775. pass
  3776. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  3777. elif response == bt_no:
  3778. try:
  3779. self.trayIcon.hide()
  3780. except:
  3781. pass
  3782. self.quit_application()
  3783. elif response == bt_cancel:
  3784. return
  3785. else:
  3786. try:
  3787. self.trayIcon.hide()
  3788. except:
  3789. pass
  3790. self.quit_application()
  3791. def quit_application(self):
  3792. """
  3793. Called (as a pyslot or not) when the application is quit.
  3794. :return: None
  3795. """
  3796. self.save_defaults()
  3797. log.debug("App.final_save() --> App Defaults saved.")
  3798. # save toolbar state to file
  3799. settings = QSettings("Open Source", "FlatCAM")
  3800. settings.setValue('saved_gui_state', self.ui.saveState())
  3801. settings.setValue('maximized_gui', self.ui.isMaximized())
  3802. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  3803. settings.setValue('notebook_font_size',
  3804. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value())
  3805. settings.setValue('axis_font_size',
  3806. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value())
  3807. settings.setValue('textbox_font_size',
  3808. self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value())
  3809. settings.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  3810. # This will write the setting to the platform specific storage.
  3811. del settings
  3812. log.debug("App.final_save() --> App UI state saved.")
  3813. QtWidgets.qApp.quit()
  3814. def on_portable_checked(self, state):
  3815. """
  3816. Callback called when the checkbox in Preferences GUI is checked.
  3817. It will set the application as portable by creating the preferences and recent files in the
  3818. 'config' folder found in the FlatCAM installation folder.
  3819. :param state: boolean, the state of the checkbox when clicked/checked
  3820. :return:
  3821. """
  3822. line_no = 0
  3823. data = None
  3824. if sys.platform != 'win32':
  3825. # this won't work in Linux or MacOS
  3826. return
  3827. # test if the app was frozen and choose the path for the configuration file
  3828. if getattr(sys, "frozen", False) is True:
  3829. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  3830. else:
  3831. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  3832. config_file = current_data_path + '\\configuration.txt'
  3833. try:
  3834. with open(config_file, 'r') as f:
  3835. try:
  3836. data = f.readlines()
  3837. except Exception as e:
  3838. log.debug('App.__init__() -->%s' % str(e))
  3839. return
  3840. except FileNotFoundError:
  3841. pass
  3842. for line in data:
  3843. line = line.strip('\n')
  3844. param = str(line).rpartition('=')
  3845. if param[0] == 'portable':
  3846. break
  3847. line_no += 1
  3848. if state:
  3849. data[line_no] = 'portable=True\n'
  3850. # create the new defauults files
  3851. # create current_defaults.FlatConfig file if there is none
  3852. try:
  3853. f = open(current_data_path + '/current_defaults.FlatConfig')
  3854. f.close()
  3855. except IOError:
  3856. App.log.debug('Creating empty current_defaults.FlatConfig')
  3857. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3858. json.dump({}, f)
  3859. f.close()
  3860. # create factory_defaults.FlatConfig file if there is none
  3861. try:
  3862. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3863. f.close()
  3864. except IOError:
  3865. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3866. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3867. json.dump({}, f)
  3868. f.close()
  3869. try:
  3870. f = open(current_data_path + '/recent.json')
  3871. f.close()
  3872. except IOError:
  3873. App.log.debug('Creating empty recent.json')
  3874. f = open(current_data_path + '/recent.json', 'w')
  3875. json.dump([], f)
  3876. f.close()
  3877. try:
  3878. fp = open(current_data_path + '/recent_projects.json')
  3879. fp.close()
  3880. except IOError:
  3881. App.log.debug('Creating empty recent_projects.json')
  3882. fp = open(current_data_path + '/recent_projects.json', 'w')
  3883. json.dump([], fp)
  3884. fp.close()
  3885. # save the current defaults to the new defaults file
  3886. self.save_defaults(silent=True, data_path=current_data_path)
  3887. self.save_factory_defaults(silent=True, data_path=current_data_path)
  3888. else:
  3889. data[line_no] = 'portable=False\n'
  3890. with open(config_file, 'w') as f:
  3891. f.writelines(data)
  3892. def on_toggle_shell(self):
  3893. """
  3894. Toggle shell: if is visible close it, if it is closed then open it
  3895. :return:
  3896. """
  3897. self.report_usage("on_toggle_shell()")
  3898. if self.ui.shell_dock.isVisible():
  3899. self.ui.shell_dock.hide()
  3900. else:
  3901. self.ui.shell_dock.show()
  3902. def on_register_files(self, obj_type=None):
  3903. """
  3904. Called whenever there is a need to register file extensions with FlatCAM.
  3905. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3906. :param obj_type: the type of object to be register for.
  3907. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3908. :return: None
  3909. """
  3910. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3911. new_reg_path = 'Software\\Classes\\'
  3912. # find if the current user is admin
  3913. try:
  3914. is_admin = os.getuid() == 0
  3915. except AttributeError:
  3916. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3917. if is_admin is True:
  3918. root_path = winreg.HKEY_LOCAL_MACHINE
  3919. else:
  3920. root_path = winreg.HKEY_CURRENT_USER
  3921. # create the keys
  3922. def set_reg(name, root_path, new_reg_path, value):
  3923. try:
  3924. winreg.CreateKey(root_path, new_reg_path)
  3925. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3926. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3927. return True
  3928. except WindowsError:
  3929. return False
  3930. # delete key in registry
  3931. def delete_reg(root_path, reg_path, key_to_del):
  3932. key_to_del_path = reg_path + key_to_del
  3933. try:
  3934. winreg.DeleteKey(root_path, key_to_del_path)
  3935. return True
  3936. except WindowsError:
  3937. return False
  3938. if obj_type is None or obj_type == 'excellon':
  3939. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3940. exc_list = [x for x in exc_list if x != '']
  3941. # register all keys in the Preferences window
  3942. for ext in exc_list:
  3943. new_k = new_reg_path + '.%s' % ext
  3944. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3945. # and unregister those that are no longer in the Preferences windows but are in the file
  3946. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3947. if ext not in exc_list:
  3948. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3949. # now write the updated extensions to the self.defaults
  3950. # new_ext = ''
  3951. # for ext in exc_list:
  3952. # new_ext = new_ext + ext + ', '
  3953. # self.defaults["fa_excellon"] = new_ext
  3954. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3955. if obj_type is None or obj_type == 'gcode':
  3956. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3957. gco_list = [x for x in gco_list if x != '']
  3958. # register all keys in the Preferences window
  3959. for ext in gco_list:
  3960. new_k = new_reg_path + '.%s' % ext
  3961. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3962. # and unregister those that are no longer in the Preferences windows but are in the file
  3963. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3964. if ext not in gco_list:
  3965. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3966. # now write the updated extensions to the self.defaults
  3967. # new_ext = ''
  3968. # for ext in gco_list:
  3969. # new_ext = new_ext + ext + ', '
  3970. # self.defaults["fa_gcode"] = new_ext
  3971. self.inform.emit('[success] %s' %
  3972. _("Selected GCode file extensions registered with FlatCAM."))
  3973. if obj_type is None or obj_type == 'gerber':
  3974. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3975. grb_list = [x for x in grb_list if x != '']
  3976. # register all keys in the Preferences window
  3977. for ext in grb_list:
  3978. new_k = new_reg_path + '.%s' % ext
  3979. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3980. # and unregister those that are no longer in the Preferences windows but are in the file
  3981. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3982. if ext not in grb_list:
  3983. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3984. # now write the updated extensions to the self.defaults
  3985. # new_ext = ''
  3986. # for ext in grb_list:
  3987. # new_ext = new_ext + ext + ', '
  3988. # self.defaults["fa_gerber"] = new_ext
  3989. self.inform.emit('[success] %s' %
  3990. _("Selected Gerber file extensions registered with FlatCAM."))
  3991. def add_extension(self, ext_type):
  3992. if ext_type == 'excellon':
  3993. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3994. if new_ext == '':
  3995. return
  3996. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3997. if new_ext in old_val:
  3998. return
  3999. old_val.append(new_ext)
  4000. old_val.sort()
  4001. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4002. if ext_type == 'gcode':
  4003. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4004. if new_ext == '':
  4005. return
  4006. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4007. if new_ext in old_val:
  4008. return
  4009. old_val.append(new_ext)
  4010. old_val.sort()
  4011. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4012. if ext_type == 'gerber':
  4013. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4014. if new_ext == '':
  4015. return
  4016. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4017. if new_ext in old_val:
  4018. return
  4019. old_val.append(new_ext)
  4020. old_val.sort()
  4021. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4022. if ext_type == 'keyword':
  4023. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4024. if new_kw == '':
  4025. return
  4026. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4027. if new_kw in old_val:
  4028. return
  4029. old_val.append(new_kw)
  4030. old_val.sort()
  4031. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4032. # update the self.myKeywords so the model is updated
  4033. self.autocomplete_kw_list = \
  4034. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4035. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4036. self.shell._edit.set_model_data(self.myKeywords)
  4037. self.ui.code_editor.set_model_data(self.myKeywords)
  4038. def del_extension(self, ext_type):
  4039. if ext_type == 'excellon':
  4040. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4041. if new_ext == '':
  4042. return
  4043. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4044. if new_ext not in old_val:
  4045. return
  4046. old_val.remove(new_ext)
  4047. old_val.sort()
  4048. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4049. if ext_type == 'gcode':
  4050. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4051. if new_ext == '':
  4052. return
  4053. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4054. if new_ext not in old_val:
  4055. return
  4056. old_val.remove(new_ext)
  4057. old_val.sort()
  4058. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4059. if ext_type == 'gerber':
  4060. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4061. if new_ext == '':
  4062. return
  4063. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4064. if new_ext not in old_val:
  4065. return
  4066. old_val.remove(new_ext)
  4067. old_val.sort()
  4068. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4069. if ext_type == 'keyword':
  4070. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4071. if new_kw == '':
  4072. return
  4073. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4074. if new_kw not in old_val:
  4075. return
  4076. old_val.remove(new_kw)
  4077. old_val.sort()
  4078. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4079. # update the self.myKeywords so the model is updated
  4080. self.autocomplete_kw_list = \
  4081. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4082. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4083. self.shell._edit.set_model_data(self.myKeywords)
  4084. self.ui.code_editor.set_model_data(self.myKeywords)
  4085. def restore_extensions(self, ext_type):
  4086. if ext_type == 'excellon':
  4087. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  4088. # for the ability to open Excellon files with .txt extension
  4089. new_exc_list = deepcopy(self.exc_list)
  4090. try:
  4091. new_exc_list.remove('txt')
  4092. except ValueError:
  4093. pass
  4094. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  4095. if ext_type == 'gcode':
  4096. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  4097. if ext_type == 'gerber':
  4098. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  4099. if ext_type == 'keyword':
  4100. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  4101. # update the self.myKeywords so the model is updated
  4102. self.autocomplete_kw_list = self.default_keywords
  4103. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4104. self.shell._edit.set_model_data(self.myKeywords)
  4105. self.ui.code_editor.set_model_data(self.myKeywords)
  4106. def delete_all_extensions(self, ext_type):
  4107. if ext_type == 'excellon':
  4108. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4109. if ext_type == 'gcode':
  4110. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4111. if ext_type == 'gerber':
  4112. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4113. if ext_type == 'keyword':
  4114. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4115. # update the self.myKeywords so the model is updated
  4116. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4117. self.shell._edit.set_model_data(self.myKeywords)
  4118. self.ui.code_editor.set_model_data(self.myKeywords)
  4119. def on_edit_join(self, name=None):
  4120. """
  4121. Callback for Edit->Join. Joins the selected geometry objects into
  4122. a new one.
  4123. :return: None
  4124. """
  4125. self.report_usage("on_edit_join()")
  4126. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4127. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4128. tooldias = []
  4129. geo_type_list = set()
  4130. objs = self.collection.get_selected()
  4131. if len(objs) < 2:
  4132. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4133. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4134. return 'fail'
  4135. for obj in objs:
  4136. geo_type_list.add(obj.multigeo)
  4137. # if len(geo_type_list) == 1 means that all list elements are the same
  4138. if len(geo_type_list) != 1:
  4139. self.inform.emit('[ERROR] %s' %
  4140. _("Failed join. The Geometry objects are of different types.\n"
  4141. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4142. "convert from one to another and retry joining \n"
  4143. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4144. "the result may not be what was expected. \n"
  4145. "Check the generated GCODE."))
  4146. return
  4147. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4148. if True in geo_type_list:
  4149. def initialize(obj, app):
  4150. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=True)
  4151. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4152. for v in obj.tools.values():
  4153. v['data']['name'] = obj_name_multi
  4154. self.new_object("geometry", obj_name_multi, initialize)
  4155. else:
  4156. def initialize(obj, app):
  4157. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=False)
  4158. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4159. for v in obj.tools.values():
  4160. v['data']['name'] = obj_name_single
  4161. self.new_object("geometry", obj_name_single, initialize)
  4162. self.should_we_save = True
  4163. def on_edit_join_exc(self):
  4164. """
  4165. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4166. a new Excellon.
  4167. :return: None
  4168. """
  4169. self.report_usage("on_edit_join_exc()")
  4170. objs = self.collection.get_selected()
  4171. for obj in objs:
  4172. if not isinstance(obj, FlatCAMExcellon):
  4173. self.inform.emit('[ERROR_NOTCL] %s' %
  4174. _("Failed. Excellon joining works only on Excellon objects."))
  4175. return
  4176. if len(objs) < 2:
  4177. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4178. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4179. return 'fail'
  4180. def initialize(obj, app):
  4181. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=obj)
  4182. self.new_object("excellon", 'Combo_Excellon', initialize)
  4183. self.should_we_save = True
  4184. def on_edit_join_grb(self):
  4185. """
  4186. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4187. a new Gerber object.
  4188. :return: None
  4189. """
  4190. self.report_usage("on_edit_join_grb()")
  4191. objs = self.collection.get_selected()
  4192. for obj in objs:
  4193. if not isinstance(obj, FlatCAMGerber):
  4194. self.inform.emit('[ERROR_NOTCL] %s' %
  4195. _("Failed. Gerber joining works only on Gerber objects."))
  4196. return
  4197. if len(objs) < 2:
  4198. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4199. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4200. return 'fail'
  4201. def initialize(obj, app):
  4202. FlatCAMGerber.merge(self, grb_list=objs, grb_final=obj)
  4203. self.new_object("gerber", 'Combo_Gerber', initialize)
  4204. self.should_we_save = True
  4205. def on_convert_singlegeo_to_multigeo(self):
  4206. """
  4207. Called for converting a Geometry object from single-geo to multi-geo.
  4208. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4209. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4210. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4211. the solid-geometry of that tool.
  4212. :return: None
  4213. """
  4214. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4215. obj = self.collection.get_active()
  4216. if obj is None:
  4217. self.inform.emit('[ERROR_NOTCL] %s' %
  4218. _("Failed. Select a Geometry Object and try again."))
  4219. return
  4220. if not isinstance(obj, FlatCAMGeometry):
  4221. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4222. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4223. return
  4224. obj.multigeo = True
  4225. for tooluid, dict_value in obj.tools.items():
  4226. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4227. if not isinstance(obj.solid_geometry, list):
  4228. obj.solid_geometry = [obj.solid_geometry]
  4229. obj.solid_geometry[:] = []
  4230. obj.plot()
  4231. self.should_we_save = True
  4232. self.inform.emit('[success] %s' %
  4233. _("A Geometry object was converted to MultiGeo type."))
  4234. def on_convert_multigeo_to_singlegeo(self):
  4235. """
  4236. Called for converting a Geometry object from multi-geo to single-geo.
  4237. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4238. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4239. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4240. the solid-geometry of that tool.
  4241. :return: None
  4242. """
  4243. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4244. obj = self.collection.get_active()
  4245. if obj is None:
  4246. self.inform.emit('[ERROR_NOTCL] %s' %
  4247. _("Failed. Select a Geometry Object and try again."))
  4248. return
  4249. if not isinstance(obj, FlatCAMGeometry):
  4250. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4251. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4252. return
  4253. obj.multigeo = False
  4254. total_solid_geometry = []
  4255. for tooluid, dict_value in obj.tools.items():
  4256. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4257. # clear the original geometry
  4258. dict_value['solid_geometry'][:] = []
  4259. obj.solid_geometry = deepcopy(total_solid_geometry)
  4260. obj.plot()
  4261. self.should_we_save = True
  4262. self.inform.emit('[success] %s' %
  4263. _("A Geometry object was converted to SingleGeo type."))
  4264. def on_options_dict_change(self, field):
  4265. """
  4266. Called whenever a key changed in the self.options dictionary. This dict was used to store the preferences of the
  4267. current project. This feature is no longer used.
  4268. :param field:
  4269. :return:
  4270. """
  4271. self.options_write_form_field(field)
  4272. if field == "units":
  4273. self.set_screen_units(self.options['units'])
  4274. def on_defaults_dict_change(self, field):
  4275. """
  4276. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4277. Edit -> Preferences tab window.
  4278. :param field: the key of the self.defaults dictionary that was changed.
  4279. :return: None
  4280. """
  4281. self.defaults_write_form_field(field)
  4282. if field == "units":
  4283. self.set_screen_units(self.defaults['units'])
  4284. def set_screen_units(self, units):
  4285. """
  4286. Set the FlatCAM units on the status bar.
  4287. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4288. :return: None
  4289. """
  4290. self.ui.units_label.setText("[" + units.lower() + "]")
  4291. def on_toggle_units(self, no_pref=False):
  4292. """
  4293. Callback for the Units radio-button change in the Preferences tab.
  4294. Changes the application's default units adn for the project too.
  4295. If changing the project's units, the change propagates to all of
  4296. the objects in the project.
  4297. :return: None
  4298. """
  4299. self.report_usage("on_toggle_units")
  4300. if self.toggle_units_ignore:
  4301. return
  4302. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4303. # If option is the same, then ignore
  4304. if new_units == self.defaults["units"].upper():
  4305. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4306. return
  4307. # Options to scale
  4308. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  4309. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  4310. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4311. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  4312. "excellon_z_pdepth",
  4313. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4314. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4315. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  4316. "geometry_feedrate_probe",
  4317. 'cncjob_tooldia',
  4318. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4319. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia"
  4320. "tools_2sided_drilldia", "tools_film_boundary",
  4321. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4322. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4323. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4324. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4325. "tools_transform_offset_y",
  4326. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4327. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4328. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4329. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4330. 'global_gridx', 'global_gridy', 'global_snap_max']
  4331. def scale_options(sfactor):
  4332. for dim in dimensions:
  4333. if dim == 'excellon_toolchangexy':
  4334. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4335. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4336. coords_xy[0] *= sfactor
  4337. coords_xy[1] *= sfactor
  4338. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4339. elif dim == 'geometry_toolchangexy':
  4340. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4341. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4342. coords_xy[0] *= sfactor
  4343. coords_xy[1] *= sfactor
  4344. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4345. elif dim == 'geometry_cnctooldia':
  4346. tools_diameters = []
  4347. try:
  4348. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4349. tools_diameters = [eval(a) for a in tools_string if a != '']
  4350. except Exception as e:
  4351. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4352. self.options['geometry_cnctooldia'] = ''
  4353. for t in range(len(tools_diameters)):
  4354. tools_diameters[t] *= sfactor
  4355. self.options['geometry_cnctooldia'] += "%f," % tools_diameters[t]
  4356. elif dim == 'tools_ncctools':
  4357. ncctools = []
  4358. try:
  4359. tools_string = self.defaults["tools_ncctools"].split(",")
  4360. ncctools = [eval(a) for a in tools_string if a != '']
  4361. except Exception as e:
  4362. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4363. self.options['tools_ncctools'] = ''
  4364. for t in range(len(ncctools)):
  4365. ncctools[t] *= sfactor
  4366. self.options['tools_ncctools'] += "%f," % ncctools[t]
  4367. elif dim == 'tools_solderpaste_tools':
  4368. sptools = []
  4369. try:
  4370. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4371. sptools = [eval(a) for a in tools_string if a != '']
  4372. except Exception as e:
  4373. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4374. self.options['tools_solderpaste_tools'] = ""
  4375. for t in range(len(sptools)):
  4376. sptools[t] *= sfactor
  4377. self.options['tools_solderpaste_tools'] += "%f," % sptools[t]
  4378. elif dim == 'tools_solderpaste_xy_toolchange':
  4379. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4380. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4381. sp_coords[0] *= sfactor
  4382. sp_coords[1] *= sfactor
  4383. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  4384. elif dim == 'global_gridx' or dim == 'global_gridy':
  4385. if new_units == 'IN':
  4386. val = 0.1
  4387. try:
  4388. val = float(self.defaults[dim]) * sfactor
  4389. except Exception as e:
  4390. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4391. self.options[dim] = float('%.6f' % val)
  4392. else:
  4393. val = 0.1
  4394. try:
  4395. val = float(self.defaults[dim]) * sfactor
  4396. except Exception as e:
  4397. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4398. self.options[dim] = float('%.4f' % val)
  4399. else:
  4400. val = 0.1
  4401. try:
  4402. val = float(self.options[dim]) * sfactor
  4403. except Exception as e:
  4404. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  4405. self.options[dim] = val
  4406. def scale_defaults(sfactor):
  4407. for dim in dimensions:
  4408. if dim == 'excellon_toolchangexy':
  4409. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4410. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4411. coords_xy[0] *= sfactor
  4412. coords_xy[1] *= sfactor
  4413. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4414. elif dim == 'geometry_toolchangexy':
  4415. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4416. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4417. coords_xy[0] *= sfactor
  4418. coords_xy[1] *= sfactor
  4419. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4420. elif dim == 'geometry_cnctooldia':
  4421. tools_diameters = []
  4422. try:
  4423. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4424. tools_diameters = [eval(a) for a in tools_string if a != '']
  4425. except Exception as e:
  4426. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4427. self.defaults['geometry_cnctooldia'] = ''
  4428. for t in range(len(tools_diameters)):
  4429. tools_diameters[t] *= sfactor
  4430. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  4431. elif dim == 'tools_ncctools':
  4432. ncctools = []
  4433. try:
  4434. tools_string = self.defaults["tools_ncctools"].split(",")
  4435. ncctools = [eval(a) for a in tools_string if a != '']
  4436. except Exception as e:
  4437. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4438. self.defaults['tools_ncctools'] = ''
  4439. for t in range(len(ncctools)):
  4440. ncctools[t] *= sfactor
  4441. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  4442. elif dim == 'tools_solderpaste_tools':
  4443. sptools = []
  4444. try:
  4445. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4446. sptools = [eval(a) for a in tools_string if a != '']
  4447. except Exception as e:
  4448. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4449. self.defaults['tools_solderpaste_tools'] = ""
  4450. for t in range(len(sptools)):
  4451. sptools[t] *= sfactor
  4452. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  4453. elif dim == 'tools_solderpaste_xy_toolchange':
  4454. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4455. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4456. sp_coords[0] *= sfactor
  4457. sp_coords[1] *= sfactor
  4458. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  4459. elif dim == 'global_gridx' or dim == 'global_gridy':
  4460. if new_units == 'IN':
  4461. val = 0.1
  4462. try:
  4463. val = float(self.defaults[dim]) * sfactor
  4464. except Exception as e:
  4465. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4466. self.defaults[dim] = float('%.6f' % val)
  4467. else:
  4468. val = 0.1
  4469. try:
  4470. val = float(self.defaults[dim]) * sfactor
  4471. except Exception as e:
  4472. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4473. self.defaults[dim] = float('%.4f' % val)
  4474. else:
  4475. val = 0.1
  4476. try:
  4477. val = float(self.defaults[dim]) * sfactor
  4478. except Exception as e:
  4479. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4480. self.defaults[dim] = val
  4481. # The scaling factor depending on choice of units.
  4482. factor = 1/25.4
  4483. if new_units == 'MM':
  4484. factor = 25.4
  4485. # Changing project units. Warn user.
  4486. msgbox = QtWidgets.QMessageBox()
  4487. msgbox.setWindowTitle(_("Toggle Units"))
  4488. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  4489. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4490. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  4491. "properties of all objects to be scaled accordingly.\nContinue?"))
  4492. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4493. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4494. msgbox.setDefaultButton(bt_ok)
  4495. msgbox.exec_()
  4496. response = msgbox.clickedButton()
  4497. if response == bt_ok:
  4498. if no_pref is False:
  4499. self.options_read_form()
  4500. scale_options(factor)
  4501. self.options_write_form()
  4502. self.defaults_read_form()
  4503. scale_defaults(factor)
  4504. self.defaults_write_form(fl_units=new_units)
  4505. # save the defaults to file, some may assume that the conversion is enough and it's not
  4506. self.on_save_button()
  4507. self.should_we_save = True
  4508. # change this only if the workspace is active
  4509. if self.defaults['global_workspace'] is True:
  4510. self.plotcanvas.draw_workspace()
  4511. # adjust the grid values on the main toolbar
  4512. dec = 6 if new_units == 'IN'else 4
  4513. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  4514. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  4515. if not self.ui.grid_gap_link_cb.isChecked():
  4516. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  4517. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  4518. for obj in self.collection.get_list():
  4519. obj.convert_units(new_units)
  4520. # make that the properties stored in the object are also updated
  4521. self.object_changed.emit(obj)
  4522. obj.build_ui()
  4523. current = self.collection.get_active()
  4524. if current is not None:
  4525. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4526. if not isinstance(current, FlatCAMGeometry):
  4527. current.to_form()
  4528. self.plot_all()
  4529. self.inform.emit('[success] %s: %s' %
  4530. (_("Converted units to"), new_units))
  4531. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4532. self.set_screen_units(new_units)
  4533. else:
  4534. # Undo toggling
  4535. self.toggle_units_ignore = True
  4536. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4537. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4538. else:
  4539. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4540. self.toggle_units_ignore = False
  4541. self.inform.emit('[WARNING_NOTCL]%s' %
  4542. _(" Units conversion cancelled."))
  4543. self.options_read_form()
  4544. self.defaults_read_form()
  4545. def on_toggle_units_click(self):
  4546. try:
  4547. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4548. except (TypeError, AttributeError):
  4549. pass
  4550. if self.defaults["units"] == 'MM':
  4551. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4552. else:
  4553. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4554. self.on_toggle_units(no_pref=True)
  4555. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4556. lambda: self.on_toggle_units(no_pref=False))
  4557. def on_fullscreen(self):
  4558. self.report_usage("on_fullscreen()")
  4559. if self.toggle_fscreen is False:
  4560. if sys.platform == 'win32':
  4561. self.ui.showFullScreen()
  4562. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4563. tb.setVisible(False)
  4564. self.ui.splitter_left.setVisible(False)
  4565. self.toggle_fscreen = True
  4566. else:
  4567. if sys.platform == 'win32':
  4568. self.ui.showNormal()
  4569. self.restore_toolbar_view()
  4570. self.ui.splitter_left.setVisible(True)
  4571. self.toggle_fscreen = False
  4572. def on_toggle_plotarea(self):
  4573. self.report_usage("on_toggle_plotarea()")
  4574. try:
  4575. name = self.ui.plot_tab_area.widget(0).objectName()
  4576. except AttributeError:
  4577. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4578. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4579. self.ui.plot_tab_area.protectTab(0)
  4580. return
  4581. if name != 'plotarea':
  4582. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4583. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4584. self.ui.plot_tab_area.protectTab(0)
  4585. else:
  4586. self.ui.plot_tab_area.closeTab(0)
  4587. def on_toggle_notebook(self):
  4588. if self.ui.splitter.sizes()[0] == 0:
  4589. self.ui.splitter.setSizes([1, 1])
  4590. else:
  4591. self.ui.splitter.setSizes([0, 1])
  4592. def on_toggle_axis(self):
  4593. self.report_usage("on_toggle_axis()")
  4594. if self.toggle_axis is False:
  4595. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4596. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4597. self.plotcanvas.redraw()
  4598. self.toggle_axis = True
  4599. else:
  4600. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4601. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4602. self.plotcanvas.redraw()
  4603. self.toggle_axis = False
  4604. def on_toggle_grid(self):
  4605. self.report_usage("on_toggle_grid()")
  4606. self.ui.grid_snap_btn.trigger()
  4607. def on_options_combo_change(self, sel):
  4608. """
  4609. Called when the combo box to choose between application defaults and
  4610. project option changes value. The corresponding variables are
  4611. copied to the UI.
  4612. :param sel: The option index that was chosen.
  4613. :return: None
  4614. """
  4615. # combo_sel = self.ui.notebook.combo_options.get_active()
  4616. App.log.debug("Options --> %s" % sel)
  4617. # form = [self.defaults_form, self.options_form][sel]
  4618. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  4619. if sel == 0:
  4620. self.gen_form = self.ui.general_defaults_form
  4621. self.ger_form = self.ui.gerber_defaults_form
  4622. self.exc_form = self.ui.excellon_defaults_form
  4623. self.geo_form = self.ui.geometry_defaults_form
  4624. self.cnc_form = self.ui.cncjob_defaults_form
  4625. self.tools_form = self.ui.tools_defaults_form
  4626. self.fa_form = self.ui.util_defaults_form
  4627. elif sel == 1:
  4628. self.gen_form = self.ui.general_options_form
  4629. self.ger_form = self.ui.gerber_options_form
  4630. self.exc_form = self.ui.excellon_options_form
  4631. self.geo_form = self.ui.geometry_options_form
  4632. self.cnc_form = self.ui.cncjob_options_form
  4633. self.tools_form = self.ui.tools_options_form
  4634. self.fa_form = self.ui.util_options_form
  4635. else:
  4636. return
  4637. try:
  4638. self.ui.general_scroll_area.takeWidget()
  4639. except:
  4640. self.log.debug("Nothing to remove")
  4641. self.ui.general_scroll_area.setWidget(self.gen_form)
  4642. self.gen_form.show()
  4643. try:
  4644. self.ui.gerber_scroll_area.takeWidget()
  4645. except:
  4646. self.log.debug("Nothing to remove")
  4647. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  4648. self.ger_form.show()
  4649. try:
  4650. self.ui.excellon_scroll_area.takeWidget()
  4651. except:
  4652. self.log.debug("Nothing to remove")
  4653. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  4654. self.exc_form.show()
  4655. try:
  4656. self.ui.geometry_scroll_area.takeWidget()
  4657. except:
  4658. self.log.debug("Nothing to remove")
  4659. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  4660. self.geo_form.show()
  4661. try:
  4662. self.ui.cncjob_scroll_area.takeWidget()
  4663. except:
  4664. self.log.debug("Nothing to remove")
  4665. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  4666. self.cnc_form.show()
  4667. try:
  4668. self.ui.tools_scroll_area.takeWidget()
  4669. except:
  4670. self.log.debug("Nothing to remove")
  4671. self.ui.tools_scroll_area.setWidget(self.tools_form)
  4672. self.tools_form.show()
  4673. try:
  4674. self.ui.fa_scroll_area.takeWidget()
  4675. except:
  4676. self.log.debug("Nothing to remove")
  4677. self.ui.fa_scroll_area.setWidget(self.fa_form)
  4678. self.fa_form.show()
  4679. self.log.debug("Finished GUI form initialization.")
  4680. # self.options2form()
  4681. def on_excellon_defaults_button(self):
  4682. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  4683. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  4684. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  4685. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  4686. self.defaults_form_fields["excellon_zeros"].set_value('L')
  4687. self.defaults_form_fields["excellon_units"].set_value('INCH')
  4688. log.debug("Excellon app defaults loaded ...")
  4689. def on_excellon_options_button(self):
  4690. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  4691. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  4692. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  4693. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  4694. self.options_form_fields["excellon_zeros"].set_value('L')
  4695. self.options_form_fields["excellon_units"].set_value('INCH')
  4696. log.debug("Excellon options defaults loaded ...")
  4697. def on_update_exc_export(self, state):
  4698. """
  4699. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  4700. if the update_excellon_cb checkbox is checked
  4701. :param state: state of the checkbox whose signals is tied to his slot
  4702. :return:
  4703. """
  4704. if state:
  4705. # first try to disconnect
  4706. try:
  4707. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.\
  4708. disconnect(self.on_excellon_format_changed)
  4709. except TypeError:
  4710. pass
  4711. try:
  4712. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged.\
  4713. disconnect(self.on_excellon_format_changed)
  4714. except TypeError:
  4715. pass
  4716. try:
  4717. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged.\
  4718. disconnect(self.on_excellon_format_changed)
  4719. except TypeError:
  4720. pass
  4721. try:
  4722. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged.\
  4723. disconnect(self.on_excellon_format_changed)
  4724. except TypeError:
  4725. pass
  4726. try:
  4727. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  4728. disconnect(self.on_excellon_zeros_changed)
  4729. except TypeError:
  4730. pass
  4731. try:
  4732. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  4733. disconnect(self.on_excellon_zeros_changed)
  4734. except TypeError:
  4735. pass
  4736. # the connect them
  4737. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.connect(
  4738. self.on_excellon_format_changed)
  4739. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged.connect(
  4740. self.on_excellon_format_changed)
  4741. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged.connect(
  4742. self.on_excellon_format_changed)
  4743. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged.connect(
  4744. self.on_excellon_format_changed)
  4745. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  4746. self.on_excellon_zeros_changed)
  4747. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  4748. self.on_excellon_units_changed)
  4749. else:
  4750. # disconnect the signals
  4751. try:
  4752. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged. \
  4753. disconnect(self.on_excellon_format_changed)
  4754. except TypeError:
  4755. pass
  4756. try:
  4757. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged. \
  4758. disconnect(self.on_excellon_format_changed)
  4759. except TypeError:
  4760. pass
  4761. try:
  4762. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged. \
  4763. disconnect(self.on_excellon_format_changed)
  4764. except TypeError:
  4765. pass
  4766. try:
  4767. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged. \
  4768. disconnect(self.on_excellon_format_changed)
  4769. except TypeError:
  4770. pass
  4771. try:
  4772. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  4773. disconnect(self.on_excellon_zeros_changed)
  4774. except TypeError:
  4775. pass
  4776. try:
  4777. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  4778. disconnect(self.on_excellon_zeros_changed)
  4779. except TypeError:
  4780. pass
  4781. def on_excellon_format_changed(self):
  4782. """
  4783. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  4784. :return: None
  4785. """
  4786. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  4787. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4788. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  4789. )
  4790. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4791. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  4792. )
  4793. else:
  4794. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4795. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  4796. )
  4797. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4798. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  4799. )
  4800. def on_excellon_zeros_changed(self):
  4801. """
  4802. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  4803. :return: None
  4804. """
  4805. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  4806. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  4807. )
  4808. def on_excellon_units_changed(self):
  4809. """
  4810. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  4811. :return: None
  4812. """
  4813. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  4814. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  4815. )
  4816. self.on_excellon_format_changed()
  4817. # Setting plot colors handlers
  4818. def on_pf_color_entry(self):
  4819. self.defaults['global_plot_fill'] = \
  4820. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  4821. self.defaults['global_plot_fill'][7:9]
  4822. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4823. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  4824. def on_pf_color_button(self):
  4825. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  4826. c_dialog = QtWidgets.QColorDialog()
  4827. plot_fill_color = c_dialog.getColor(initial=current_color)
  4828. if plot_fill_color.isValid() is False:
  4829. return
  4830. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4831. "background-color:%s" % str(plot_fill_color.name()))
  4832. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  4833. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  4834. self.defaults['global_plot_fill'] = new_val
  4835. def on_pf_color_spinner(self):
  4836. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  4837. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  4838. self.defaults['global_plot_fill'] = \
  4839. self.defaults['global_plot_fill'][:7] + \
  4840. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4841. self.defaults['global_plot_line'] = \
  4842. self.defaults['global_plot_line'][:7] + \
  4843. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4844. def on_pf_color_slider(self):
  4845. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  4846. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  4847. def on_pl_color_entry(self):
  4848. self.defaults['global_plot_line'] = \
  4849. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  4850. self.defaults['global_plot_line'][7:9]
  4851. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4852. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  4853. def on_pl_color_button(self):
  4854. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  4855. # print(current_color)
  4856. c_dialog = QtWidgets.QColorDialog()
  4857. plot_line_color = c_dialog.getColor(initial=current_color)
  4858. if plot_line_color.isValid() is False:
  4859. return
  4860. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4861. "background-color:%s" % str(plot_line_color.name()))
  4862. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  4863. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  4864. self.defaults['global_plot_line'] = new_val_line
  4865. # Setting selection colors (left - right) handlers
  4866. def on_sf_color_entry(self):
  4867. self.defaults['global_sel_fill'] = \
  4868. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  4869. self.defaults['global_sel_fill'][7:9]
  4870. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4871. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  4872. def on_sf_color_button(self):
  4873. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  4874. c_dialog = QtWidgets.QColorDialog()
  4875. plot_fill_color = c_dialog.getColor(initial=current_color)
  4876. if plot_fill_color.isValid() is False:
  4877. return
  4878. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4879. "background-color:%s" % str(plot_fill_color.name()))
  4880. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  4881. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  4882. self.defaults['global_sel_fill'] = new_val
  4883. def on_sf_color_spinner(self):
  4884. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  4885. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  4886. self.defaults['global_sel_fill'] = \
  4887. self.defaults['global_sel_fill'][:7] + \
  4888. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4889. self.defaults['global_sel_line'] = \
  4890. self.defaults['global_sel_line'][:7] + \
  4891. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4892. def on_sf_color_slider(self):
  4893. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  4894. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  4895. def on_sl_color_entry(self):
  4896. self.defaults['global_sel_line'] = \
  4897. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  4898. self.defaults['global_sel_line'][7:9]
  4899. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4900. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  4901. def on_sl_color_button(self):
  4902. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  4903. c_dialog = QtWidgets.QColorDialog()
  4904. plot_line_color = c_dialog.getColor(initial=current_color)
  4905. if plot_line_color.isValid() is False:
  4906. return
  4907. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4908. "background-color:%s" % str(plot_line_color.name()))
  4909. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  4910. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  4911. self.defaults['global_sel_line'] = new_val_line
  4912. # Setting selection colors (right - left) handlers
  4913. def on_alt_sf_color_entry(self):
  4914. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  4915. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  4916. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4917. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  4918. def on_alt_sf_color_button(self):
  4919. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  4920. c_dialog = QtWidgets.QColorDialog()
  4921. plot_fill_color = c_dialog.getColor(initial=current_color)
  4922. if plot_fill_color.isValid() is False:
  4923. return
  4924. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4925. "background-color:%s" % str(plot_fill_color.name()))
  4926. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  4927. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  4928. self.defaults['global_alt_sel_fill'] = new_val
  4929. def on_alt_sf_color_spinner(self):
  4930. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  4931. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  4932. self.defaults['global_alt_sel_fill'] = \
  4933. self.defaults['global_alt_sel_fill'][:7] + \
  4934. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4935. self.defaults['global_alt_sel_line'] = \
  4936. self.defaults['global_alt_sel_line'][:7] + \
  4937. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4938. def on_alt_sf_color_slider(self):
  4939. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  4940. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  4941. def on_alt_sl_color_entry(self):
  4942. self.defaults['global_alt_sel_line'] = \
  4943. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  4944. self.defaults['global_alt_sel_line'][7:9]
  4945. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  4946. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  4947. def on_alt_sl_color_button(self):
  4948. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  4949. c_dialog = QtWidgets.QColorDialog()
  4950. plot_line_color = c_dialog.getColor(initial=current_color)
  4951. if plot_line_color.isValid() is False:
  4952. return
  4953. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  4954. "background-color:%s" % str(plot_line_color.name()))
  4955. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  4956. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  4957. self.defaults['global_alt_sel_line'] = new_val_line
  4958. # Setting Editor colors
  4959. def on_draw_color_entry(self):
  4960. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  4961. .draw_color_entry.get_value()
  4962. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  4963. "background-color:%s" % str(self.defaults['global_draw_color']))
  4964. def on_draw_color_button(self):
  4965. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  4966. c_dialog = QtWidgets.QColorDialog()
  4967. draw_color = c_dialog.getColor(initial=current_color)
  4968. if draw_color.isValid() is False:
  4969. return
  4970. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  4971. "background-color:%s" % str(draw_color.name()))
  4972. new_val = str(draw_color.name())
  4973. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  4974. self.defaults['global_draw_color'] = new_val
  4975. def on_sel_draw_color_entry(self):
  4976. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  4977. .sel_draw_color_entry.get_value()
  4978. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  4979. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  4980. def on_sel_draw_color_button(self):
  4981. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  4982. c_dialog = QtWidgets.QColorDialog()
  4983. sel_draw_color = c_dialog.getColor(initial=current_color)
  4984. if sel_draw_color.isValid() is False:
  4985. return
  4986. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  4987. "background-color:%s" % str(sel_draw_color.name()))
  4988. new_val_sel = str(sel_draw_color.name())
  4989. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  4990. self.defaults['global_sel_draw_color'] = new_val_sel
  4991. def on_proj_color_entry(self):
  4992. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  4993. .proj_color_entry.get_value()
  4994. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  4995. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  4996. def on_proj_color_button(self):
  4997. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  4998. c_dialog = QtWidgets.QColorDialog()
  4999. proj_color = c_dialog.getColor(initial=current_color)
  5000. if proj_color.isValid() is False:
  5001. return
  5002. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5003. "background-color:%s" % str(proj_color.name()))
  5004. new_val_sel = str(proj_color.name())
  5005. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  5006. self.defaults['global_proj_item_color'] = new_val_sel
  5007. def on_proj_color_dis_entry(self):
  5008. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  5009. .proj_color_dis_entry.get_value()
  5010. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5011. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  5012. def on_proj_color_dis_button(self):
  5013. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  5014. c_dialog = QtWidgets.QColorDialog()
  5015. proj_color = c_dialog.getColor(initial=current_color)
  5016. if proj_color.isValid() is False:
  5017. return
  5018. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5019. "background-color:%s" % str(proj_color.name()))
  5020. new_val_sel = str(proj_color.name())
  5021. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  5022. self.defaults['global_proj_item_dis_color'] = new_val_sel
  5023. def on_annotation_fontcolor_entry(self):
  5024. self.defaults['cncjob_annotation_fontcolor'] = \
  5025. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.get_value()
  5026. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5027. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  5028. def on_annotation_fontcolor_button(self):
  5029. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  5030. c_dialog = QtWidgets.QColorDialog()
  5031. annotation_color = c_dialog.getColor(initial=current_color)
  5032. if annotation_color.isValid() is False:
  5033. return
  5034. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5035. "background-color:%s" % str(annotation_color.name()))
  5036. new_val_sel = str(annotation_color.name())
  5037. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(new_val_sel)
  5038. self.defaults['cncjob_annotation_fontcolor'] = new_val_sel
  5039. def on_film_color_entry(self):
  5040. self.defaults['tools_film_color'] = \
  5041. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  5042. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5043. "background-color:%s" % str(self.defaults['tools_film_color']))
  5044. def on_film_color_button(self):
  5045. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  5046. c_dialog = QtWidgets.QColorDialog()
  5047. film_color = c_dialog.getColor(initial=current_color)
  5048. if film_color.isValid() is False:
  5049. return
  5050. # if new color is different then mark that the Preferences are changed
  5051. if film_color != current_color:
  5052. self.on_preferences_edited()
  5053. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5054. "background-color:%s" % str(film_color.name()))
  5055. new_val_sel = str(film_color.name())
  5056. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  5057. self.defaults['tools_film_color'] = new_val_sel
  5058. def on_splash_changed(self, state):
  5059. settings = QSettings("Open Source", "FlatCAM")
  5060. settings.setValue('splash_screen', 1) if state else settings.setValue('splash_screen', 0)
  5061. # This will write the setting to the platform specific storage.
  5062. del settings
  5063. def on_notebook_tab_rmb_click(self, checked):
  5064. self.ui.notebook.set_detachable(val=checked)
  5065. self.defaults["global_tabs_detachable"] = checked
  5066. self.ui.plot_tab_area.set_detachable(val=checked)
  5067. self.defaults["global_tabs_detachable"] = checked
  5068. def on_deselect_all(self):
  5069. self.collection.set_all_inactive()
  5070. self.delete_selection_shape()
  5071. def on_workspace_modified(self):
  5072. self.save_defaults(silent=True)
  5073. self.plotcanvas.draw_workspace()
  5074. def on_workspace(self):
  5075. self.report_usage("on_workspace()")
  5076. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5077. self.plotcanvas.restore_workspace()
  5078. else:
  5079. self.plotcanvas.delete_workspace()
  5080. self.save_defaults(silent=True)
  5081. def on_workspace_menu(self):
  5082. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5083. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  5084. else:
  5085. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  5086. self.on_workspace()
  5087. def on_layout(self, index=None, lay=None):
  5088. self.report_usage("on_layout()")
  5089. if lay:
  5090. current_layout = lay
  5091. else:
  5092. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  5093. settings = QSettings("Open Source", "FlatCAM")
  5094. settings.setValue('layout', current_layout)
  5095. # This will write the setting to the platform specific storage.
  5096. del settings
  5097. # first remove the toolbars:
  5098. try:
  5099. self.ui.removeToolBar(self.ui.toolbarfile)
  5100. self.ui.removeToolBar(self.ui.toolbargeo)
  5101. self.ui.removeToolBar(self.ui.toolbarview)
  5102. self.ui.removeToolBar(self.ui.toolbarshell)
  5103. self.ui.removeToolBar(self.ui.toolbartools)
  5104. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  5105. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  5106. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  5107. self.ui.removeToolBar(self.ui.snap_toolbar)
  5108. self.ui.removeToolBar(self.ui.toolbarshell)
  5109. except Exception as e:
  5110. pass
  5111. if current_layout == 'standard':
  5112. # ## TOOLBAR INSTALLATION # ##
  5113. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5114. self.ui.toolbarfile.setObjectName('File_TB')
  5115. self.ui.addToolBar(self.ui.toolbarfile)
  5116. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5117. self.ui.toolbargeo.setObjectName('Edit_TB')
  5118. self.ui.addToolBar(self.ui.toolbargeo)
  5119. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5120. self.ui.toolbarview.setObjectName('View_TB')
  5121. self.ui.addToolBar(self.ui.toolbarview)
  5122. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5123. self.ui.toolbarshell.setObjectName('Shell_TB')
  5124. self.ui.addToolBar(self.ui.toolbarshell)
  5125. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5126. self.ui.toolbartools.setObjectName('Tools_TB')
  5127. self.ui.addToolBar(self.ui.toolbartools)
  5128. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5129. # self.ui.exc_edit_toolbar.setVisible(False)
  5130. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5131. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  5132. self.ui.addToolBarBreak()
  5133. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5134. # self.ui.geo_edit_toolbar.setVisible(False)
  5135. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5136. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  5137. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5138. # self.ui.grb_edit_toolbar.setVisible(False)
  5139. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5140. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  5141. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5142. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5143. # self.ui.snap_toolbar.setMaximumHeight(30)
  5144. self.ui.addToolBar(self.ui.snap_toolbar)
  5145. self.ui.corner_snap_btn.setVisible(False)
  5146. self.ui.snap_magnet.setVisible(False)
  5147. elif current_layout == 'compact':
  5148. # ## TOOLBAR INSTALLATION # ##
  5149. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5150. self.ui.toolbarfile.setObjectName('File_TB')
  5151. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  5152. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5153. self.ui.toolbargeo.setObjectName('Edit_TB')
  5154. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  5155. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5156. self.ui.toolbarshell.setObjectName('Shell_TB')
  5157. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  5158. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5159. self.ui.toolbartools.setObjectName('Tools_TB')
  5160. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  5161. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5162. # self.ui.geo_edit_toolbar.setVisible(False)
  5163. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5164. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  5165. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5166. self.ui.toolbarview.setObjectName('View_TB')
  5167. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  5168. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  5169. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5170. # self.ui.grb_edit_toolbar.setVisible(False)
  5171. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5172. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  5173. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5174. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5175. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  5176. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5177. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5178. self.ui.snap_toolbar.setMaximumHeight(30)
  5179. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  5180. self.ui.corner_snap_btn.setVisible(True)
  5181. self.ui.snap_magnet.setVisible(True)
  5182. # add all the actions to the toolbars
  5183. self.ui.populate_toolbars()
  5184. # reconnect all the signals to the toolbar actions
  5185. self.connect_toolbar_signals()
  5186. self.ui.grid_snap_btn.setChecked(True)
  5187. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  5188. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  5189. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  5190. self.ui.grid_gap_link_cb.setChecked(True)
  5191. def on_cnc_custom_parameters(self, signal_text):
  5192. if signal_text == 'Parameters':
  5193. return
  5194. else:
  5195. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  5196. def on_save_button(self):
  5197. log.debug("App.on_save_button() --> Saving preferences to file.")
  5198. self.preferences_changed_flag = False
  5199. self.save_defaults(silent=False)
  5200. # load the defaults so they are updated into the app
  5201. self.load_defaults(filename='current_defaults')
  5202. # Re-fresh project options
  5203. self.on_options_app2project()
  5204. settings = QSettings("Open Source", "FlatCAM")
  5205. # save the notebook font size
  5206. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  5207. settings.setValue('notebook_font_size', fsize)
  5208. # save the axis font size
  5209. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  5210. settings.setValue('axis_font_size', g_fsize)
  5211. # save the textbox font size
  5212. tb_fsize = self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  5213. settings.setValue('textbox_font_size', tb_fsize)
  5214. # This will write the setting to the platform specific storage.
  5215. del settings
  5216. def handlePrint(self):
  5217. self.report_usage("handlePrint()")
  5218. dialog = QtPrintSupport.QPrintDialog()
  5219. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  5220. self.ui.code_editor.document().print_(dialog.printer())
  5221. def handlePreview(self):
  5222. self.report_usage("handlePreview()")
  5223. dialog = QtPrintSupport.QPrintPreviewDialog()
  5224. dialog.paintRequested.connect(self.ui.code_editor.print_)
  5225. dialog.exec_()
  5226. def handleTextChanged(self):
  5227. # enable = not self.ui.code_editor.document().isEmpty()
  5228. # self.ui.buttonPrint.setEnabled(enable)
  5229. # self.ui.buttonPreview.setEnabled(enable)
  5230. pass
  5231. def handleOpen(self, filt=None):
  5232. self.report_usage("handleOpen()")
  5233. if filt:
  5234. _filter_ = filt
  5235. else:
  5236. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  5237. "All Files (*.*)"
  5238. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  5239. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  5240. if path:
  5241. file = QtCore.QFile(path)
  5242. if file.open(QtCore.QIODevice.ReadOnly):
  5243. stream = QtCore.QTextStream(file)
  5244. self.gcode_edited = stream.readAll()
  5245. self.ui.code_editor.setPlainText(self.gcode_edited)
  5246. file.close()
  5247. def handleSaveGCode(self, name=None, filt=None):
  5248. self.report_usage("handleSaveGCode()")
  5249. if filt:
  5250. _filter_ = filt
  5251. else:
  5252. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  5253. "All Files (*.*)"
  5254. if name:
  5255. obj_name = name
  5256. else:
  5257. try:
  5258. obj_name = self.collection.get_active().options['name']
  5259. except AttributeError:
  5260. obj_name = 'file'
  5261. if filt is None:
  5262. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  5263. try:
  5264. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  5265. caption=_("Export G-Code ..."),
  5266. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  5267. filter=_filter_
  5268. )[0])
  5269. except TypeError:
  5270. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  5271. if filename == "":
  5272. self.inform.emit('[WARNING_NOTCL] %s' %
  5273. _("Export Code cancelled."))
  5274. return
  5275. else:
  5276. try:
  5277. my_gcode = self.ui.code_editor.toPlainText()
  5278. with open(filename, 'w') as f:
  5279. for line in my_gcode:
  5280. f.write(line)
  5281. except FileNotFoundError:
  5282. self.inform.emit('[WARNING] %s' %
  5283. _("No such file or directory"))
  5284. return
  5285. except PermissionError:
  5286. self.inform.emit('[WARNING] %s' %
  5287. _("Permission denied, saving not possible.\n"
  5288. "Most likely another app is holding the file open and not accessible."))
  5289. return
  5290. # Just for adding it to the recent files list.
  5291. if self.defaults["global_open_style"] is False:
  5292. self.file_opened.emit("cncjob", filename)
  5293. self.file_saved.emit("cncjob", filename)
  5294. self.inform.emit('%s: %s' % (_("Saved to"), str(filename)))
  5295. def handleFindGCode(self):
  5296. self.report_usage("handleFindGCode()")
  5297. flags = QtGui.QTextDocument.FindCaseSensitively
  5298. text_to_be_found = self.ui.entryFind.get_value()
  5299. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  5300. if r is False:
  5301. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5302. def handleReplaceGCode(self):
  5303. self.report_usage("handleReplaceGCode()")
  5304. old = self.ui.entryFind.get_value()
  5305. new = self.ui.entryReplace.get_value()
  5306. if self.ui.sel_all_cb.isChecked():
  5307. while True:
  5308. cursor = self.ui.code_editor.textCursor()
  5309. cursor.beginEditBlock()
  5310. flags = QtGui.QTextDocument.FindCaseSensitively
  5311. # self.ui.editor is the QPlainTextEdit
  5312. r = self.ui.code_editor.find(str(old), flags)
  5313. if r:
  5314. qc = self.ui.code_editor.textCursor()
  5315. if qc.hasSelection():
  5316. qc.insertText(new)
  5317. else:
  5318. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5319. break
  5320. # Mark end of undo block
  5321. cursor.endEditBlock()
  5322. else:
  5323. cursor = self.ui.code_editor.textCursor()
  5324. cursor.beginEditBlock()
  5325. qc = self.ui.code_editor.textCursor()
  5326. if qc.hasSelection():
  5327. qc.insertText(new)
  5328. # Mark end of undo block
  5329. cursor.endEditBlock()
  5330. def handleRunCode(self):
  5331. # trying to run a Tcl command without having the Shell open will create some warnings because the Tcl Shell
  5332. # tries to print on a hidden widget, therefore show the dock if hidden
  5333. if self.ui.shell_dock.isHidden():
  5334. self.ui.shell_dock.show()
  5335. self.script_code = deepcopy(self.ui.code_editor.toPlainText())
  5336. # self.shell._sysShell.exec_command(script_code)
  5337. old_line = ''
  5338. for tcl_command_line in self.script_code.splitlines():
  5339. # do not process lines starting with '#' = comment and empty lines
  5340. if not tcl_command_line.startswith('#') and tcl_command_line != '':
  5341. # id FlatCAM is run in Windows then replace all the slashes with
  5342. # the UNIX style slash that TCL understands
  5343. if sys.platform == 'win32':
  5344. if "open" in tcl_command_line:
  5345. tcl_command_line = tcl_command_line.replace('\\', '/')
  5346. if old_line != '':
  5347. new_command = old_line + tcl_command_line + '\n'
  5348. else:
  5349. new_command = tcl_command_line
  5350. # execute the actual Tcl command
  5351. try:
  5352. self.shell.open_proccessing() # Disables input box.
  5353. result = self.tcl.eval(str(new_command))
  5354. if result != 'None':
  5355. self.shell.append_output(result + '\n')
  5356. old_line = ''
  5357. except tk.TclError:
  5358. old_line = old_line + tcl_command_line + '\n'
  5359. except Exception as e:
  5360. log.debug("App.handleRunCode() --> %s" % str(e))
  5361. if old_line != '':
  5362. # it means that the script finished with an error
  5363. result = self.tcl.eval("set errorInfo")
  5364. self.log.error("Exec command Exception: %s" % (result + '\n'))
  5365. self.shell.append_error('ERROR: ' + result + '\n')
  5366. self.shell.close_proccessing()
  5367. def on_tool_add_keypress(self):
  5368. # ## Current application units in Upper Case
  5369. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5370. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5371. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5372. if notebook_widget_name == 'selected_tab':
  5373. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5374. # Tool add works for Geometry only if Advanced is True in Preferences
  5375. if self.defaults["global_app_level"] == 'a':
  5376. tool_add_popup = FCInputDialog(title="New Tool ...",
  5377. text='Enter a Tool Diameter:',
  5378. min=0.0000, max=99.9999, decimals=4)
  5379. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5380. val, ok = tool_add_popup.get_value()
  5381. if ok:
  5382. if float(val) == 0:
  5383. self.inform.emit('[WARNING_NOTCL] %s' %
  5384. _("Please enter a tool diameter with non-zero value, in Float format."))
  5385. return
  5386. self.collection.get_active().on_tool_add(dia=float(val))
  5387. else:
  5388. self.inform.emit('[WARNING_NOTCL] %s...' %
  5389. _("Adding Tool cancelled"))
  5390. else:
  5391. msgbox = QtWidgets.QMessageBox()
  5392. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5393. "Go to Preferences -> General - Show Advanced Options."))
  5394. msgbox.setWindowTitle("Tool adding ...")
  5395. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  5396. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5397. msgbox.setDefaultButton(bt_ok)
  5398. msgbox.exec_()
  5399. # work only if the notebook tab on focus is the Tools_Tab
  5400. if notebook_widget_name == 'tool_tab':
  5401. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5402. tool_add_popup = FCInputDialog(title="New Tool ...",
  5403. text='Enter a Tool Diameter:',
  5404. min=0.0000, max=99.9999, decimals=4)
  5405. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5406. val, ok = tool_add_popup.get_value()
  5407. # and only if the tool is NCC Tool
  5408. if tool_widget == self.ncclear_tool.toolName:
  5409. if ok:
  5410. if float(val) == 0:
  5411. self.inform.emit('[WARNING_NOTCL] %s' %
  5412. _("Please enter a tool diameter with non-zero value, in Float format."))
  5413. return
  5414. self.ncclear_tool.on_tool_add(dia=float(val))
  5415. else:
  5416. self.inform.emit('[WARNING_NOTCL] %s...' %
  5417. _("Adding Tool cancelled"))
  5418. # and only if the tool is Paint Area Tool
  5419. elif tool_widget == self.paint_tool.toolName:
  5420. if ok:
  5421. if float(val) == 0:
  5422. self.inform.emit('[WARNING_NOTCL] %s' %
  5423. _("Please enter a tool diameter with non-zero value, in Float format."))
  5424. return
  5425. self.paint_tool.on_tool_add(dia=float(val))
  5426. else:
  5427. self.inform.emit('[WARNING_NOTCL] %s...' %
  5428. _("Adding Tool cancelled"))
  5429. # and only if the tool is Solder Paste Dispensing Tool
  5430. elif tool_widget == self.paste_tool.toolName:
  5431. if ok:
  5432. if float(val) == 0:
  5433. self.inform.emit('[WARNING_NOTCL] %s' %
  5434. _("Please enter a tool diameter with non-zero value, in Float format."))
  5435. return
  5436. self.paste_tool.on_tool_add(dia=float(val))
  5437. else:
  5438. self.inform.emit('[WARNING_NOTCL] %s...' %
  5439. _("Adding Tool cancelled"))
  5440. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5441. # See description bellow.
  5442. def on_delete_keypress(self):
  5443. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5444. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5445. if notebook_widget_name == 'selected_tab':
  5446. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5447. self.collection.get_active().on_tool_delete()
  5448. # work only if the notebook tab on focus is the Tools_Tab
  5449. elif notebook_widget_name == 'tool_tab':
  5450. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5451. # and only if the tool is NCC Tool
  5452. if tool_widget == self.ncclear_tool.toolName:
  5453. self.ncclear_tool.on_tool_delete()
  5454. # and only if the tool is Paint Tool
  5455. elif tool_widget == self.paint_tool.toolName:
  5456. self.paint_tool.on_tool_delete()
  5457. # and only if the tool is Solder Paste Dispensing Tool
  5458. elif tool_widget == self.paste_tool.toolName:
  5459. self.paste_tool.on_tool_delete()
  5460. else:
  5461. self.on_delete()
  5462. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5463. # some screens you have to be careful where you hover with your mouse.
  5464. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5465. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5466. # Complicated, I know :)
  5467. def on_delete(self):
  5468. """
  5469. Delete the currently selected FlatCAMObjs.
  5470. :return: None
  5471. """
  5472. self.report_usage("on_delete()")
  5473. response = None
  5474. bt_ok = None
  5475. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5476. # a geometry object before we update it.
  5477. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5478. and self.grb_editor.editor_active is False:
  5479. if self.defaults["global_delete_confirmation"] is True:
  5480. msgbox = QtWidgets.QMessageBox()
  5481. msgbox.setWindowTitle(_("Delete objects"))
  5482. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  5483. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5484. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5485. "the selected objects?"))
  5486. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5487. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5488. msgbox.setDefaultButton(bt_ok)
  5489. msgbox.exec_()
  5490. response = msgbox.clickedButton()
  5491. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  5492. if self.collection.get_active():
  5493. self.log.debug("App.on_delete()")
  5494. while self.collection.get_active():
  5495. obj_active = self.collection.get_active()
  5496. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  5497. if isinstance(obj_active, FlatCAMGerber):
  5498. for el in obj_active.mark_shapes:
  5499. obj_active.mark_shapes[el].clear(update=True)
  5500. obj_active.mark_shapes[el].enabled = False
  5501. # obj_active.mark_shapes[el] = None
  5502. del el
  5503. elif isinstance(obj_active, FlatCAMCNCjob):
  5504. try:
  5505. obj_active.annotation.clear(update=True)
  5506. obj_active.annotation.enabled = False
  5507. except AttributeError:
  5508. pass
  5509. self.delete_first_selected()
  5510. self.inform.emit('%s...' %
  5511. _("Object(s) deleted"))
  5512. # make sure that the selection shape is deleted, too
  5513. self.delete_selection_shape()
  5514. else:
  5515. self.inform.emit(_("Failed. No object(s) selected..."))
  5516. else:
  5517. self.inform.emit(_("Save the work in Editor and try again ..."))
  5518. def delete_first_selected(self):
  5519. # Keep this for later
  5520. try:
  5521. sel_obj = self.collection.get_active()
  5522. name = sel_obj.options["name"]
  5523. except AttributeError:
  5524. self.log.debug("Nothing selected for deletion")
  5525. return
  5526. # Remove from dictionary
  5527. self.collection.delete_active()
  5528. # Clear form
  5529. self.setup_component_editor()
  5530. self.inform.emit('%s: %s' %
  5531. (_("Object deleted"), name))
  5532. def on_set_origin(self):
  5533. """
  5534. Set the origin to the left mouse click position
  5535. :return: None
  5536. """
  5537. # display the message for the user
  5538. # and ask him to click on the desired position
  5539. self.report_usage("on_set_origin()")
  5540. def origin_replot():
  5541. def worker_task():
  5542. with self.proc_container.new('%s...' % _("Plotting")):
  5543. for obj in self.collection.get_list():
  5544. obj.plot()
  5545. self.plotcanvas.fit_view()
  5546. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  5547. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5548. self.inform.emit(_('Click to set the origin ...'))
  5549. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  5550. # first disconnect it as it may have been used by something else
  5551. try:
  5552. self.replot_signal.disconnect()
  5553. except TypeError:
  5554. pass
  5555. self.replot_signal[list].connect(origin_replot)
  5556. def on_set_zero_click(self, event):
  5557. # this function will be available only for mouse left click
  5558. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5559. if event.button == 1:
  5560. if self.grid_status() == True:
  5561. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5562. else:
  5563. pos = pos_canvas
  5564. x = 0 - pos[0]
  5565. y = 0 - pos[1]
  5566. def worker_task():
  5567. with self.proc_container.new(_("Setting Origin...")):
  5568. for obj in self.collection.get_list():
  5569. obj.offset((x, y))
  5570. self.object_changed.emit(obj)
  5571. # Update the object bounding box options
  5572. a, b, c, d = obj.bounds()
  5573. obj.options['xmin'] = a
  5574. obj.options['ymin'] = b
  5575. obj.options['xmax'] = c
  5576. obj.options['ymax'] = d
  5577. self.inform.emit('[success]%s...' %
  5578. _('Origin set'))
  5579. self.replot_signal.emit([])
  5580. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5581. self.should_we_save = True
  5582. def on_jump_to(self, custom_location=None, fit_center=True):
  5583. """
  5584. Jump to a location by setting the mouse cursor location
  5585. :return:
  5586. """
  5587. self.report_usage("on_jump_to()")
  5588. if not custom_location:
  5589. dia_box = Dialog_box(title=_("Jump to ..."),
  5590. label=_("Enter the coordinates in format X,Y:"),
  5591. icon=QtGui.QIcon('share/jump_to16.png'))
  5592. if dia_box.ok is True:
  5593. try:
  5594. location = eval(dia_box.location)
  5595. if not isinstance(location, tuple):
  5596. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  5597. return
  5598. except:
  5599. return
  5600. else:
  5601. return
  5602. else:
  5603. location = custom_location
  5604. if fit_center:
  5605. self.plotcanvas.fit_center(loc=location)
  5606. cursor = QtGui.QCursor()
  5607. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5608. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  5609. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  5610. self.inform.emit('[success] %s' %
  5611. _("Done."))
  5612. return location
  5613. def on_copy_object(self):
  5614. self.report_usage("on_copy_object()")
  5615. def initialize(obj_init, app):
  5616. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5617. try:
  5618. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5619. except AttributeError:
  5620. pass
  5621. try:
  5622. obj_init.apertures = deepcopy(obj.apertures)
  5623. except AttributeError:
  5624. pass
  5625. try:
  5626. if obj.tools:
  5627. obj_init.tools = deepcopy(obj.tools)
  5628. except Exception as e:
  5629. log.debug("App.on_copy_object() --> %s" % str(e))
  5630. def initialize_excellon(obj_init, app):
  5631. obj_init.tools = deepcopy(obj.tools)
  5632. # drills are offset, so they need to be deep copied
  5633. obj_init.drills = deepcopy(obj.drills)
  5634. # slots are offset, so they need to be deep copied
  5635. obj_init.slots = deepcopy(obj.slots)
  5636. obj_init.create_geometry()
  5637. for obj in self.collection.get_selected():
  5638. obj_name = obj.options["name"]
  5639. try:
  5640. if isinstance(obj, FlatCAMExcellon):
  5641. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  5642. elif isinstance(obj, FlatCAMGerber):
  5643. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  5644. elif isinstance(obj, FlatCAMGeometry):
  5645. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  5646. except Exception as e:
  5647. return "Operation failed: %s" % str(e)
  5648. def on_copy_object2(self, custom_name):
  5649. def initialize_geometry(obj_init, app):
  5650. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5651. try:
  5652. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5653. except AttributeError:
  5654. pass
  5655. try:
  5656. obj_init.apertures = deepcopy(obj.apertures)
  5657. except AttributeError:
  5658. pass
  5659. try:
  5660. if obj.tools:
  5661. obj_init.tools = deepcopy(obj.tools)
  5662. except Exception as e:
  5663. log.debug("on_copy_object2() --> %s" % str(e))
  5664. def initialize_gerber(obj_init, app):
  5665. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5666. obj_init.apertures = deepcopy(obj.apertures)
  5667. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  5668. def initialize_excellon(obj_init, app):
  5669. obj_init.tools = deepcopy(obj.tools)
  5670. # drills are offset, so they need to be deep copied
  5671. obj_init.drills = deepcopy(obj.drills)
  5672. # slots are offset, so they need to be deep copied
  5673. obj_init.slots = deepcopy(obj.slots)
  5674. obj_init.create_geometry()
  5675. for obj in self.collection.get_selected():
  5676. obj_name = obj.options["name"]
  5677. try:
  5678. if isinstance(obj, FlatCAMExcellon):
  5679. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  5680. elif isinstance(obj, FlatCAMGerber):
  5681. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  5682. elif isinstance(obj, FlatCAMGeometry):
  5683. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  5684. except Exception as e:
  5685. return "Operation failed: %s" % str(e)
  5686. def on_rename_object(self, text):
  5687. self.report_usage("on_rename_object()")
  5688. named_obj = self.collection.get_active()
  5689. for obj in named_obj:
  5690. if obj is list:
  5691. self.on_rename_object(text)
  5692. else:
  5693. try:
  5694. obj.options['name'] = text
  5695. except Exception as e:
  5696. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  5697. def convert_any2geo(self):
  5698. self.report_usage("convert_any2geo()")
  5699. def initialize(obj_init, app):
  5700. obj_init.solid_geometry = obj.solid_geometry
  5701. try:
  5702. obj_init.follow_geometry = obj.follow_geometry
  5703. except AttributeError:
  5704. pass
  5705. try:
  5706. obj_init.apertures = obj.apertures
  5707. except AttributeError:
  5708. pass
  5709. try:
  5710. if obj.tools:
  5711. obj_init.tools = obj.tools
  5712. except AttributeError:
  5713. pass
  5714. def initialize_excellon(obj_init, app):
  5715. # objs = self.collection.get_selected()
  5716. # FlatCAMGeometry.merge(objs, obj)
  5717. solid_geo = []
  5718. for tool in obj.tools:
  5719. for geo in obj.tools[tool]['solid_geometry']:
  5720. solid_geo.append(geo)
  5721. obj_init.solid_geometry = deepcopy(solid_geo)
  5722. if not self.collection.get_selected():
  5723. log.warning("App.convert_any2geo --> No object selected")
  5724. self.inform.emit('[WARNING_NOTCL] %s' %
  5725. _("No object is selected. Select an object and try again."))
  5726. return
  5727. for obj in self.collection.get_selected():
  5728. obj_name = obj.options["name"]
  5729. try:
  5730. if isinstance(obj, FlatCAMExcellon):
  5731. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  5732. else:
  5733. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  5734. except Exception as e:
  5735. return "Operation failed: %s" % str(e)
  5736. def convert_any2gerber(self):
  5737. self.report_usage("convert_any2gerber()")
  5738. def initialize_geometry(obj_init, app):
  5739. apertures = {}
  5740. apid = 0
  5741. apertures[str(apid)] = {}
  5742. apertures[str(apid)]['geometry'] = []
  5743. for obj_orig in obj.solid_geometry:
  5744. new_elem = dict()
  5745. new_elem['solid'] = obj_orig
  5746. new_elem['follow'] = obj_orig.exterior
  5747. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  5748. apertures[str(apid)]['size'] = 0.0
  5749. apertures[str(apid)]['type'] = 'C'
  5750. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5751. obj_init.apertures = deepcopy(apertures)
  5752. def initialize_excellon(obj_init, app):
  5753. apertures = {}
  5754. apid = 10
  5755. for tool in obj.tools:
  5756. apertures[str(apid)] = {}
  5757. apertures[str(apid)]['geometry'] = []
  5758. for geo in obj.tools[tool]['solid_geometry']:
  5759. new_el = dict()
  5760. new_el['solid'] = geo
  5761. new_el['follow'] = geo.exterior
  5762. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  5763. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  5764. apertures[str(apid)]['type'] = 'C'
  5765. apid += 1
  5766. # create solid_geometry
  5767. solid_geometry = []
  5768. for apid in apertures:
  5769. for geo_el in apertures[apid]['geometry']:
  5770. solid_geometry.append(geo_el['solid'])
  5771. solid_geometry = MultiPolygon(solid_geometry)
  5772. solid_geometry = solid_geometry.buffer(0.0000001)
  5773. obj_init.solid_geometry = deepcopy(solid_geometry)
  5774. obj_init.apertures = deepcopy(apertures)
  5775. # clear the working objects (perhaps not necessary due of Python GC)
  5776. apertures.clear()
  5777. if not self.collection.get_selected():
  5778. log.warning("App.convert_any2gerber --> No object selected")
  5779. self.inform.emit('[WARNING_NOTCL] %s' %
  5780. _("No object is selected. Select an object and try again."))
  5781. return
  5782. for obj in self.collection.get_selected():
  5783. obj_name = obj.options["name"]
  5784. try:
  5785. if isinstance(obj, FlatCAMExcellon):
  5786. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  5787. elif isinstance(obj, FlatCAMGeometry):
  5788. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  5789. else:
  5790. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  5791. except Exception as e:
  5792. return "Operation failed: %s" % str(e)
  5793. def abort_all_tasks(self):
  5794. if self.abort_flag is False:
  5795. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  5796. self.abort_flag = True
  5797. def app_is_idle(self):
  5798. if self.abort_flag:
  5799. self.inform.emit('[WARNING_NOTCL] %s' %
  5800. _("The current task was gracefully closed on user request..."))
  5801. self.abort_flag = False
  5802. def on_selectall(self):
  5803. self.report_usage("on_selectall()")
  5804. # delete the possible selection box around a possible selected object
  5805. self.delete_selection_shape()
  5806. for name in self.collection.get_names():
  5807. self.collection.set_active(name)
  5808. curr_sel_obj = self.collection.get_by_name(name)
  5809. # create the selection box around the selected object
  5810. if self.defaults['global_selection_shape'] is True:
  5811. self.draw_selection_shape(curr_sel_obj)
  5812. def on_preferences(self):
  5813. # add the tab if it was closed
  5814. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  5815. # delete the absolute and relative position and messages in the infobar
  5816. self.ui.position_label.setText("")
  5817. self.ui.rel_position_label.setText("")
  5818. # Switch plot_area to preferences page
  5819. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  5820. # self.ui.show()
  5821. # this disconnect() is done so the slot will be connected only once
  5822. try:
  5823. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_preferences_closed)
  5824. except (TypeError, AttributeError):
  5825. pass
  5826. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_preferences_closed)
  5827. # detect changes in the preferences
  5828. for idx in range(self.ui.pref_tab_area.count()):
  5829. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5830. try:
  5831. try:
  5832. tb.textEdited.disconnect(self.on_preferences_edited)
  5833. except (TypeError, AttributeError):
  5834. pass
  5835. tb.textEdited.connect(self.on_preferences_edited)
  5836. except AttributeError:
  5837. pass
  5838. try:
  5839. try:
  5840. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5841. except (TypeError, AttributeError):
  5842. pass
  5843. tb.modificationChanged.connect(self.on_preferences_edited)
  5844. except AttributeError:
  5845. pass
  5846. try:
  5847. try:
  5848. tb.toggled.disconnect(self.on_preferences_edited)
  5849. except (TypeError, AttributeError):
  5850. pass
  5851. tb.toggled.connect(self.on_preferences_edited)
  5852. except AttributeError:
  5853. pass
  5854. try:
  5855. try:
  5856. tb.valueChanged.disconnect(self.on_preferences_edited)
  5857. except (TypeError, AttributeError):
  5858. pass
  5859. tb.valueChanged.connect(self.on_preferences_edited)
  5860. except AttributeError:
  5861. pass
  5862. try:
  5863. try:
  5864. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5865. except (TypeError, AttributeError):
  5866. pass
  5867. tb.currentIndexChanged.connect(self.on_preferences_edited)
  5868. except AttributeError:
  5869. pass
  5870. def on_preferences_edited(self):
  5871. self.inform.emit('[WARNING_NOTCL] %s' %
  5872. _("Preferences edited but not saved."))
  5873. self.preferences_changed_flag = True
  5874. def on_preferences_closed(self):
  5875. # disconnect
  5876. for idx in range(self.ui.pref_tab_area.count()):
  5877. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5878. try:
  5879. tb.textEdited.disconnect(self.on_preferences_edited)
  5880. except (TypeError, AttributeError):
  5881. pass
  5882. try:
  5883. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5884. except (TypeError, AttributeError):
  5885. pass
  5886. try:
  5887. tb.toggled.disconnect(self.on_preferences_edited)
  5888. except (TypeError, AttributeError):
  5889. pass
  5890. try:
  5891. tb.valueChanged.disconnect(self.on_preferences_edited)
  5892. except (TypeError, AttributeError):
  5893. pass
  5894. try:
  5895. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5896. except (TypeError, AttributeError):
  5897. pass
  5898. if self.preferences_changed_flag is True:
  5899. msgbox = QtWidgets.QMessageBox()
  5900. msgbox.setText(_("One or more values are changed.\n"
  5901. "Do you want to save the Preferences?"))
  5902. msgbox.setWindowTitle(_("Save Preferences"))
  5903. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  5904. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5905. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5906. msgbox.setDefaultButton(bt_yes)
  5907. msgbox.exec_()
  5908. response = msgbox.clickedButton()
  5909. if response == bt_yes:
  5910. self.on_save_button()
  5911. self.inform.emit('[success] %s' %
  5912. _("Preferences saved."))
  5913. else:
  5914. self.preferences_changed_flag = False
  5915. return
  5916. def on_flipy(self):
  5917. self.report_usage("on_flipy()")
  5918. obj_list = self.collection.get_selected()
  5919. xminlist = []
  5920. yminlist = []
  5921. xmaxlist = []
  5922. ymaxlist = []
  5923. if not obj_list:
  5924. self.inform.emit('[WARNING_NOTCL] %s' %
  5925. _("No object selected to Flip on Y axis."))
  5926. else:
  5927. try:
  5928. # first get a bounding box to fit all
  5929. for obj in obj_list:
  5930. xmin, ymin, xmax, ymax = obj.bounds()
  5931. xminlist.append(xmin)
  5932. yminlist.append(ymin)
  5933. xmaxlist.append(xmax)
  5934. ymaxlist.append(ymax)
  5935. # get the minimum x,y and maximum x,y for all objects selected
  5936. xminimal = min(xminlist)
  5937. yminimal = min(yminlist)
  5938. xmaximal = max(xmaxlist)
  5939. ymaximal = max(ymaxlist)
  5940. px = 0.5 * (xminimal + xmaximal)
  5941. py = 0.5 * (yminimal + ymaximal)
  5942. # execute mirroring
  5943. for obj in obj_list:
  5944. obj.mirror('X', [px, py])
  5945. obj.plot()
  5946. self.object_changed.emit(obj)
  5947. self.inform.emit('[success] %s' %
  5948. _("Flip on Y axis done."))
  5949. except Exception as e:
  5950. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  5951. (_("Flip action was not executed."), str(e)))
  5952. return
  5953. def on_flipx(self):
  5954. self.report_usage("on_flipx()")
  5955. obj_list = self.collection.get_selected()
  5956. xminlist = []
  5957. yminlist = []
  5958. xmaxlist = []
  5959. ymaxlist = []
  5960. if not obj_list:
  5961. self.inform.emit('[WARNING_NOTCL] %s' %
  5962. _("No object selected to Flip on X axis."))
  5963. else:
  5964. try:
  5965. # first get a bounding box to fit all
  5966. for obj in obj_list:
  5967. xmin, ymin, xmax, ymax = obj.bounds()
  5968. xminlist.append(xmin)
  5969. yminlist.append(ymin)
  5970. xmaxlist.append(xmax)
  5971. ymaxlist.append(ymax)
  5972. # get the minimum x,y and maximum x,y for all objects selected
  5973. xminimal = min(xminlist)
  5974. yminimal = min(yminlist)
  5975. xmaximal = max(xmaxlist)
  5976. ymaximal = max(ymaxlist)
  5977. px = 0.5 * (xminimal + xmaximal)
  5978. py = 0.5 * (yminimal + ymaximal)
  5979. # execute mirroring
  5980. for obj in obj_list:
  5981. obj.mirror('Y', [px, py])
  5982. obj.plot()
  5983. self.object_changed.emit(obj)
  5984. self.inform.emit('[success] %s' %
  5985. _("Flip on X axis done."))
  5986. except Exception as e:
  5987. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  5988. (_("Flip action was not executed."), str(e)))
  5989. return
  5990. def on_rotate(self, silent=False, preset=None):
  5991. self.report_usage("on_rotate()")
  5992. obj_list = self.collection.get_selected()
  5993. xminlist = []
  5994. yminlist = []
  5995. xmaxlist = []
  5996. ymaxlist = []
  5997. if not obj_list:
  5998. self.inform.emit('[WARNING_NOTCL] %s' %
  5999. _("No object selected to Rotate."))
  6000. else:
  6001. if silent is False:
  6002. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6003. min=-360, max=360, decimals=4,
  6004. init_val=float(self.defaults['tools_transform_rotate']))
  6005. num, ok = rotatebox.get_value()
  6006. else:
  6007. num = preset
  6008. ok = True
  6009. if ok:
  6010. try:
  6011. # first get a bounding box to fit all
  6012. for obj in obj_list:
  6013. xmin, ymin, xmax, ymax = obj.bounds()
  6014. xminlist.append(xmin)
  6015. yminlist.append(ymin)
  6016. xmaxlist.append(xmax)
  6017. ymaxlist.append(ymax)
  6018. # get the minimum x,y and maximum x,y for all objects selected
  6019. xminimal = min(xminlist)
  6020. yminimal = min(yminlist)
  6021. xmaximal = max(xmaxlist)
  6022. ymaximal = max(ymaxlist)
  6023. px = 0.5 * (xminimal + xmaximal)
  6024. py = 0.5 * (yminimal + ymaximal)
  6025. for sel_obj in obj_list:
  6026. sel_obj.rotate(-float(num), point=(px, py))
  6027. sel_obj.plot()
  6028. self.object_changed.emit(sel_obj)
  6029. self.inform.emit('[success] %s' %
  6030. _("Rotation done."))
  6031. except Exception as e:
  6032. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6033. (_("Rotation movement was not executed."), str(e)))
  6034. return
  6035. def on_skewx(self):
  6036. self.report_usage("on_skewx()")
  6037. obj_list = self.collection.get_selected()
  6038. xminlist = []
  6039. yminlist = []
  6040. if not obj_list:
  6041. self.inform.emit('[WARNING_NOTCL] %s' %
  6042. _("No object selected to Skew/Shear on X axis."))
  6043. else:
  6044. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6045. min=-360, max=360, decimals=4,
  6046. init_val=float(self.defaults['tools_transform_skew_x']))
  6047. num, ok = skewxbox.get_value()
  6048. if ok:
  6049. # first get a bounding box to fit all
  6050. for obj in obj_list:
  6051. xmin, ymin, xmax, ymax = obj.bounds()
  6052. xminlist.append(xmin)
  6053. yminlist.append(ymin)
  6054. # get the minimum x,y and maximum x,y for all objects selected
  6055. xminimal = min(xminlist)
  6056. yminimal = min(yminlist)
  6057. for obj in obj_list:
  6058. obj.skew(num, 0, point=(xminimal, yminimal))
  6059. obj.plot()
  6060. self.object_changed.emit(obj)
  6061. self.inform.emit('[success] %s' %
  6062. _("Skew on X axis done."))
  6063. def on_skewy(self):
  6064. self.report_usage("on_skewy()")
  6065. obj_list = self.collection.get_selected()
  6066. xminlist = []
  6067. yminlist = []
  6068. if not obj_list:
  6069. self.inform.emit('[WARNING_NOTCL] %s' %
  6070. _("No object selected to Skew/Shear on Y axis."))
  6071. else:
  6072. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6073. min=-360, max=360, decimals=4,
  6074. init_val=float(self.defaults['tools_transform_skew_y']))
  6075. num, ok = skewybox.get_value()
  6076. if ok:
  6077. # first get a bounding box to fit all
  6078. for obj in obj_list:
  6079. xmin, ymin, xmax, ymax = obj.bounds()
  6080. xminlist.append(xmin)
  6081. yminlist.append(ymin)
  6082. # get the minimum x,y and maximum x,y for all objects selected
  6083. xminimal = min(xminlist)
  6084. yminimal = min(yminlist)
  6085. for obj in obj_list:
  6086. obj.skew(0, num, point=(xminimal, yminimal))
  6087. obj.plot()
  6088. self.object_changed.emit(obj)
  6089. self.inform.emit('[success] %s' %
  6090. _("Skew on Y axis done."))
  6091. def on_plots_updated(self):
  6092. """
  6093. Callback used to report when the plots have changed.
  6094. Adjust axes and zooms to fit.
  6095. :return: None
  6096. """
  6097. self.plotcanvas.update() # TODO: Need update canvas?
  6098. self.on_zoom_fit(None)
  6099. self.collection.update_view()
  6100. # self.inform.emit(_("Plots updated ..."))
  6101. # TODO: Rework toolbar 'clear', 'replot' functions
  6102. def on_toolbar_replot(self):
  6103. """
  6104. Callback for toolbar button. Re-plots all objects.
  6105. :return: None
  6106. """
  6107. self.report_usage("on_toolbar_replot")
  6108. self.log.debug("on_toolbar_replot()")
  6109. try:
  6110. self.collection.get_active().read_form()
  6111. except AttributeError:
  6112. self.log.debug("on_toolbar_replot(): AttributeError")
  6113. pass
  6114. self.plot_all()
  6115. def on_row_activated(self, index):
  6116. if index.isValid():
  6117. if index.internalPointer().parent_item != self.collection.root_item:
  6118. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6119. self.collection.on_item_activated(index)
  6120. def grid_status(self):
  6121. if self.ui.grid_snap_btn.isChecked():
  6122. return True
  6123. else:
  6124. return False
  6125. def populate_cmenu_grids(self):
  6126. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6127. self.ui.cmenu_gridmenu.clear()
  6128. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  6129. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  6130. grid_toggle.setCheckable(True)
  6131. if self.grid_status() == True:
  6132. grid_toggle.setChecked(True)
  6133. else:
  6134. grid_toggle.setChecked(False)
  6135. self.ui.cmenu_gridmenu.addSeparator()
  6136. for grid in sorted_list:
  6137. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  6138. action.triggered.connect(self.set_grid)
  6139. self.ui.cmenu_gridmenu.addSeparator()
  6140. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  6141. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  6142. grid_add.triggered.connect(self.on_grid_add)
  6143. grid_delete.triggered.connect(self.on_grid_delete)
  6144. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  6145. def set_grid(self):
  6146. self.ui.grid_gap_x_entry.setText(self.sender().text())
  6147. self.ui.grid_gap_y_entry.setText(self.sender().text())
  6148. def on_grid_add(self):
  6149. # ## Current application units in lower Case
  6150. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6151. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  6152. text=_('Enter a Grid Value:'),
  6153. min=0.0000, max=99.9999, decimals=4)
  6154. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  6155. val, ok = grid_add_popup.get_value()
  6156. if ok:
  6157. if float(val) == 0:
  6158. self.inform.emit('[WARNING_NOTCL] %s' %
  6159. _("Please enter a grid value with non-zero value, in Float format."))
  6160. return
  6161. else:
  6162. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  6163. self.defaults["global_grid_context_menu"][str(units)].append(val)
  6164. self.inform.emit('[success] %s...' %
  6165. _("New Grid added"))
  6166. else:
  6167. self.inform.emit('[WARNING_NOTCL] %s...' %
  6168. _("Grid already exists"))
  6169. else:
  6170. self.inform.emit('[WARNING_NOTCL] %s...' %
  6171. _("Adding New Grid cancelled"))
  6172. def on_grid_delete(self):
  6173. # ## Current application units in lower Case
  6174. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6175. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  6176. text='Enter a Grid Value:',
  6177. min=0.0000, max=99.9999, decimals=4)
  6178. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  6179. val, ok = grid_del_popup.get_value()
  6180. if ok:
  6181. if float(val) == 0:
  6182. self.inform.emit('[WARNING_NOTCL] %s' %
  6183. _("Please enter a grid value with non-zero value, in Float format."))
  6184. return
  6185. else:
  6186. try:
  6187. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  6188. except ValueError:
  6189. self.inform.emit('[ERROR_NOTCL]%s...' %
  6190. _(" Grid Value does not exist"))
  6191. return
  6192. self.inform.emit('[success] %s...' %
  6193. _("Grid Value deleted"))
  6194. else:
  6195. self.inform.emit('[WARNING_NOTCL] %s...' %
  6196. _("Delete Grid value cancelled"))
  6197. def on_shortcut_list(self):
  6198. self.report_usage("on_shortcut_list()")
  6199. # add the tab if it was closed
  6200. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  6201. # delete the absolute and relative position and messages in the infobar
  6202. self.ui.position_label.setText("")
  6203. self.ui.rel_position_label.setText("")
  6204. # Switch plot_area to preferences page
  6205. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  6206. # self.ui.show()
  6207. def on_select_tab(self, name):
  6208. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  6209. if self.ui.splitter.sizes()[0] == 0:
  6210. self.ui.splitter.setSizes([1, 1])
  6211. else:
  6212. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  6213. self.ui.splitter.setSizes([0, 1])
  6214. if name == 'project':
  6215. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6216. elif name == 'selected':
  6217. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6218. elif name == 'tool':
  6219. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  6220. def on_copy_name(self):
  6221. self.report_usage("on_copy_name()")
  6222. obj = self.collection.get_active()
  6223. try:
  6224. name = obj.options["name"]
  6225. except AttributeError:
  6226. log.debug("on_copy_name() --> No object selected to copy it's name")
  6227. self.inform.emit('[WARNING_NOTCL]%s' %
  6228. _(" No object selected to copy it's name"))
  6229. return
  6230. self.clipboard.setText(name)
  6231. self.inform.emit(_("Name copied on clipboard ..."))
  6232. def on_mouse_click_over_plot(self, event):
  6233. """
  6234. Default actions are:
  6235. :param event: Contains information about the event, like which button
  6236. was clicked, the pixel coordinates and the axes coordinates.
  6237. :return: None
  6238. """
  6239. self.pos = []
  6240. # So it can receive key presses
  6241. self.plotcanvas.native.setFocus()
  6242. # Set the mouse button for panning
  6243. self.plotcanvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  6244. self.pos_canvas = self.plotcanvas.translate_coords(event.pos)
  6245. if self.grid_status() == True:
  6246. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  6247. self.app_cursor.enabled = True
  6248. else:
  6249. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  6250. self.app_cursor.enabled = False
  6251. try:
  6252. modifiers = QtWidgets.QApplication.keyboardModifiers()
  6253. if event.button == 1:
  6254. # Reset here the relative coordinates so there is a new reference on the click position
  6255. if self.rel_point1 is None:
  6256. self.rel_point1 = self.pos
  6257. else:
  6258. self.rel_point2 = copy(self.rel_point1)
  6259. self.rel_point1 = self.pos
  6260. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  6261. if modifiers == QtCore.Qt.ShiftModifier:
  6262. # do not auto open the Project Tab
  6263. self.click_noproject = True
  6264. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  6265. self.inform.emit('[success] %s' %
  6266. _("Coordinates copied to clipboard."))
  6267. return
  6268. self.on_mouse_move_over_plot(event, origin_click=True)
  6269. except Exception as e:
  6270. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  6271. def on_double_click_over_plot(self, event):
  6272. self.doubleclick = True
  6273. def on_mouse_move_over_plot(self, event, origin_click=None):
  6274. """
  6275. Callback for the mouse motion event over the plot.
  6276. :param event: Contains information about the event.
  6277. :param origin_click
  6278. :return: None
  6279. """
  6280. # So it can receive key presses
  6281. self.plotcanvas.native.setFocus()
  6282. self.pos_jump = event.pos
  6283. self.ui.popMenu.mouse_is_panning = False
  6284. if not origin_click:
  6285. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  6286. if event.button == 2 and event.is_dragging == 1:
  6287. self.ui.popMenu.mouse_is_panning = True
  6288. return
  6289. if self.rel_point1 is not None:
  6290. try: # May fail in case mouse not within axes
  6291. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  6292. if self.grid_status() == True:
  6293. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6294. self.app_cursor.enabled = True
  6295. # Update cursor
  6296. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  6297. else:
  6298. pos = (pos_canvas[0], pos_canvas[1])
  6299. self.app_cursor.enabled = False
  6300. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6301. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  6302. dx = pos[0] - self.rel_point1[0]
  6303. dy = pos[1] - self.rel_point1[1]
  6304. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6305. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6306. self.mouse = [pos[0], pos[1]]
  6307. # if the mouse is moved and the LMB is clicked then the action is a selection
  6308. if event.is_dragging == 1 and event.button == 1:
  6309. self.delete_selection_shape()
  6310. if dx < 0:
  6311. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  6312. face_color=self.defaults['global_alt_sel_fill'])
  6313. self.selection_type = False
  6314. else:
  6315. self.draw_moving_selection_shape(self.pos, pos)
  6316. self.selection_type = True
  6317. # hover effect - enabled in Preferences -> General -> GUI Settings
  6318. if self.defaults['global_hover']:
  6319. for obj in self.collection.get_list():
  6320. try:
  6321. # select the object(s) only if it is enabled (plotted)
  6322. if obj.options['plot']:
  6323. if obj not in self.collection.get_selected():
  6324. poly_obj = Polygon(
  6325. [(obj.options['xmin'], obj.options['ymin']),
  6326. (obj.options['xmax'], obj.options['ymin']),
  6327. (obj.options['xmax'], obj.options['ymax']),
  6328. (obj.options['xmin'], obj.options['ymax'])]
  6329. )
  6330. if Point(pos).within(poly_obj):
  6331. if obj.isHovering is False:
  6332. obj.isHovering = True
  6333. obj.notHovering = True
  6334. # create the selection box around the selected object
  6335. self.draw_hover_shape(obj, color='#d1e0e0')
  6336. else:
  6337. if obj.notHovering is True:
  6338. obj.notHovering = False
  6339. obj.isHovering = False
  6340. self.delete_hover_shape()
  6341. except:
  6342. # the Exception here will happen if we try to select on screen and we have an
  6343. # newly (and empty) just created Geometry or Excellon object that do not have the
  6344. # xmin, xmax, ymin, ymax options.
  6345. # In this case poly_obj creation (see above) will fail
  6346. pass
  6347. except:
  6348. self.ui.position_label.setText("")
  6349. self.ui.rel_position_label.setText("")
  6350. self.mouse = None
  6351. def on_mouse_click_release_over_plot(self, event):
  6352. """
  6353. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  6354. and has been registered in ''self.__init__()''.
  6355. :param event: contains information about the event.
  6356. :return:
  6357. """
  6358. pos = 0, 0
  6359. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  6360. if self.grid_status() == True:
  6361. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6362. else:
  6363. pos = (pos_canvas[0], pos_canvas[1])
  6364. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  6365. # canvas menu
  6366. if event.button == 2: # right click
  6367. if self.ui.popMenu.mouse_is_panning is False:
  6368. self.cursor = QtGui.QCursor()
  6369. self.populate_cmenu_grids()
  6370. self.ui.popMenu.popup(self.cursor.pos())
  6371. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  6372. # selection and then select a type of selection ("enclosing" or "touching")
  6373. try:
  6374. if event.button == 1: # left click
  6375. if self.doubleclick is True:
  6376. self.doubleclick = False
  6377. if self.collection.get_selected():
  6378. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6379. if self.ui.splitter.sizes()[0] == 0:
  6380. self.ui.splitter.setSizes([1, 1])
  6381. # delete the selection shape(S) as it may be in the way
  6382. self.delete_selection_shape()
  6383. self.delete_hover_shape()
  6384. else:
  6385. if self.selection_type is not None:
  6386. self.selection_area_handler(self.pos, pos, self.selection_type)
  6387. self.selection_type = None
  6388. else:
  6389. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  6390. if key_modifier == QtCore.Qt.ShiftModifier:
  6391. mod_key = 'Shift'
  6392. elif key_modifier == QtCore.Qt.ControlModifier:
  6393. mod_key = 'Control'
  6394. else:
  6395. mod_key = None
  6396. if mod_key == self.defaults["global_mselect_key"]:
  6397. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  6398. # deselect, and if it's not selected then it will be selected
  6399. # If there is no active command (self.command_active is None) then we check if we clicked
  6400. # on a object by checking the bounding limits against mouse click position
  6401. if self.command_active is None:
  6402. self.select_objects(key='CTRL')
  6403. self.delete_hover_shape()
  6404. else:
  6405. # If there is no active command (self.command_active is None) then we check if we clicked
  6406. # on a object by checking the bounding limits against mouse click position
  6407. if self.command_active is None:
  6408. self.select_objects()
  6409. self.delete_hover_shape()
  6410. except Exception as e:
  6411. log.warning("Error: %s" % str(e))
  6412. return
  6413. def selection_area_handler(self, start_pos, end_pos, sel_type):
  6414. """
  6415. :param start_pos: mouse position when the selection LMB click was done
  6416. :param end_pos: mouse position when the left mouse button is released
  6417. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  6418. :return:
  6419. """
  6420. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  6421. self.delete_selection_shape()
  6422. for obj in self.collection.get_list():
  6423. try:
  6424. # select the object(s) only if it is enabled (plotted)
  6425. if obj.options['plot']:
  6426. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  6427. (obj.options['xmax'], obj.options['ymin']),
  6428. (obj.options['xmax'], obj.options['ymax']),
  6429. (obj.options['xmin'], obj.options['ymax'])])
  6430. if sel_type is True:
  6431. if poly_obj.within(poly_selection):
  6432. # create the selection box around the selected object
  6433. if self.defaults['global_selection_shape'] is True:
  6434. self.draw_selection_shape(obj)
  6435. self.collection.set_active(obj.options['name'])
  6436. else:
  6437. if poly_selection.intersects(poly_obj):
  6438. # create the selection box around the selected object
  6439. if self.defaults['global_selection_shape'] is True:
  6440. self.draw_selection_shape(obj)
  6441. self.collection.set_active(obj.options['name'])
  6442. except Exception as e:
  6443. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  6444. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  6445. # In this case poly_obj creation (see above) will fail
  6446. log.debug("App.selection_area_handler() --> %s" % str(e))
  6447. def select_objects(self, key=None):
  6448. # list where we store the overlapped objects under our mouse left click position
  6449. objects_under_the_click_list = []
  6450. # Populate the list with the overlapped objects on the click position
  6451. curr_x, curr_y = self.pos
  6452. for obj in self.all_objects_list:
  6453. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  6454. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  6455. if obj.options['name'] not in objects_under_the_click_list:
  6456. if obj.options['plot']:
  6457. # add objects to the objects_under_the_click list only if the object is plotted
  6458. # (active and not disabled)
  6459. objects_under_the_click_list.append(obj.options['name'])
  6460. try:
  6461. # If there is no element in the overlapped objects list then make everyone inactive
  6462. # because we selected "nothing"
  6463. if not objects_under_the_click_list:
  6464. self.collection.set_all_inactive()
  6465. # delete the possible selection box around a possible selected object
  6466. self.delete_selection_shape()
  6467. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  6468. # only when working on App
  6469. if self.call_source == 'app':
  6470. if self.click_noproject is False:
  6471. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6472. else:
  6473. # restore auto open the Project Tab
  6474. self.click_noproject = False
  6475. # delete any text in the status bar, implicitly the last object name that was selected
  6476. self.inform.emit("")
  6477. else:
  6478. self.call_source = 'app'
  6479. else:
  6480. # case when there is only an object under the click and we toggle it
  6481. if len(objects_under_the_click_list) == 1:
  6482. if self.collection.get_active() is None:
  6483. self.collection.set_active(objects_under_the_click_list[0])
  6484. # create the selection box around the selected object
  6485. curr_sel_obj = self.collection.get_active()
  6486. if self.defaults['global_selection_shape'] is True:
  6487. self.draw_selection_shape(curr_sel_obj)
  6488. # self.inform.emit('[selected] %s: %s selected' %
  6489. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6490. if curr_sel_obj.kind == 'gerber':
  6491. self.inform.emit(
  6492. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6493. color='green', name=str(curr_sel_obj.options['name'])))
  6494. elif curr_sel_obj.kind == 'excellon':
  6495. self.inform.emit(
  6496. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6497. color='brown', name=str(curr_sel_obj.options['name'])))
  6498. elif curr_sel_obj.kind == 'cncjob':
  6499. self.inform.emit(
  6500. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6501. color='blue', name=str(curr_sel_obj.options['name'])))
  6502. elif curr_sel_obj.kind == 'geometry':
  6503. self.inform.emit(
  6504. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6505. color='red', name=str(curr_sel_obj.options['name'])))
  6506. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  6507. self.collection.set_all_inactive()
  6508. self.delete_selection_shape()
  6509. self.collection.set_active(objects_under_the_click_list[0])
  6510. # create the selection box around the selected object
  6511. curr_sel_obj = self.collection.get_active()
  6512. if self.defaults['global_selection_shape'] is True:
  6513. self.draw_selection_shape(curr_sel_obj)
  6514. # self.inform.emit('[selected] %s: %s selected' %
  6515. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6516. if curr_sel_obj.kind == 'gerber':
  6517. self.inform.emit(
  6518. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6519. color='green', name=str(curr_sel_obj.options['name'])))
  6520. elif curr_sel_obj.kind == 'excellon':
  6521. self.inform.emit(
  6522. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6523. color='brown', name=str(curr_sel_obj.options['name'])))
  6524. elif curr_sel_obj.kind == 'cncjob':
  6525. self.inform.emit(
  6526. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6527. color='blue', name=str(curr_sel_obj.options['name'])))
  6528. elif curr_sel_obj.kind == 'geometry':
  6529. self.inform.emit(
  6530. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6531. color='red', name=str(curr_sel_obj.options['name'])))
  6532. else:
  6533. self.collection.set_all_inactive()
  6534. self.delete_selection_shape()
  6535. if self.call_source == 'app':
  6536. # delete any text in the status bar, implicitly the last object name that was selected
  6537. self.inform.emit("")
  6538. else:
  6539. self.call_source = 'app'
  6540. else:
  6541. # If there is no selected object
  6542. # make active the first element of the overlapped objects list
  6543. if self.collection.get_active() is None:
  6544. self.collection.set_active(objects_under_the_click_list[0])
  6545. name_sel_obj = self.collection.get_active().options['name']
  6546. # In case that there is a selected object but it is not in the overlapped object list
  6547. # make that object inactive and activate the first element in the overlapped object list
  6548. if name_sel_obj not in objects_under_the_click_list:
  6549. self.collection.set_inactive(name_sel_obj)
  6550. name_sel_obj = objects_under_the_click_list[0]
  6551. self.collection.set_active(name_sel_obj)
  6552. else:
  6553. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  6554. self.collection.set_all_inactive()
  6555. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  6556. len(objects_under_the_click_list)])
  6557. curr_sel_obj = self.collection.get_active()
  6558. # delete the possible selection box around a possible selected object
  6559. self.delete_selection_shape()
  6560. # create the selection box around the selected object
  6561. if self.defaults['global_selection_shape'] is True:
  6562. self.draw_selection_shape(curr_sel_obj)
  6563. # self.inform.emit('[selected] %s: %s selected' %
  6564. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6565. if curr_sel_obj.kind == 'gerber':
  6566. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6567. color='green', name=str(curr_sel_obj.options['name'])))
  6568. elif curr_sel_obj.kind == 'excellon':
  6569. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6570. color='brown', name=str(curr_sel_obj.options['name'])))
  6571. elif curr_sel_obj.kind == 'cncjob':
  6572. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6573. color='blue', name=str(curr_sel_obj.options['name'])))
  6574. elif curr_sel_obj.kind == 'geometry':
  6575. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6576. color='red', name=str(curr_sel_obj.options['name'])))
  6577. # for obj in self.collection.get_list():
  6578. # obj.plot()
  6579. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  6580. # TODO: on selected objects change the object colors and do not draw the selection box
  6581. # self.plotcanvas.update() # this updates the canvas
  6582. except Exception as e:
  6583. log.error("[ERROR] Something went bad. %s" % str(e))
  6584. return
  6585. def delete_hover_shape(self):
  6586. self.hover_shapes.clear()
  6587. self.hover_shapes.redraw()
  6588. def draw_hover_shape(self, sel_obj, color=None):
  6589. """
  6590. :param sel_obj: the object for which the hover shape must be drawn
  6591. :return:
  6592. """
  6593. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6594. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6595. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6596. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6597. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  6598. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6599. hover_rect = hover_rect.buffer(-0.1)
  6600. hover_rect = hover_rect.buffer(0.2)
  6601. else:
  6602. hover_rect = hover_rect.buffer(-0.00393)
  6603. hover_rect = hover_rect.buffer(0.00787)
  6604. if color:
  6605. face = Color(color)
  6606. face.alpha = 0.2
  6607. outline = Color(color, alpha=0.8)
  6608. else:
  6609. face = Color(self.defaults['global_sel_fill'])
  6610. face.alpha = 0.2
  6611. outline = self.defaults['global_sel_line']
  6612. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  6613. def delete_selection_shape(self):
  6614. self.move_tool.sel_shapes.clear()
  6615. self.move_tool.sel_shapes.redraw()
  6616. def draw_selection_shape(self, sel_obj, color=None):
  6617. """
  6618. :param sel_obj: the object for which the selection shape must be drawn
  6619. :return:
  6620. """
  6621. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6622. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6623. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6624. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6625. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6626. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6627. sel_rect = sel_rect.buffer(-0.1)
  6628. sel_rect = sel_rect.buffer(0.2)
  6629. else:
  6630. sel_rect = sel_rect.buffer(-0.00393)
  6631. sel_rect = sel_rect.buffer(0.00787)
  6632. if color:
  6633. face = Color(color, alpha=0.2)
  6634. outline = Color(color, alpha=0.8)
  6635. else:
  6636. face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  6637. outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  6638. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  6639. color=outline,
  6640. face_color=face,
  6641. update=True,
  6642. layer=0,
  6643. tolerance=None))
  6644. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  6645. """
  6646. :param old_coords: old coordinates
  6647. :param coords: new coordinates
  6648. :return:
  6649. """
  6650. if 'color' in kwargs:
  6651. color = kwargs['color']
  6652. else:
  6653. color = self.defaults['global_sel_line']
  6654. if 'face_color' in kwargs:
  6655. face_color = kwargs['face_color']
  6656. else:
  6657. face_color = self.defaults['global_sel_fill']
  6658. if 'face_alpha' in kwargs:
  6659. face_alpha = kwargs['face_alpha']
  6660. else:
  6661. face_alpha = 0.3
  6662. x0, y0 = old_coords
  6663. x1, y1 = coords
  6664. pt1 = (x0, y0)
  6665. pt2 = (x1, y0)
  6666. pt3 = (x1, y1)
  6667. pt4 = (x0, y1)
  6668. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6669. color_t = Color(face_color)
  6670. color_t.alpha = face_alpha
  6671. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  6672. layer=0, tolerance=None)
  6673. def on_file_new_click(self):
  6674. if self.collection.get_list() and self.should_we_save:
  6675. msgbox = QtWidgets.QMessageBox()
  6676. # msgbox.setText("<B>Save changes ...</B>")
  6677. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  6678. "Creating a New project will delete them.\n"
  6679. "Do you want to Save the project?"))
  6680. msgbox.setWindowTitle(_("Save changes"))
  6681. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6682. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6683. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6684. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6685. msgbox.setDefaultButton(bt_yes)
  6686. msgbox.exec_()
  6687. response = msgbox.clickedButton()
  6688. if response == bt_yes:
  6689. self.on_file_saveprojectas()
  6690. elif response == bt_cancel:
  6691. return
  6692. elif response == bt_no:
  6693. self.on_file_new()
  6694. else:
  6695. self.on_file_new()
  6696. self.inform.emit('[success] %s...' %
  6697. _("New Project created"))
  6698. def on_file_new(self, cli=None):
  6699. """
  6700. Callback for menu item File->New. Returns the application to its
  6701. startup state. This method is thread-safe.
  6702. :return: None
  6703. """
  6704. self.report_usage("on_file_new")
  6705. # Remove everything from memory
  6706. App.log.debug("on_file_new()")
  6707. if self.call_source != 'app':
  6708. self.editor2object(cleanup=True)
  6709. # ## EDITOR section
  6710. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  6711. self.exc_editor = FlatCAMExcEditor(self)
  6712. self.grb_editor = FlatCAMGrbEditor(self)
  6713. # Clear pool
  6714. self.clear_pool()
  6715. for obj in self.collection.get_list():
  6716. # delete shapes left drawn from mark shape_collections, if any
  6717. if isinstance(obj, FlatCAMGerber):
  6718. try:
  6719. obj.mark_shapes.enabled = False
  6720. obj.mark_shapes.clear(update=True)
  6721. except AttributeError:
  6722. pass
  6723. # also delete annotation shapes, if any
  6724. elif isinstance(obj, FlatCAMCNCjob):
  6725. try:
  6726. obj.annotation.enabled = False
  6727. obj.annotation.clear(update=True)
  6728. except AttributeError:
  6729. pass
  6730. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6731. self.init_tcl()
  6732. self.delete_selection_shape()
  6733. self.collection.delete_all()
  6734. self.setup_component_editor()
  6735. # Clear project filename
  6736. self.project_filename = None
  6737. # Load the application defaults
  6738. self.load_defaults(filename='current_defaults')
  6739. # Re-fresh project options
  6740. self.on_options_app2project()
  6741. # Init Tools
  6742. self.init_tools()
  6743. if cli is None:
  6744. # Close any Tabs opened in the Plot Tab Area section
  6745. for index in range(self.ui.plot_tab_area.count()):
  6746. self.ui.plot_tab_area.closeTab(index)
  6747. # for whatever reason previous command does not close the last tab so I do it manually
  6748. self.ui.plot_tab_area.closeTab(0)
  6749. # # And then add again the Plot Area
  6750. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  6751. self.ui.plot_tab_area.protectTab(0)
  6752. # take the focus of the Notebook on Project Tab.
  6753. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6754. self.set_ui_title(name=_("New Project - Not saved"))
  6755. def obj_properties(self):
  6756. self.report_usage("obj_properties()")
  6757. self.properties_tool.run(toggle=False)
  6758. def on_project_context_save(self):
  6759. obj = self.collection.get_active()
  6760. if type(obj) == FlatCAMGeometry:
  6761. self.on_file_exportdxf()
  6762. elif type(obj) == FlatCAMExcellon:
  6763. self.on_file_saveexcellon()
  6764. elif type(obj) == FlatCAMCNCjob:
  6765. obj.on_exportgcode_button_click()
  6766. elif type(obj) == FlatCAMGerber:
  6767. self.on_file_savegerber()
  6768. def obj_move(self):
  6769. self.report_usage("obj_move()")
  6770. self.move_tool.run(toggle=False)
  6771. def on_fileopengerber(self, checked=None, name=None):
  6772. """
  6773. File menu callback for opening a Gerber.
  6774. :return: None
  6775. """
  6776. self.report_usage("on_fileopengerber")
  6777. App.log.debug("on_fileopengerber()")
  6778. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6779. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6780. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  6781. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6782. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6783. "*.mil);;" \
  6784. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6785. "Allegro Files (*.art);;" \
  6786. "Mentor Files (*.pho *.gdo);;" \
  6787. "All Files (*.*)"
  6788. if name is None:
  6789. try:
  6790. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6791. directory=self.get_last_folder(),
  6792. filter=_filter_)
  6793. except TypeError:
  6794. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6795. filenames = [str(filename) for filename in filenames]
  6796. else:
  6797. filenames = [name]
  6798. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6799. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6800. _("Opening Gerber file.")),
  6801. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6802. color=QtGui.QColor("gray"))
  6803. if len(filenames) == 0:
  6804. self.inform.emit('[WARNING_NOTCL] %s' %
  6805. _("Open Gerber cancelled."))
  6806. else:
  6807. for filename in filenames:
  6808. if filename != '':
  6809. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6810. def on_fileopenexcellon(self, checked=None, name=None):
  6811. """
  6812. File menu callback for opening an Excellon file.
  6813. :return: None
  6814. """
  6815. self.report_usage("on_fileopenexcellon")
  6816. App.log.debug("on_fileopenexcellon()")
  6817. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6818. "All Files (*.*)"
  6819. if name is None:
  6820. try:
  6821. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6822. directory=self.get_last_folder(),
  6823. filter=_filter_)
  6824. except TypeError:
  6825. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6826. filenames = [str(filename) for filename in filenames]
  6827. else:
  6828. filenames = [str(name)]
  6829. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6830. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6831. _("Opening Excellon file.")),
  6832. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6833. color=QtGui.QColor("gray"))
  6834. if len(filenames) == 0:
  6835. self.inform.emit('[WARNING_NOTCL]%s' %
  6836. _(" Open Excellon cancelled."))
  6837. else:
  6838. for filename in filenames:
  6839. if filename != '':
  6840. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6841. def on_fileopengcode(self, checked=None, name=None):
  6842. """
  6843. File menu call back for opening gcode.
  6844. :return: None
  6845. """
  6846. self.report_usage("on_fileopengcode")
  6847. App.log.debug("on_fileopengcode()")
  6848. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6849. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6850. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  6851. "All Files (*.*)"
  6852. if name is None:
  6853. try:
  6854. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6855. directory=self.get_last_folder(),
  6856. filter=_filter_)
  6857. except TypeError:
  6858. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6859. filenames = [str(filename) for filename in filenames]
  6860. else:
  6861. filenames = [name]
  6862. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6863. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6864. _("Opening G-Code file.")),
  6865. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6866. color=QtGui.QColor("gray"))
  6867. if len(filenames) == 0:
  6868. self.inform.emit('[WARNING_NOTCL] %s' %
  6869. _("Open G-Code cancelled."))
  6870. else:
  6871. for filename in filenames:
  6872. if filename != '':
  6873. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename]})
  6874. def on_file_openproject(self, checked=None):
  6875. """
  6876. File menu callback for opening a project.
  6877. :return: None
  6878. """
  6879. self.report_usage("on_file_openproject")
  6880. App.log.debug("on_file_openproject()")
  6881. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6882. try:
  6883. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6884. directory=self.get_last_folder(), filter=_filter_)
  6885. except TypeError:
  6886. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6887. # The Qt methods above will return a QString which can cause problems later.
  6888. # So far json.dump() will fail to serialize it.
  6889. # TODO: Improve the serialization methods and remove this fix.
  6890. filename = str(filename)
  6891. if filename == "":
  6892. self.inform.emit('[WARNING_NOTCL] %s' %
  6893. _("Open Project cancelled."))
  6894. else:
  6895. # self.worker_task.emit({'fcn': self.open_project,
  6896. # 'params': [filename]})
  6897. # The above was failing because open_project() is not
  6898. # thread safe. The new_project()
  6899. self.open_project(filename)
  6900. def on_file_openconfig(self, checked=None):
  6901. """
  6902. File menu callback for opening a config file.
  6903. :return: None
  6904. """
  6905. self.report_usage("on_file_openconfig")
  6906. App.log.debug("on_file_openconfig()")
  6907. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6908. try:
  6909. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6910. directory=self.data_path, filter=_filter_)
  6911. except TypeError:
  6912. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6913. filter=_filter_)
  6914. if filename == "":
  6915. self.inform.emit('[WARNING_NOTCL] %s' %
  6916. _("Open Config cancelled."))
  6917. else:
  6918. self.open_config_file(filename)
  6919. def on_file_exportsvg(self):
  6920. """
  6921. Callback for menu item File->Export SVG.
  6922. :return: None
  6923. """
  6924. self.report_usage("on_file_exportsvg")
  6925. App.log.debug("on_file_exportsvg()")
  6926. obj = self.collection.get_active()
  6927. if obj is None:
  6928. self.inform.emit('[WARNING_NOTCL] %s' %
  6929. _("No object selected."))
  6930. msg = _("Please Select a Geometry object to export")
  6931. msgbox = QtWidgets.QMessageBox()
  6932. msgbox.setInformativeText(msg)
  6933. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6934. msgbox.setDefaultButton(bt_ok)
  6935. msgbox.exec_()
  6936. return
  6937. # Check for more compatible types and add as required
  6938. if (not isinstance(obj, FlatCAMGeometry)
  6939. and not isinstance(obj, FlatCAMGerber)
  6940. and not isinstance(obj, FlatCAMCNCjob)
  6941. and not isinstance(obj, FlatCAMExcellon)):
  6942. msg = '[ERROR_NOTCL] %s' % \
  6943. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6944. msgbox = QtWidgets.QMessageBox()
  6945. msgbox.setInformativeText(msg)
  6946. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6947. msgbox.setDefaultButton(bt_ok)
  6948. msgbox.exec_()
  6949. return
  6950. name = obj.options["name"]
  6951. _filter = "SVG File (*.svg);;All Files (*.*)"
  6952. try:
  6953. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6954. caption=_("Export SVG"),
  6955. directory=self.get_last_save_folder() + '/' + str(name),
  6956. filter=_filter)
  6957. except TypeError:
  6958. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  6959. filename = str(filename)
  6960. if filename == "":
  6961. self.inform.emit('[WARNING_NOTCL]%s' %
  6962. _(" Export SVG cancelled."))
  6963. return
  6964. else:
  6965. self.export_svg(name, filename)
  6966. if self.defaults["global_open_style"] is False:
  6967. self.file_opened.emit("SVG", filename)
  6968. self.file_saved.emit("SVG", filename)
  6969. def on_file_exportpng(self):
  6970. self.report_usage("on_file_exportpng")
  6971. App.log.debug("on_file_exportpng()")
  6972. self.date = str(datetime.today()).rpartition('.')[0]
  6973. self.date = ''.join(c for c in self.date if c not in ':-')
  6974. self.date = self.date.replace(' ', '_')
  6975. image = _screenshot()
  6976. data = np.asarray(image)
  6977. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6978. self.inform.emit('[[WARNING_NOTCL]] %s' %
  6979. _('Data must be a 3D array with last dimension 3 or 4'))
  6980. return
  6981. filter_ = "PNG File (*.png);;All Files (*.*)"
  6982. try:
  6983. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6984. caption=_("Export PNG Image"),
  6985. directory=self.get_last_save_folder() + '/png_' + self.date,
  6986. filter=filter_)
  6987. except TypeError:
  6988. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  6989. filename = str(filename)
  6990. if filename == "":
  6991. self.inform.emit(_("Export PNG cancelled."))
  6992. return
  6993. else:
  6994. write_png(filename, data)
  6995. if self.defaults["global_open_style"] is False:
  6996. self.file_opened.emit("png", filename)
  6997. self.file_saved.emit("png", filename)
  6998. def on_file_savegerber(self):
  6999. """
  7000. Callback for menu item in Project context menu.
  7001. :return: None
  7002. """
  7003. self.report_usage("on_file_savegerber")
  7004. App.log.debug("on_file_savegerber()")
  7005. obj = self.collection.get_active()
  7006. if obj is None:
  7007. self.inform.emit('[WARNING_NOTCL] %s' %
  7008. _("No object selected. Please select an Gerber object to export."))
  7009. return
  7010. # Check for more compatible types and add as required
  7011. if not isinstance(obj, FlatCAMGerber):
  7012. self.inform.emit('[ERROR_NOTCL] %s' %
  7013. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7014. return
  7015. name = self.collection.get_active().options["name"]
  7016. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  7017. try:
  7018. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7019. caption="Save Gerber source file",
  7020. directory=self.get_last_save_folder() + '/' + name,
  7021. filter=_filter)
  7022. except TypeError:
  7023. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  7024. filename = str(filename)
  7025. if filename == "":
  7026. self.inform.emit('[WARNING_NOTCL] %s' %
  7027. _("Save Gerber source file cancelled."))
  7028. return
  7029. else:
  7030. self.save_source_file(name, filename)
  7031. if self.defaults["global_open_style"] is False:
  7032. self.file_opened.emit("Gerber", filename)
  7033. self.file_saved.emit("Gerber", filename)
  7034. def on_file_saveexcellon(self):
  7035. """
  7036. Callback for menu item in project context menu.
  7037. :return: None
  7038. """
  7039. self.report_usage("on_file_saveexcellon")
  7040. App.log.debug("on_file_saveexcellon()")
  7041. obj = self.collection.get_active()
  7042. if obj is None:
  7043. self.inform.emit('[WARNING_NOTCL] %s' %
  7044. _("No object selected. Please select an Excellon object to export."))
  7045. return
  7046. # Check for more compatible types and add as required
  7047. if not isinstance(obj, FlatCAMExcellon):
  7048. self.inform.emit('[ERROR_NOTCL] %s' %
  7049. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7050. return
  7051. name = self.collection.get_active().options["name"]
  7052. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7053. try:
  7054. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7055. caption=_("Save Excellon source file"),
  7056. directory=self.get_last_save_folder() + '/' + name,
  7057. filter=_filter)
  7058. except TypeError:
  7059. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  7060. filename = str(filename)
  7061. if filename == "":
  7062. self.inform.emit('[WARNING_NOTCL] %s' %
  7063. _("Saving Excellon source file cancelled."))
  7064. return
  7065. else:
  7066. self.save_source_file(name, filename)
  7067. if self.defaults["global_open_style"] is False:
  7068. self.file_opened.emit("Excellon", filename)
  7069. self.file_saved.emit("Excellon", filename)
  7070. def on_file_exportexcellon(self):
  7071. """
  7072. Callback for menu item File->Export->Excellon.
  7073. :return: None
  7074. """
  7075. self.report_usage("on_file_exportexcellon")
  7076. App.log.debug("on_file_exportexcellon()")
  7077. obj = self.collection.get_active()
  7078. if obj is None:
  7079. self.inform.emit('[WARNING_NOTCL] %s' %
  7080. _("No object selected. Please Select an Excellon object to export."))
  7081. return
  7082. # Check for more compatible types and add as required
  7083. if not isinstance(obj, FlatCAMExcellon):
  7084. self.inform.emit('[ERROR_NOTCL] %s' %
  7085. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7086. return
  7087. name = self.collection.get_active().options["name"]
  7088. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7089. try:
  7090. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7091. caption=_("Export Excellon"),
  7092. directory=self.get_last_save_folder() + '/' + name,
  7093. filter=_filter)
  7094. except TypeError:
  7095. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  7096. filename = str(filename)
  7097. if filename == "":
  7098. self.inform.emit('[WARNING_NOTCL] %s' %
  7099. _("Export Excellon cancelled."))
  7100. return
  7101. else:
  7102. self.export_excellon(name, filename)
  7103. if self.defaults["global_open_style"] is False:
  7104. self.file_opened.emit("Excellon", filename)
  7105. self.file_saved.emit("Excellon", filename)
  7106. def on_file_exportgerber(self):
  7107. """
  7108. Callback for menu item File->Export->Gerber.
  7109. :return: None
  7110. """
  7111. self.report_usage("on_file_exportgerber")
  7112. App.log.debug("on_file_exportgerber()")
  7113. obj = self.collection.get_active()
  7114. if obj is None:
  7115. self.inform.emit('[WARNING_NOTCL] %s' %
  7116. _("No object selected. Please Select an Gerber object to export."))
  7117. return
  7118. # Check for more compatible types and add as required
  7119. if not isinstance(obj, FlatCAMGerber):
  7120. self.inform.emit('[ERROR_NOTCL] %s' %
  7121. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7122. return
  7123. name = self.collection.get_active().options["name"]
  7124. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  7125. try:
  7126. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7127. caption=_("Export Gerber"),
  7128. directory=self.get_last_save_folder() + '/' + name,
  7129. filter=_filter_)
  7130. except TypeError:
  7131. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  7132. filename = str(filename)
  7133. if filename == "":
  7134. self.inform.emit('[WARNING_NOTCL] %s' %
  7135. _("Export Gerber cancelled."))
  7136. return
  7137. else:
  7138. self.export_gerber(name, filename)
  7139. if self.defaults["global_open_style"] is False:
  7140. self.file_opened.emit("Gerber", filename)
  7141. self.file_saved.emit("Gerber", filename)
  7142. def on_file_exportdxf(self):
  7143. """
  7144. Callback for menu item File->Export DXF.
  7145. :return: None
  7146. """
  7147. self.report_usage("on_file_exportdxf")
  7148. App.log.debug("on_file_exportdxf()")
  7149. obj = self.collection.get_active()
  7150. if obj is None:
  7151. self.inform.emit('[WARNING_NOTCL] %s' %
  7152. _("No object selected."))
  7153. msg = _("Please Select a Geometry object to export")
  7154. msgbox = QtWidgets.QMessageBox()
  7155. msgbox.setInformativeText(msg)
  7156. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7157. msgbox.setDefaultButton(bt_ok)
  7158. msgbox.exec_()
  7159. return
  7160. # Check for more compatible types and add as required
  7161. if not isinstance(obj, FlatCAMGeometry):
  7162. msg = '[ERROR_NOTCL] %s' % \
  7163. _("Only Geometry objects can be used.")
  7164. msgbox = QtWidgets.QMessageBox()
  7165. msgbox.setInformativeText(msg)
  7166. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7167. msgbox.setDefaultButton(bt_ok)
  7168. msgbox.exec_()
  7169. return
  7170. name = self.collection.get_active().options["name"]
  7171. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7172. try:
  7173. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7174. caption=_("Export DXF"),
  7175. directory=self.get_last_save_folder() + '/' + name,
  7176. filter=_filter_)
  7177. except TypeError:
  7178. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  7179. filter=_filter_)
  7180. filename = str(filename)
  7181. if filename == "":
  7182. self.inform.emit('[WARNING_NOTCL] %s' %
  7183. _("Export DXF cancelled."))
  7184. return
  7185. else:
  7186. self.export_dxf(name, filename)
  7187. if self.defaults["global_open_style"] is False:
  7188. self.file_opened.emit("DXF", filename)
  7189. self.file_saved.emit("DXF", filename)
  7190. def on_file_importsvg(self, type_of_obj):
  7191. """
  7192. Callback for menu item File->Import SVG.
  7193. :param type_of_obj: to import the SVG as Geometry or as Gerber
  7194. :type type_of_obj: str
  7195. :return: None
  7196. """
  7197. self.report_usage("on_file_importsvg")
  7198. App.log.debug("on_file_importsvg()")
  7199. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  7200. try:
  7201. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7202. directory=self.get_last_folder(), filter=_filter_)
  7203. except TypeError:
  7204. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7205. filter=_filter_)
  7206. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7207. type_of_obj = "geometry"
  7208. filenames = [str(filename) for filename in filenames]
  7209. if len(filenames) == 0:
  7210. self.inform.emit('[WARNING_NOTCL] %s' %
  7211. _("Open SVG cancelled."))
  7212. else:
  7213. for filename in filenames:
  7214. if filename != '':
  7215. self.worker_task.emit({'fcn': self.import_svg,
  7216. 'params': [filename, type_of_obj]})
  7217. def on_file_importdxf(self, type_of_obj):
  7218. """
  7219. Callback for menu item File->Import DXF.
  7220. :param type_of_obj: to import the DXF as Geometry or as Gerber
  7221. :type type_of_obj: str
  7222. :return: None
  7223. """
  7224. self.report_usage("on_file_importdxf")
  7225. App.log.debug("on_file_importdxf()")
  7226. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7227. try:
  7228. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7229. directory=self.get_last_folder(),
  7230. filter=_filter_)
  7231. except TypeError:
  7232. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7233. filter=_filter_)
  7234. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7235. type_of_obj = "geometry"
  7236. filenames = [str(filename) for filename in filenames]
  7237. if len(filenames) == 0:
  7238. self.inform.emit('[WARNING_NOTCL] %s' %
  7239. _("Open DXF cancelled."))
  7240. else:
  7241. for filename in filenames:
  7242. if filename != '':
  7243. self.worker_task.emit({'fcn': self.import_dxf,
  7244. 'params': [filename, type_of_obj]})
  7245. # ###############################################################################################################
  7246. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  7247. # ###############################################################################################################
  7248. def init_code_editor(self, name):
  7249. # Signals section
  7250. # Disconnect the old signals
  7251. try:
  7252. self.ui.buttonOpen.clicked.disconnect()
  7253. except TypeError:
  7254. pass
  7255. try:
  7256. self.ui.buttonSave.clicked.disconnect()
  7257. except TypeError:
  7258. pass
  7259. # add the tab if it was closed
  7260. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, '%s' % name)
  7261. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  7262. # delete the absolute and relative position and messages in the infobar
  7263. self.ui.position_label.setText("")
  7264. self.ui.rel_position_label.setText("")
  7265. # first clear previous text in text editor (if any)
  7266. self.ui.code_editor.clear()
  7267. self.ui.code_editor.setReadOnly(False)
  7268. self.toggle_codeeditor = True
  7269. self.ui.code_editor.completer_enable = False
  7270. self.ui.buttonRun.hide()
  7271. # make sure to keep a reference to the code editor
  7272. self.reference_code_editor = self.ui.code_editor
  7273. # Switch plot_area to CNCJob tab
  7274. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  7275. def on_view_source(self):
  7276. self.inform.emit('%s' %
  7277. _("Viewing the source code of the selected object."))
  7278. self.proc_container.view.set_busy(_("Loading..."))
  7279. try:
  7280. obj = self.collection.get_active()
  7281. except Exception as e:
  7282. log.debug("App.on_view_source() --> %s" % str(e))
  7283. self.inform.emit('[WARNING_NOTCL] %s' %
  7284. _("Select an Gerber or Excellon file to view it's source file."))
  7285. return 'fail'
  7286. if obj.kind == 'gerber':
  7287. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  7288. elif obj.kind == 'excellon':
  7289. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  7290. elif obj.kind == 'cncjob':
  7291. "GCode Files (*.NC);;All Files (*.*)"
  7292. else:
  7293. flt = "All Files (*.*)"
  7294. self.init_code_editor(name=_("Source Editor"))
  7295. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  7296. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  7297. # then append the text from GCode to the text editor
  7298. if obj.kind == 'cncjob':
  7299. try:
  7300. file = obj.export_gcode(
  7301. preamble=self.defaults["cncjob_prepend"],
  7302. postamble=self.defaults["cncjob_append"],
  7303. to_file=True)
  7304. if file == 'fail':
  7305. return 'fail'
  7306. except AttributeError:
  7307. self.inform.emit('[WARNING_NOTCL] %s' %
  7308. _("There is no selected object for which to see it's source file code."))
  7309. return 'fail'
  7310. else:
  7311. try:
  7312. file = StringIO(obj.source_file)
  7313. except AttributeError:
  7314. self.inform.emit('[WARNING_NOTCL] %s' %
  7315. _("There is no selected object for which to see it's source file code."))
  7316. return 'fail'
  7317. self.ui.cncjob_frame.hide()
  7318. try:
  7319. for line in file:
  7320. QtWidgets.QApplication.processEvents()
  7321. proc_line = str(line).strip('\n')
  7322. self.ui.code_editor.append(proc_line)
  7323. except Exception as e:
  7324. log.debug('App.on_view_source() -->%s' % str(e))
  7325. self.inform.emit('[ERROR] %s: %s' %
  7326. (_('Failed to load the source code for the selected object'), str(e)))
  7327. return
  7328. self.handleTextChanged()
  7329. self.ui.cncjob_frame.show()
  7330. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7331. self.proc_container.view.set_idle()
  7332. # self.ui.show()
  7333. def on_toggle_code_editor(self):
  7334. self.report_usage("on_toggle_code_editor()")
  7335. if self.toggle_codeeditor is False:
  7336. self.init_code_editor(name=_("Code Editor"))
  7337. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  7338. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  7339. else:
  7340. for idx in range(self.ui.plot_tab_area.count()):
  7341. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  7342. self.ui.plot_tab_area.closeTab(idx)
  7343. break
  7344. self.toggle_codeeditor = False
  7345. def on_filenewscript(self, silent=False):
  7346. """
  7347. Will create a new script file and open it in the Code Editor
  7348. :param silent: if True will not display status messages
  7349. :return: None
  7350. """
  7351. if silent is False:
  7352. self.inform.emit('[success] %s' %
  7353. _("New TCL script file created in Code Editor."))
  7354. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  7355. self.init_code_editor(name=_("Script Editor"))
  7356. self.ui.code_editor.completer_enable = True
  7357. self.ui.code_editor.append(_(
  7358. "#\n"
  7359. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  7360. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  7361. "#\n\n"
  7362. "# FlatCAM commands list:\n"
  7363. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, ClearCopper,\n"
  7364. "# Cncjob, Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, GetNames,\n"
  7365. "# GetSys, ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillDrills,\n"
  7366. "# MillSlots, Mirror, New, NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"
  7367. "# Options, Paint, Panelize, Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, SubtractPoly,\n"
  7368. "# SubtractRectangle, Version, WriteGCode\n"
  7369. "#\n\n"
  7370. ))
  7371. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  7372. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  7373. self.ui.buttonRun.show()
  7374. try:
  7375. self.ui.buttonRun.clicked.disconnect(self.handleRunCode)
  7376. except TypeError:
  7377. pass
  7378. self.ui.buttonRun.clicked.connect(self.handleRunCode)
  7379. self.handleTextChanged()
  7380. self.ui.code_editor.show()
  7381. def on_fileopenscript(self, name=None, silent=False):
  7382. """
  7383. Will open a Tcl script file into the Code Editor
  7384. :param silent: if True will not display status messages
  7385. :param name: name of a Tcl script file to open
  7386. :return:
  7387. """
  7388. if name:
  7389. filename = name
  7390. else:
  7391. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7392. try:
  7393. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  7394. directory=self.get_last_folder(), filter=_filter_)
  7395. except TypeError:
  7396. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  7397. # The Qt methods above will return a QString which can cause problems later.
  7398. # So far json.dump() will fail to serialize it.
  7399. # TODO: Improve the serialization methods and remove this fix.
  7400. filename = str(filename)
  7401. if filename == "":
  7402. if silent is False:
  7403. self.inform.emit('[WARNING_NOTCL] %s' %
  7404. _("Open TCL script cancelled."))
  7405. else:
  7406. self.on_filenewscript()
  7407. try:
  7408. with open(filename, "r") as opened_script:
  7409. try:
  7410. for line in opened_script:
  7411. proc_line = str(line).strip('\n')
  7412. self.ui.code_editor.append(proc_line)
  7413. except Exception as e:
  7414. log.debug('App.on_fileopenscript() -->%s' % str(e))
  7415. if silent is False:
  7416. self.inform.emit('[ERROR] %s %s' %
  7417. (_('App.on_fileopenscript() -->'), str(e)))
  7418. return
  7419. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7420. self.handleTextChanged()
  7421. if silent is False:
  7422. self.inform.emit('[success] %s' %
  7423. _("TCL script file opened in Code Editor."))
  7424. # self.ui.show()
  7425. except Exception as e:
  7426. log.debug("App.on_fileopenscript() -> %s" % str(e))
  7427. def on_filerunscript(self, name=None, silent=False):
  7428. """
  7429. File menu callback for loading and running a TCL script.
  7430. :param silent: if True will not display status messages
  7431. :param name: name of a Tcl script file to be run by FlatCAM
  7432. :return: None
  7433. """
  7434. self.report_usage("on_filerunscript")
  7435. App.log.debug("on_file_runscript()")
  7436. if name:
  7437. filename = name
  7438. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7439. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7440. _("Executing FlatCAMScript file.")),
  7441. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7442. color=QtGui.QColor("gray"))
  7443. else:
  7444. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7445. try:
  7446. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  7447. directory=self.get_last_folder(), filter=_filter_)
  7448. except TypeError:
  7449. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  7450. # The Qt methods above will return a QString which can cause problems later.
  7451. # So far json.dump() will fail to serialize it.
  7452. # TODO: Improve the serialization methods and remove this fix.
  7453. filename = str(filename)
  7454. if filename == "":
  7455. if silent is False:
  7456. self.inform.emit('[WARNING_NOTCL] %s' %
  7457. _("Run TCL script cancelled."))
  7458. else:
  7459. if self.ui.shell_dock.isHidden():
  7460. self.ui.shell_dock.show()
  7461. try:
  7462. with open(filename, "r") as tcl_script:
  7463. cmd_line_shellfile_content = tcl_script.read()
  7464. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  7465. if silent is False:
  7466. self.inform.emit('[success] %s' %
  7467. _("TCL script file opened in Code Editor and executed."))
  7468. except Exception as e:
  7469. log.debug("App.on_filerunscript() -> %s" % str(e))
  7470. sys.exit(2)
  7471. def on_file_saveproject(self, silent=False):
  7472. """
  7473. Callback for menu item File->Save Project. Saves the project to
  7474. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7475. if set to None. The project is saved by calling ``self.save_project()``.
  7476. :param silent: if True will not display status messages
  7477. :return: None
  7478. """
  7479. self.report_usage("on_file_saveproject")
  7480. if self.project_filename is None:
  7481. self.on_file_saveprojectas()
  7482. else:
  7483. self.worker_task.emit({'fcn': self.save_project,
  7484. 'params': [self.project_filename, silent]})
  7485. if self.defaults["global_open_style"] is False:
  7486. self.file_opened.emit("project", self.project_filename)
  7487. self.file_saved.emit("project", self.project_filename)
  7488. self.set_ui_title(name=self.project_filename)
  7489. self.should_we_save = False
  7490. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7491. """
  7492. Callback for menu item File->Save Project As... Opens a file
  7493. chooser and saves the project to the given file via
  7494. ``self.save_project()``.
  7495. :param make_copy if to be create a copy of the project; boolean
  7496. :param use_thread: if to be run in a separate thread; boolean
  7497. :param quit_action: if to be followed by quiting the application; boolean
  7498. :return: None
  7499. """
  7500. self.report_usage("on_file_saveprojectas")
  7501. self.date = str(datetime.today()).rpartition('.')[0]
  7502. self.date = ''.join(c for c in self.date if c not in ':-')
  7503. self.date = self.date.replace(' ', '_')
  7504. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  7505. try:
  7506. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7507. caption=_("Save Project As ..."),
  7508. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  7509. filter=filter_)
  7510. except TypeError:
  7511. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  7512. filename = str(filename)
  7513. if filename == '':
  7514. self.inform.emit('[WARNING_NOTCL] %s' %
  7515. _("Save Project cancelled."))
  7516. return
  7517. try:
  7518. f = open(filename, 'r')
  7519. f.close()
  7520. except IOError:
  7521. pass
  7522. if use_thread is True:
  7523. self.worker_task.emit({'fcn': self.save_project,
  7524. 'params': [filename, quit_action]})
  7525. else:
  7526. self.save_project(filename, quit_action)
  7527. # self.save_project(filename)
  7528. if self.defaults["global_open_style"] is False:
  7529. self.file_opened.emit("project", filename)
  7530. self.file_saved.emit("project", filename)
  7531. if not make_copy:
  7532. self.project_filename = filename
  7533. self.set_ui_title(name=self.project_filename)
  7534. self.should_we_save = False
  7535. def export_svg(self, obj_name, filename, scale_factor=0.00):
  7536. """
  7537. Exports a Geometry Object to an SVG file.
  7538. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7539. :param filename: Path to the SVG file to save to.
  7540. :param scale_factor: factor by which to change/scale the thickness of the features
  7541. :return:
  7542. """
  7543. self.report_usage("export_svg()")
  7544. if filename is None:
  7545. filename = self.defaults["global_last_save_folder"]
  7546. self.log.debug("export_svg()")
  7547. try:
  7548. obj = self.collection.get_by_name(str(obj_name))
  7549. except:
  7550. # TODO: The return behavior has not been established... should raise exception?
  7551. return "Could not retrieve object: %s" % obj_name
  7552. with self.proc_container.new(_("Exporting SVG")) as proc:
  7553. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7554. # Determine bounding area for svg export
  7555. bounds = obj.bounds()
  7556. size = obj.size()
  7557. # Convert everything to strings for use in the xml doc
  7558. svgwidth = str(size[0])
  7559. svgheight = str(size[1])
  7560. minx = str(bounds[0])
  7561. miny = str(bounds[1] - size[1])
  7562. uom = obj.units.lower()
  7563. # Add a SVG Header and footer to the svg output from shapely
  7564. # The transform flips the Y Axis so that everything renders
  7565. # properly within svg apps such as inkscape
  7566. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7567. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7568. svg_header += 'width="' + svgwidth + uom + '" '
  7569. svg_header += 'height="' + svgheight + uom + '" '
  7570. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7571. svg_header += '<g transform="scale(1,-1)">'
  7572. svg_footer = '</g> </svg>'
  7573. svg_elem = svg_header + exported_svg + svg_footer
  7574. # Parse the xml through a xml parser just to add line feeds
  7575. # and to make it look more pretty for the output
  7576. svgcode = parse_xml_string(svg_elem)
  7577. try:
  7578. with open(filename, 'w') as fp:
  7579. fp.write(svgcode.toprettyxml())
  7580. except PermissionError:
  7581. self.inform.emit('[WARNING] %s' %
  7582. _("Permission denied, saving not possible.\n"
  7583. "Most likely another app is holding the file open and not accessible."))
  7584. return 'fail'
  7585. if self.defaults["global_open_style"] is False:
  7586. self.file_opened.emit("SVG", filename)
  7587. self.file_saved.emit("SVG", filename)
  7588. self.inform.emit('[success] %s: %s' %
  7589. (_("SVG file exported to"), filename))
  7590. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  7591. """
  7592. Exports a Geometry Object to an SVG file in negative.
  7593. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7594. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  7595. :param filename: Path to the SVG file to save to.
  7596. :param boundary: thickness of a black border to surround all the features
  7597. :param scale_factor: factor by which to change/scale the thickness of the features
  7598. :param use_thread: if to be run in a separate thread; boolean
  7599. :return:
  7600. """
  7601. self.report_usage("export_negative()")
  7602. if filename is None:
  7603. filename = self.defaults["global_last_save_folder"]
  7604. self.log.debug("export_svg() negative")
  7605. try:
  7606. obj = self.collection.get_by_name(str(obj_name))
  7607. except:
  7608. # TODO: The return behavior has not been established... should raise exception?
  7609. return "Could not retrieve object: %s" % obj_name
  7610. try:
  7611. box = self.collection.get_by_name(str(box_name))
  7612. except:
  7613. # TODO: The return behavior has not been established... should raise exception?
  7614. return "Could not retrieve object: %s" % box_name
  7615. if box is None:
  7616. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  7617. (_("No object Box. Using instead"), obj))
  7618. box = obj
  7619. def make_negative_film():
  7620. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7621. # Determine bounding area for svg export
  7622. bounds = box.bounds()
  7623. size = box.size()
  7624. uom = obj.units.lower()
  7625. # Convert everything to strings for use in the xml doc
  7626. svgwidth = str(size[0] + (2 * boundary))
  7627. svgheight = str(size[1] + (2 * boundary))
  7628. minx = str(bounds[0] - boundary)
  7629. miny = str(bounds[1] + boundary + size[1])
  7630. miny_rect = str(bounds[1] - boundary)
  7631. # Add a SVG Header and footer to the svg output from shapely
  7632. # The transform flips the Y Axis so that everything renders
  7633. # properly within svg apps such as inkscape
  7634. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7635. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7636. svg_header += 'width="' + svgwidth + uom + '" '
  7637. svg_header += 'height="' + svgheight + uom + '" '
  7638. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7639. svg_header += '>'
  7640. svg_header += '<g transform="scale(1,-1)">'
  7641. svg_footer = '</g> </svg>'
  7642. # Change the attributes of the exported SVG
  7643. # We don't need stroke-width - wrong, we do when we have lines with certain width
  7644. # We set opacity to maximum
  7645. # We set the color to WHITE
  7646. root = ET.fromstring(exported_svg)
  7647. for child in root:
  7648. child.set('fill', '#FFFFFF')
  7649. child.set('opacity', '1.0')
  7650. child.set('stroke', '#FFFFFF')
  7651. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  7652. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  7653. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  7654. first_svg_elem_tag = 'rect'
  7655. first_svg_elem_attribs = {
  7656. 'x': minx,
  7657. 'y': miny_rect,
  7658. 'width': svgwidth,
  7659. 'height': svgheight,
  7660. 'id': 'neg_rect',
  7661. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  7662. }
  7663. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  7664. exported_svg = ET.tostring(root)
  7665. svg_elem = svg_header + str(exported_svg) + svg_footer
  7666. # Parse the xml through a xml parser just to add line feeds
  7667. # and to make it look more pretty for the output
  7668. doc = parse_xml_string(svg_elem)
  7669. try:
  7670. with open(filename, 'w') as fp:
  7671. fp.write(doc.toprettyxml())
  7672. except PermissionError:
  7673. self.inform.emit('[WARNING] %s' %
  7674. _("Permission denied, saving not possible.\n"
  7675. "Most likely another app is holding the file open and not accessible."))
  7676. return 'fail'
  7677. if self.defaults["global_open_style"] is False:
  7678. self.file_opened.emit("SVG", filename)
  7679. self.file_saved.emit("SVG", filename)
  7680. self.inform.emit('[success] %s: %s' %
  7681. (_("SVG file exported to"), filename))
  7682. if use_thread is True:
  7683. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  7684. def job_thread_film(app_obj):
  7685. try:
  7686. make_negative_film()
  7687. except Exception as e:
  7688. proc.done()
  7689. return
  7690. proc.done()
  7691. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  7692. else:
  7693. make_negative_film()
  7694. def export_svg_positive(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  7695. """
  7696. Exports a Geometry Object to an SVG file in positive black.
  7697. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7698. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  7699. :param filename: Path to the SVG file to save to.
  7700. :param scale_factor: factor by which to change/scale the thickness of the features
  7701. :param use_thread: if to be run in a separate thread; boolean
  7702. :return:
  7703. """
  7704. self.report_usage("export_svg_positive()")
  7705. if filename is None:
  7706. filename = self.defaults["global_last_save_folder"]
  7707. self.log.debug("export_svg() black")
  7708. try:
  7709. obj = self.collection.get_by_name(str(obj_name))
  7710. except:
  7711. # TODO: The return behavior has not been established... should raise exception?
  7712. return "Could not retrieve object: %s" % obj_name
  7713. try:
  7714. box = self.collection.get_by_name(str(box_name))
  7715. except:
  7716. # TODO: The return behavior has not been established... should raise exception?
  7717. return "Could not retrieve object: %s" % box_name
  7718. if box is None:
  7719. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  7720. (_("No object Box. Using instead"), obj))
  7721. box = obj
  7722. def make_positive_film():
  7723. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7724. self.progress.emit(40)
  7725. # Change the attributes of the exported SVG
  7726. # We don't need stroke-width
  7727. # We set opacity to maximum
  7728. # We set the colour to WHITE
  7729. root = ET.fromstring(exported_svg)
  7730. for child in root:
  7731. child.set('fill', str(self.defaults['tools_film_color']))
  7732. child.set('opacity', '1.0')
  7733. child.set('stroke', str(self.defaults['tools_film_color']))
  7734. exported_svg = ET.tostring(root)
  7735. # Determine bounding area for svg export
  7736. bounds = box.bounds()
  7737. size = box.size()
  7738. # This contain the measure units
  7739. uom = obj.units.lower()
  7740. # Define a boundary around SVG of about 1.0mm (~39mils)
  7741. if uom in "mm":
  7742. boundary = 1.0
  7743. else:
  7744. boundary = 0.0393701
  7745. self.progress.emit(80)
  7746. # Convert everything to strings for use in the xml doc
  7747. svgwidth = str(size[0] + (2 * boundary))
  7748. svgheight = str(size[1] + (2 * boundary))
  7749. minx = str(bounds[0] - boundary)
  7750. miny = str(bounds[1] + boundary + size[1])
  7751. self.log.debug(minx)
  7752. self.log.debug(miny)
  7753. # Add a SVG Header and footer to the svg output from shapely
  7754. # The transform flips the Y Axis so that everything renders
  7755. # properly within svg apps such as inkscape
  7756. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7757. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7758. svg_header += 'width="' + svgwidth + uom + '" '
  7759. svg_header += 'height="' + svgheight + uom + '" '
  7760. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7761. svg_header += '>'
  7762. svg_header += '<g transform="scale(1,-1)">'
  7763. svg_footer = '</g> </svg>'
  7764. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  7765. self.progress.emit(90)
  7766. # Parse the xml through a xml parser just to add line feeds
  7767. # and to make it look more pretty for the output
  7768. doc = parse_xml_string(svg_elem)
  7769. try:
  7770. with open(filename, 'w') as fp:
  7771. fp.write(doc.toprettyxml())
  7772. except PermissionError:
  7773. self.inform.emit('[WARNING] %s' %
  7774. _("Permission denied, saving not possible.\n"
  7775. "Most likely another app is holding the file open and not accessible."))
  7776. return 'fail'
  7777. self.progress.emit(100)
  7778. if self.defaults["global_open_style"] is False:
  7779. self.file_opened.emit("SVG", filename)
  7780. self.file_saved.emit("SVG", filename)
  7781. self.inform.emit('[success] %s: %s' %
  7782. (_("SVG file exported to"), filename))
  7783. if use_thread is True:
  7784. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  7785. def job_thread_film(app_obj):
  7786. try:
  7787. make_positive_film()
  7788. except Exception as e:
  7789. proc.done()
  7790. return
  7791. proc.done()
  7792. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  7793. else:
  7794. make_positive_film()
  7795. def save_source_file(self, obj_name, filename, use_thread=True):
  7796. """
  7797. Exports a FlatCAM Object to an Gerber/Excellon file.
  7798. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7799. :param filename: Path to the Gerber file to save to.
  7800. :param use_thread: if to be run in a separate thread
  7801. :return:
  7802. """
  7803. self.report_usage("save source file()")
  7804. if filename is None:
  7805. filename = self.defaults["global_last_save_folder"]
  7806. self.log.debug("save source file()")
  7807. obj = self.collection.get_by_name(obj_name)
  7808. file_string = StringIO(obj.source_file)
  7809. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7810. try:
  7811. with open(filename, 'w') as file:
  7812. file.writelines('G04*\n')
  7813. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7814. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7815. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7816. file.writelines('G04 Created on : %s*\n' % time_string)
  7817. for line in file_string:
  7818. file.writelines(line)
  7819. except PermissionError:
  7820. self.inform.emit('[WARNING] %s' %
  7821. _("Permission denied, saving not possible.\n"
  7822. "Most likely another app is holding the file open and not accessible."))
  7823. return 'fail'
  7824. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7825. """
  7826. Exports a Excellon Object to an Excellon file.
  7827. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7828. :param filename: Path to the Excellon file to save to.
  7829. :param use_thread: if to be run in a separate thread
  7830. :return:
  7831. """
  7832. self.report_usage("export_excellon()")
  7833. if filename is None:
  7834. filename = self.defaults["global_last_save_folder"]
  7835. self.log.debug("export_excellon()")
  7836. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7837. self.defaults["excellon_exp_decimals"]
  7838. )
  7839. units = ''
  7840. if local_use is None:
  7841. try:
  7842. obj = self.collection.get_by_name(str(obj_name))
  7843. except:
  7844. # TODO: The return behavior has not been established... should raise exception?
  7845. return "Could not retrieve object: %s" % obj_name
  7846. else:
  7847. obj = local_use
  7848. # updated units
  7849. eunits = self.defaults["excellon_exp_units"]
  7850. ewhole = self.defaults["excellon_exp_integer"]
  7851. efract = self.defaults["excellon_exp_decimals"]
  7852. ezeros = self.defaults["excellon_exp_zeros"]
  7853. eformat = self.defaults["excellon_exp_format"]
  7854. slot_type = self.defaults["excellon_exp_slot_type"]
  7855. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7856. if fc_units == 'MM':
  7857. factor = 1 if eunits == 'METRIC' else 0.03937
  7858. else:
  7859. factor = 25.4 if eunits == 'METRIC' else 1
  7860. def make_excellon():
  7861. try:
  7862. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7863. header = 'M48\n'
  7864. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7865. (str(self.version), str(self.version_date))
  7866. header += ';Filename: %s' % str(obj_name) + '\n'
  7867. header += ';Created on : %s' % time_str + '\n'
  7868. if eformat == 'dec':
  7869. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7870. header += eunits + '\n'
  7871. for tool in obj.tools:
  7872. if eunits == 'METRIC':
  7873. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7874. tool=str(tool),
  7875. dec=2)
  7876. else:
  7877. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7878. tool=str(tool),
  7879. dec=4)
  7880. else:
  7881. if ezeros == 'LZ':
  7882. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7883. form='ndec', e_zeros='LZ', factor=factor,
  7884. slot_type=slot_type)
  7885. header += '%s,%s\n' % (eunits, 'LZ')
  7886. header += format_exc
  7887. for tool in obj.tools:
  7888. if eunits == 'METRIC':
  7889. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7890. tool=str(tool),
  7891. dec=2)
  7892. else:
  7893. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7894. tool=str(tool),
  7895. dec=4)
  7896. else:
  7897. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7898. form='ndec', e_zeros='TZ', factor=factor,
  7899. slot_type=slot_type)
  7900. header += '%s,%s\n' % (eunits, 'TZ')
  7901. header += format_exc
  7902. for tool in obj.tools:
  7903. if eunits == 'METRIC':
  7904. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7905. tool=str(tool),
  7906. dec=2)
  7907. else:
  7908. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7909. tool=str(tool),
  7910. dec=4)
  7911. header += '%\n'
  7912. footer = 'M30\n'
  7913. exported_excellon = header
  7914. exported_excellon += excellon_code
  7915. exported_excellon += footer
  7916. if local_use is None:
  7917. try:
  7918. with open(filename, 'w') as fp:
  7919. fp.write(exported_excellon)
  7920. except PermissionError:
  7921. self.inform.emit('[WARNING] %s' %
  7922. _("Permission denied, saving not possible.\n"
  7923. "Most likely another app is holding the file open and not accessible."))
  7924. return 'fail'
  7925. if self.defaults["global_open_style"] is False:
  7926. self.file_opened.emit("Excellon", filename)
  7927. self.file_saved.emit("Excellon", filename)
  7928. self.inform.emit('[success] %s: %s' %
  7929. (_("Excellon file exported to"), filename))
  7930. else:
  7931. return exported_excellon
  7932. except Exception as e:
  7933. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7934. return 'fail'
  7935. if use_thread is True:
  7936. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7937. def job_thread_exc(app_obj):
  7938. ret = make_excellon()
  7939. if ret == 'fail':
  7940. self.inform.emit('[ERROR_NOTCL] %s' %
  7941. _('Could not export Excellon file.'))
  7942. return
  7943. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7944. else:
  7945. ret = make_excellon()
  7946. if ret == 'fail':
  7947. self.inform.emit('[ERROR_NOTCL] %s' %
  7948. _('Could not export Excellon file.'))
  7949. return 'fail'
  7950. if local_use is not None:
  7951. return ret
  7952. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7953. """
  7954. Exports a Gerber Object to an Gerber file.
  7955. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7956. :param filename: Path to the Gerber file to save to.
  7957. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7958. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7959. :param use_thread: if to be run in a separate thread
  7960. :return:
  7961. """
  7962. self.report_usage("export_gerber()")
  7963. if filename is None:
  7964. filename = self.defaults["global_last_save_folder"]
  7965. self.log.debug("export_gerber()")
  7966. if local_use is None:
  7967. try:
  7968. obj = self.collection.get_by_name(str(obj_name))
  7969. except:
  7970. # TODO: The return behavior has not been established... should raise exception?
  7971. return "Could not retrieve object: %s" % obj_name
  7972. else:
  7973. obj = local_use
  7974. # updated units
  7975. gunits = self.defaults["gerber_exp_units"]
  7976. gwhole = self.defaults["gerber_exp_integer"]
  7977. gfract = self.defaults["gerber_exp_decimals"]
  7978. gzeros = self.defaults["gerber_exp_zeros"]
  7979. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7980. if fc_units == 'MM':
  7981. factor = 1 if gunits == 'MM' else 0.03937
  7982. else:
  7983. factor = 25.4 if gunits == 'MM' else 1
  7984. def make_gerber():
  7985. try:
  7986. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7987. header = 'G04*\n'
  7988. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7989. (str(self.version), str(self.version_date))
  7990. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7991. header += 'G04 Created on : %s*' % time_str + '\n'
  7992. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7993. header += "%MO{units}*%\n".format(units=gunits)
  7994. for apid in obj.apertures:
  7995. if obj.apertures[apid]['type'] == 'C':
  7996. header += "%ADD{apid}{type},{size}*%\n".format(
  7997. apid=str(apid),
  7998. type='C',
  7999. size=(factor * obj.apertures[apid]['size'])
  8000. )
  8001. elif obj.apertures[apid]['type'] == 'R':
  8002. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8003. apid=str(apid),
  8004. type='R',
  8005. width=(factor * obj.apertures[apid]['width']),
  8006. height=(factor * obj.apertures[apid]['height'])
  8007. )
  8008. elif obj.apertures[apid]['type'] == 'O':
  8009. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8010. apid=str(apid),
  8011. type='O',
  8012. width=(factor * obj.apertures[apid]['width']),
  8013. height=(factor * obj.apertures[apid]['height'])
  8014. )
  8015. header += '\n'
  8016. # obsolete units but some software may need it
  8017. if gunits == 'IN':
  8018. header += 'G70*\n'
  8019. else:
  8020. header += 'G71*\n'
  8021. # Absolute Mode
  8022. header += 'G90*\n'
  8023. header += 'G01*\n'
  8024. # positive polarity
  8025. header += '%LPD*%\n'
  8026. footer = 'M02*\n'
  8027. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8028. exported_gerber = header
  8029. exported_gerber += gerber_code
  8030. exported_gerber += footer
  8031. if local_use is None:
  8032. try:
  8033. with open(filename, 'w') as fp:
  8034. fp.write(exported_gerber)
  8035. except PermissionError:
  8036. self.inform.emit('[WARNING] %s' %
  8037. _("Permission denied, saving not possible.\n"
  8038. "Most likely another app is holding the file open and not accessible."))
  8039. return 'fail'
  8040. if self.defaults["global_open_style"] is False:
  8041. self.file_opened.emit("Gerber", filename)
  8042. self.file_saved.emit("Gerber", filename)
  8043. self.inform.emit('[success] %s: %s' %
  8044. (_("Gerber file exported to"), filename))
  8045. else:
  8046. return exported_gerber
  8047. except Exception as e:
  8048. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8049. return 'fail'
  8050. if use_thread is True:
  8051. with self.proc_container.new(_("Exporting Gerber")) as proc:
  8052. def job_thread_grb(app_obj):
  8053. ret = make_gerber()
  8054. if ret == 'fail':
  8055. self.inform.emit('[ERROR_NOTCL] %s' %
  8056. _('Could not export Gerber file.'))
  8057. return
  8058. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8059. else:
  8060. ret = make_gerber()
  8061. if ret == 'fail':
  8062. self.inform.emit('[ERROR_NOTCL] %s' %
  8063. _('Could not export Gerber file.'))
  8064. return 'fail'
  8065. if local_use is not None:
  8066. return ret
  8067. def export_dxf(self, obj_name, filename, use_thread=True):
  8068. """
  8069. Exports a Geometry Object to an DXF file.
  8070. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8071. :param filename: Path to the DXF file to save to.
  8072. :param use_thread: if to be run in a separate thread
  8073. :return:
  8074. """
  8075. self.report_usage("export_dxf()")
  8076. if filename is None:
  8077. filename = self.defaults["global_last_save_folder"]
  8078. self.log.debug("export_dxf()")
  8079. format_exc = ''
  8080. units = ''
  8081. try:
  8082. obj = self.collection.get_by_name(str(obj_name))
  8083. except:
  8084. # TODO: The return behavior has not been established... should raise exception?
  8085. return "Could not retrieve object: %s" % obj_name
  8086. # updated units
  8087. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8088. if units == 'IN' or units == 'INCH':
  8089. units = 'INCH'
  8090. elif units == 'MM' or units == 'METIRC':
  8091. units ='METRIC'
  8092. def make_dxf():
  8093. try:
  8094. dxf_code = obj.export_dxf()
  8095. dxf_code.saveas(filename)
  8096. if self.defaults["global_open_style"] is False:
  8097. self.file_opened.emit("DXF", filename)
  8098. self.file_saved.emit("DXF", filename)
  8099. self.inform.emit('[success] %s: %s' %
  8100. (_("DXF file exported to"), filename))
  8101. except:
  8102. return 'fail'
  8103. if use_thread is True:
  8104. with self.proc_container.new(_("Exporting DXF")) as proc:
  8105. def job_thread_exc(app_obj):
  8106. ret = make_dxf()
  8107. if ret == 'fail':
  8108. app_obj.inform.emit('[WARNING_NOTCL] %s' %
  8109. _('Could not export DXF file.'))
  8110. return
  8111. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8112. else:
  8113. ret = make_dxf()
  8114. if ret == 'fail':
  8115. self.inform.emit('[WARNING_NOTCL] %s' %
  8116. _('Could not export DXF file.'))
  8117. return
  8118. def import_svg(self, filename, geo_type='geometry', outname=None):
  8119. """
  8120. Adds a new Geometry Object to the projects and populates
  8121. it with shapes extracted from the SVG file.
  8122. :param filename: Path to the SVG file.
  8123. :param outname:
  8124. :return:
  8125. """
  8126. self.report_usage("import_svg()")
  8127. obj_type = ""
  8128. if geo_type is None or geo_type == "geometry":
  8129. obj_type = "geometry"
  8130. elif geo_type == "gerber":
  8131. obj_type = geo_type
  8132. else:
  8133. self.inform.emit('[ERROR_NOTCL] %s' %
  8134. _("Not supported type is picked as parameter. "
  8135. "Only Geometry and Gerber are supported"))
  8136. return
  8137. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8138. def obj_init(geo_obj, app_obj):
  8139. geo_obj.import_svg(filename, obj_type, units=units)
  8140. geo_obj.multigeo = False
  8141. with self.proc_container.new(_("Importing SVG")) as proc:
  8142. # Object name
  8143. name = outname or filename.split('/')[-1].split('\\')[-1]
  8144. self.new_object(obj_type, name, obj_init, autoselected=False)
  8145. self.progress.emit(20)
  8146. # Register recent file
  8147. self.file_opened.emit("svg", filename)
  8148. # GUI feedback
  8149. self.inform.emit('[success] %s: %s' %
  8150. (_("Opened"), filename))
  8151. self.progress.emit(100)
  8152. def import_dxf(self, filename, geo_type='geometry', outname=None):
  8153. """
  8154. Adds a new Geometry Object to the projects and populates
  8155. it with shapes extracted from the DXF file.
  8156. :param filename: Path to the DXF file.
  8157. :param outname:
  8158. :type putname: str
  8159. :return:
  8160. """
  8161. self.report_usage("import_dxf()")
  8162. obj_type = ""
  8163. if geo_type is None or geo_type == "geometry":
  8164. obj_type = "geometry"
  8165. elif geo_type == "gerber":
  8166. obj_type = geo_type
  8167. else:
  8168. self.inform.emit('[ERROR_NOTCL] %s' %
  8169. _("Not supported type is picked as parameter. "
  8170. "Only Geometry and Gerber are supported"))
  8171. return
  8172. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8173. def obj_init(geo_obj, app_obj):
  8174. geo_obj.import_dxf(filename, obj_type, units=units)
  8175. geo_obj.multigeo = False
  8176. with self.proc_container.new(_("Importing DXF")) as proc:
  8177. # Object name
  8178. name = outname or filename.split('/')[-1].split('\\')[-1]
  8179. self.new_object(obj_type, name, obj_init, autoselected=False)
  8180. self.progress.emit(20)
  8181. # Register recent file
  8182. self.file_opened.emit("dxf", filename)
  8183. # GUI feedback
  8184. self.inform.emit('[success] %s: %s' %
  8185. (_("Opened"), filename))
  8186. self.progress.emit(100)
  8187. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  8188. """
  8189. Adds a new Geometry Object to the projects and populates
  8190. it with shapes extracted from the SVG file.
  8191. :param filename: Path to the SVG file.
  8192. :param o_type: type of FlatCAM objeect
  8193. :param dpi: dot per inch
  8194. :param mode: black or color
  8195. :param mask: dictate the level of detail
  8196. :param outname: name for the resulting file
  8197. :return:
  8198. """
  8199. self.report_usage("import_image()")
  8200. if o_type is None or o_type == "geometry":
  8201. obj_type = "geometry"
  8202. elif o_type == "gerber":
  8203. obj_type = o_type
  8204. else:
  8205. self.inform.emit('[ERROR_NOTCL] %s' %
  8206. _("Not supported type is picked as parameter. "
  8207. "Only Geometry and Gerber are supported"))
  8208. return
  8209. def obj_init(geo_obj, app_obj):
  8210. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  8211. geo_obj.multigeo = False
  8212. with self.proc_container.new(_("Importing Image")) as proc:
  8213. # Object name
  8214. name = outname or filename.split('/')[-1].split('\\')[-1]
  8215. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  8216. self.new_object(obj_type, name, obj_init)
  8217. self.progress.emit(20)
  8218. # Register recent file
  8219. self.file_opened.emit("image", filename)
  8220. # GUI feedback
  8221. self.inform.emit('[success] %s: %s' %
  8222. (_("Opened"), filename))
  8223. self.progress.emit(100)
  8224. def open_gerber(self, filename, outname=None):
  8225. """
  8226. Opens a Gerber file, parses it and creates a new object for
  8227. it in the program. Thread-safe.
  8228. :param outname: Name of the resulting object. None causes the
  8229. name to be that of the file.
  8230. :param filename: Gerber file filename
  8231. :type filename: str
  8232. :param follow: If true, the parser will not create polygons, just lines
  8233. following the gerber path.
  8234. :type follow: bool
  8235. :return: None
  8236. """
  8237. # How the object should be initialized
  8238. def obj_init(gerber_obj, app_obj):
  8239. assert isinstance(gerber_obj, FlatCAMGerber), \
  8240. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  8241. # Opening the file happens here
  8242. self.progress.emit(30)
  8243. try:
  8244. gerber_obj.parse_file(filename)
  8245. except IOError:
  8246. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8247. (_("Failed to open file"), filename))
  8248. app_obj.progress.emit(0)
  8249. return "fail"
  8250. except ParseError as err:
  8251. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' %
  8252. (_("Failed to parse file"), filename, str(err)))
  8253. app_obj.progress.emit(0)
  8254. self.log.error(str(err))
  8255. return "fail"
  8256. except Exception as e:
  8257. log.debug("App.open_gerber() --> %s" % str(e))
  8258. msg = '[ERROR] %s' % \
  8259. _("An internal error has occurred. See shell.\n")
  8260. msg += traceback.format_exc()
  8261. app_obj.inform.emit(msg)
  8262. return "fail"
  8263. if gerber_obj.is_empty():
  8264. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  8265. # self.collection.set_active(gerber_obj.options["name"])
  8266. # self.collection.delete_active()
  8267. self.inform.emit('[ERROR_NOTCL] %s' %
  8268. _("Object is not Gerber file or empty. Aborting object creation."))
  8269. return "fail"
  8270. # Further parsing
  8271. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  8272. App.log.debug("open_gerber()")
  8273. with self.proc_container.new(_("Opening Gerber")) as proc:
  8274. self.progress.emit(10)
  8275. # Object name
  8276. name = outname or filename.split('/')[-1].split('\\')[-1]
  8277. # # ## Object creation # ##
  8278. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  8279. if ret == 'fail':
  8280. self.inform.emit('[ERROR_NOTCL]%s' %
  8281. _(' Open Gerber failed. Probable not a Gerber file.'))
  8282. return
  8283. # Register recent file
  8284. self.file_opened.emit("gerber", filename)
  8285. self.progress.emit(100)
  8286. # GUI feedback
  8287. self.inform.emit('[success] %s: %s' %
  8288. (_("Opened"), filename))
  8289. def open_excellon(self, filename, outname=None, plot=True):
  8290. """
  8291. Opens an Excellon file, parses it and creates a new object for
  8292. it in the program. Thread-safe.
  8293. :param outname: Name of the resulting object. None causes the
  8294. name to be that of the file.
  8295. :param filename: Excellon file filename
  8296. :type filename: str
  8297. :return: None
  8298. """
  8299. App.log.debug("open_excellon()")
  8300. # How the object should be initialized
  8301. def obj_init(excellon_obj, app_obj):
  8302. # self.progress.emit(20)
  8303. try:
  8304. ret = excellon_obj.parse_file(filename=filename)
  8305. if ret == "fail":
  8306. log.debug("Excellon parsing failed.")
  8307. self.inform.emit('[ERROR_NOTCL] %s' %
  8308. _("This is not Excellon file."))
  8309. return "fail"
  8310. except IOError:
  8311. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8312. (_("Cannot open file"), filename))
  8313. log.debug("Could not open Excellon object.")
  8314. self.progress.emit(0) # TODO: self and app_bjj mixed
  8315. return "fail"
  8316. except:
  8317. msg = '[ERROR_NOTCL] %s' % \
  8318. _("An internal error has occurred. See shell.\n")
  8319. msg += traceback.format_exc()
  8320. app_obj.inform.emit(msg)
  8321. return "fail"
  8322. ret = excellon_obj.create_geometry()
  8323. if ret == 'fail':
  8324. log.debug("Could not create geometry for Excellon object.")
  8325. return "fail"
  8326. for tool in excellon_obj.tools:
  8327. if excellon_obj.tools[tool]['solid_geometry']:
  8328. return
  8329. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8330. (_("No geometry found in file"), filename))
  8331. return "fail"
  8332. with self.proc_container.new(_("Opening Excellon.")):
  8333. # Object name
  8334. name = outname or filename.split('/')[-1].split('\\')[-1]
  8335. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8336. if ret_val == 'fail':
  8337. self.inform.emit('[ERROR_NOTCL] %s' %
  8338. _('Open Excellon file failed. Probable not an Excellon file.'))
  8339. return
  8340. # Register recent file
  8341. self.file_opened.emit("excellon", filename)
  8342. # GUI feedback
  8343. self.inform.emit('[success] %s: %s' %
  8344. (_("Opened"), filename))
  8345. def open_gcode(self, filename, outname=None, plot=True):
  8346. """
  8347. Opens a G-gcode file, parses it and creates a new object for
  8348. it in the program. Thread-safe.
  8349. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8350. :param filename: G-code file filename
  8351. :type filename: str
  8352. :return: None
  8353. """
  8354. App.log.debug("open_gcode()")
  8355. # How the object should be initialized
  8356. def obj_init(job_obj, app_obj_):
  8357. """
  8358. :param job_obj: the resulting object
  8359. :type app_obj_: App
  8360. """
  8361. assert isinstance(app_obj_, App), \
  8362. "Initializer expected App, got %s" % type(app_obj_)
  8363. self.progress.emit(10)
  8364. try:
  8365. f = open(filename)
  8366. gcode = f.read()
  8367. f.close()
  8368. except IOError:
  8369. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  8370. (_("Failed to open"), filename))
  8371. self.progress.emit(0)
  8372. return "fail"
  8373. job_obj.gcode = gcode
  8374. self.progress.emit(20)
  8375. ret = job_obj.gcode_parse()
  8376. if ret == "fail":
  8377. self.inform.emit('[ERROR_NOTCL] %s' %
  8378. _("This is not GCODE"))
  8379. return "fail"
  8380. self.progress.emit(60)
  8381. job_obj.create_geometry()
  8382. with self.proc_container.new(_("Opening G-Code.")):
  8383. # Object name
  8384. name = outname or filename.split('/')[-1].split('\\')[-1]
  8385. # New object creation and file processing
  8386. ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8387. if ret == 'fail':
  8388. self.inform.emit('[ERROR_NOTCL] %s' %
  8389. _("Failed to create CNCJob Object. Probable not a GCode file.\n "
  8390. "Attempting to create a FlatCAM CNCJob Object from "
  8391. "G-Code file failed during processing"))
  8392. return "fail"
  8393. # Register recent file
  8394. self.file_opened.emit("cncjob", filename)
  8395. # GUI feedback
  8396. self.inform.emit('[success] %s: %s' %
  8397. (_("Opened"), filename))
  8398. self.progress.emit(100)
  8399. def open_config_file(self, filename, run_from_arg=None):
  8400. """
  8401. Loads a config file from the specified file.
  8402. :param filename: Name of the file from which to load.
  8403. :type filename: str
  8404. :return: None
  8405. """
  8406. App.log.debug("Opening config file: " + filename)
  8407. if run_from_arg:
  8408. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8409. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8410. _("Opening FlatCAM Config file.")),
  8411. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8412. color=QtGui.QColor("gray"))
  8413. # add the tab if it was closed
  8414. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  8415. # first clear previous text in text editor (if any)
  8416. self.ui.code_editor.clear()
  8417. # Switch plot_area to CNCJob tab
  8418. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  8419. try:
  8420. if filename:
  8421. f = QtCore.QFile(filename)
  8422. if f.open(QtCore.QIODevice.ReadOnly):
  8423. stream = QtCore.QTextStream(f)
  8424. gcode_edited = stream.readAll()
  8425. self.ui.code_editor.setPlainText(gcode_edited)
  8426. f.close()
  8427. except IOError:
  8428. App.log.error("Failed to open config file: %s" % filename)
  8429. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8430. (_("Failed to open config file"), filename))
  8431. return
  8432. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  8433. """
  8434. Loads a project from the specified file.
  8435. 1) Loads and parses file
  8436. 2) Registers the file as recently opened.
  8437. 3) Calls on_file_new()
  8438. 4) Updates options
  8439. 5) Calls new_object() with the object's from_dict() as init method.
  8440. 6) Calls plot_all() if plot=True
  8441. :param filename: Name of the file from which to load.
  8442. :type filename: str
  8443. :param run_from_arg: True if run for arguments
  8444. :param plot: If True plot all objects in the project
  8445. :param cli: run from command line
  8446. :return: None
  8447. """
  8448. App.log.debug("Opening project: " + filename)
  8449. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8450. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8451. if cli is None:
  8452. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8453. if run_from_arg:
  8454. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8455. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8456. _("Opening FlatCAM Project file.")),
  8457. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8458. color=QtGui.QColor("gray"))
  8459. # Open and parse an uncompressed Project file
  8460. try:
  8461. f = open(filename, 'r')
  8462. except IOError:
  8463. App.log.error("Failed to open project file: %s" % filename)
  8464. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8465. (_("Failed to open project file"), filename))
  8466. return
  8467. try:
  8468. d = json.load(f, object_hook=dict2obj)
  8469. except Exception as e:
  8470. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8471. (filename, str(e)))
  8472. f.close()
  8473. # Open and parse a compressed Project file
  8474. try:
  8475. with lzma.open(filename) as f:
  8476. file_content = f.read().decode('utf-8')
  8477. d = json.loads(file_content, object_hook=dict2obj)
  8478. except Exception as e:
  8479. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8480. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8481. (_("Failed to open project file"), filename))
  8482. return
  8483. # Clear the current project
  8484. # # NOT THREAD SAFE # ##
  8485. if run_from_arg is True:
  8486. pass
  8487. elif cli is True:
  8488. self.delete_selection_shape()
  8489. else:
  8490. self.on_file_new()
  8491. # Project options
  8492. self.options.update(d['options'])
  8493. self.project_filename = filename
  8494. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8495. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8496. if cli is None:
  8497. self.set_screen_units(self.options["units"])
  8498. # Re create objects
  8499. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8500. for obj in d['objs']:
  8501. def obj_init(obj_inst, app_inst):
  8502. obj_inst.from_dict(obj)
  8503. App.log.debug("Recreating from opened project an %s object: %s" %
  8504. (obj['kind'].capitalize(), obj['options']['name']))
  8505. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8506. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8507. if cli is None:
  8508. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8509. obj['kind'].upper(),
  8510. obj['options']['name']
  8511. )
  8512. )
  8513. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  8514. self.inform.emit('[success] %s: %s' %
  8515. (_("Project loaded from"), filename))
  8516. self.should_we_save = False
  8517. self.file_opened.emit("project", filename)
  8518. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8519. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8520. if cli is None:
  8521. self.set_ui_title(name=self.project_filename)
  8522. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8523. def propagate_defaults(self, silent=False):
  8524. """
  8525. This method is used to set default values in classes. It's
  8526. an alternative to project options but allows the use
  8527. of values invisible to the user.
  8528. :return: None
  8529. """
  8530. if silent is False:
  8531. self.log.debug("propagate_defaults()")
  8532. # Which objects to update the given parameters.
  8533. routes = {
  8534. "global_zdownrate": CNCjob,
  8535. "excellon_zeros": Excellon,
  8536. "excellon_format_upper_in": Excellon,
  8537. "excellon_format_lower_in": Excellon,
  8538. "excellon_format_upper_mm": Excellon,
  8539. "excellon_format_lower_mm": Excellon,
  8540. "excellon_units": Excellon,
  8541. "gerber_use_buffer_for_union": Gerber,
  8542. "geometry_multidepth": Geometry
  8543. }
  8544. for param in routes:
  8545. if param in routes[param].defaults:
  8546. try:
  8547. routes[param].defaults[param] = self.defaults[param]
  8548. if silent is False:
  8549. self.log.debug(" " + param + " OK")
  8550. except KeyError:
  8551. if silent is False:
  8552. self.log.debug(" ERROR: " + param + " not in defaults.")
  8553. else:
  8554. # Try extracting the name:
  8555. # classname_param here is param in the object
  8556. if param.find(routes[param].__name__.lower() + "_") == 0:
  8557. p = param[len(routes[param].__name__) + 1:]
  8558. if p in routes[param].defaults:
  8559. routes[param].defaults[p] = self.defaults[param]
  8560. if silent is False:
  8561. self.log.debug(" " + param + " OK!")
  8562. def restore_main_win_geom(self):
  8563. try:
  8564. self.ui.setGeometry(self.defaults["global_def_win_x"],
  8565. self.defaults["global_def_win_y"],
  8566. self.defaults["global_def_win_w"],
  8567. self.defaults["global_def_win_h"])
  8568. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  8569. except KeyError as e:
  8570. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  8571. def plot_all(self, zoom=True):
  8572. """
  8573. Re-generates all plots from all objects.
  8574. :return: None
  8575. """
  8576. self.log.debug("Plot_all()")
  8577. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  8578. for obj in self.collection.get_list():
  8579. def worker_task(obj):
  8580. with self.proc_container.new("Plotting"):
  8581. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8582. if zoom:
  8583. self.object_plotted.emit(obj)
  8584. # Send to worker
  8585. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  8586. def register_folder(self, filename):
  8587. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8588. def register_save_folder(self, filename):
  8589. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8590. def set_progress_bar(self, percentage, text=""):
  8591. self.ui.progress_bar.setValue(int(percentage))
  8592. def setup_shell(self):
  8593. """
  8594. Creates shell functions. Runs once at startup.
  8595. :return: None
  8596. """
  8597. self.log.debug("setup_shell()")
  8598. def shelp(p=None):
  8599. if not p:
  8600. return _("Available commands:\n") + \
  8601. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  8602. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  8603. if p not in commands:
  8604. return "Unknown command: %s" % p
  8605. return commands[p]["help"]
  8606. # --- Migrated to new architecture ---
  8607. # def options(name):
  8608. # ops = self.collection.get_by_name(str(name)).options
  8609. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  8610. def h(*args):
  8611. """
  8612. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  8613. and standalone parameters into list.
  8614. """
  8615. kwa = {}
  8616. a = []
  8617. n = len(args)
  8618. name = None
  8619. for i in range(n):
  8620. match = re.search(r'^-([a-zA-Z].*)', args[i])
  8621. if match:
  8622. assert name is None
  8623. name = match.group(1)
  8624. continue
  8625. if name is None:
  8626. a.append(args[i])
  8627. else:
  8628. kwa[name] = args[i]
  8629. name = None
  8630. return a, kwa
  8631. @contextmanager
  8632. def wait_signal(signal, timeout=10000):
  8633. """
  8634. Block loop until signal emitted, timeout (ms) elapses
  8635. or unhandled exception happens in a thread.
  8636. :param timeout: time after which the loop is exited
  8637. :param signal: Signal to wait for.
  8638. """
  8639. loop = QtCore.QEventLoop()
  8640. # Normal termination
  8641. signal.connect(loop.quit)
  8642. # Termination by exception in thread
  8643. self.thread_exception.connect(loop.quit)
  8644. status = {'timed_out': False}
  8645. def report_quit():
  8646. status['timed_out'] = True
  8647. loop.quit()
  8648. yield
  8649. # Temporarily change how exceptions are managed.
  8650. oeh = sys.excepthook
  8651. ex = []
  8652. def except_hook(type_, value, traceback_):
  8653. ex.append(value)
  8654. oeh(type_, value, traceback_)
  8655. sys.excepthook = except_hook
  8656. # Terminate on timeout
  8657. if timeout is not None:
  8658. QtCore.QTimer.singleShot(timeout, report_quit)
  8659. # # ## Block ## ##
  8660. loop.exec_()
  8661. # Restore exception management
  8662. sys.excepthook = oeh
  8663. if ex:
  8664. self.raiseTclError(str(ex[0]))
  8665. if status['timed_out']:
  8666. raise Exception('Timed out!')
  8667. def make_docs():
  8668. output = ''
  8669. import collections
  8670. od = collections.OrderedDict(sorted(commands.items()))
  8671. for cmd_, val in od.items():
  8672. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  8673. t = val['help']
  8674. usage_i = t.find('>')
  8675. if usage_i < 0:
  8676. expl = t
  8677. output += expl + '\n\n'
  8678. continue
  8679. expl = t[:usage_i - 1]
  8680. output += expl + '\n\n'
  8681. end_usage_i = t[usage_i:].find('\n')
  8682. if end_usage_i < 0:
  8683. end_usage_i = len(t[usage_i:])
  8684. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  8685. else:
  8686. extras = t[usage_i+end_usage_i+1:]
  8687. parts = [s.strip() for s in extras.split('\n')]
  8688. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  8689. for p in parts:
  8690. output += ' ' + p + '\n\n'
  8691. return output
  8692. '''
  8693. Howto implement TCL shell commands:
  8694. All parameters passed to command should be possible to set as None and test it afterwards.
  8695. This is because we need to see error caused in tcl,
  8696. if None value as default parameter is not allowed TCL will return empty error.
  8697. Use:
  8698. def mycommand(name=None,...):
  8699. Test it like this:
  8700. if name is None:
  8701. self.raise_tcl_error('Argument name is missing.')
  8702. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  8703. otherwise we will miss it and processing will silently continue.
  8704. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  8705. which is catched in exec_command and displayed in TCL shell console with red background.
  8706. Error in console is displayed with TCL trace.
  8707. This behavior works only within main thread,
  8708. errors with promissed tasks can be catched and detected only with log.
  8709. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  8710. TCL shell.
  8711. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  8712. '''
  8713. commands = {
  8714. 'help': {
  8715. 'fcn': shelp,
  8716. 'help': _("Shows list of commands.")
  8717. },
  8718. }
  8719. # Import/overwrite tcl commands as objects of TclCommand descendants
  8720. # This modifies the variable 'commands'.
  8721. tclCommands.register_all_commands(self, commands)
  8722. # Add commands to the tcl interpreter
  8723. for cmd in commands:
  8724. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  8725. # Make the tcl puts function return instead of print to stdout
  8726. self.tcl.eval('''
  8727. rename puts original_puts
  8728. proc puts {args} {
  8729. if {[llength $args] == 1} {
  8730. return "[lindex $args 0]"
  8731. } else {
  8732. eval original_puts $args
  8733. }
  8734. }
  8735. ''')
  8736. def setup_recent_items(self):
  8737. # TODO: Move this to constructor
  8738. icons = {
  8739. "gerber": "share/flatcam_icon16.png",
  8740. "excellon": "share/drill16.png",
  8741. 'geometry': "share/geometry16.png",
  8742. "cncjob": "share/cnc16.png",
  8743. "project": "share/project16.png",
  8744. "svg": "share/geometry16.png",
  8745. "dxf": "share/dxf16.png",
  8746. "pdf": "share/pdf32.png",
  8747. "image": "share/image16.png"
  8748. }
  8749. openers = {
  8750. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8751. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8752. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8753. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8754. 'project': self.open_project,
  8755. 'svg': self.import_svg,
  8756. 'dxf': self.import_dxf,
  8757. 'image': self.import_image,
  8758. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8759. }
  8760. # Open recent file for files
  8761. try:
  8762. f = open(self.data_path + '/recent.json')
  8763. except IOError:
  8764. App.log.error("Failed to load recent item list.")
  8765. self.inform.emit('[ERROR_NOTCL] %s' %
  8766. _("Failed to load recent item list."))
  8767. return
  8768. try:
  8769. self.recent = json.load(f)
  8770. except json.scanner.JSONDecodeError:
  8771. App.log.error("Failed to parse recent item list.")
  8772. self.inform.emit('[ERROR_NOTCL] %s' %
  8773. _("Failed to parse recent item list."))
  8774. f.close()
  8775. return
  8776. f.close()
  8777. # Open recent file for projects
  8778. try:
  8779. fp = open(self.data_path + '/recent_projects.json')
  8780. except IOError:
  8781. App.log.error("Failed to load recent project item list.")
  8782. self.inform.emit('[ERROR_NOTCL] %s' %
  8783. _("Failed to load recent projects item list."))
  8784. return
  8785. try:
  8786. self.recent_projects = json.load(fp)
  8787. except json.scanner.JSONDecodeError:
  8788. App.log.error("Failed to parse recent project item list.")
  8789. self.inform.emit('[ERROR_NOTCL] %s' %
  8790. _("Failed to parse recent project item list."))
  8791. fp.close()
  8792. return
  8793. fp.close()
  8794. # Closure needed to create callbacks in a loop.
  8795. # Otherwise late binding occurs.
  8796. def make_callback(func, fname):
  8797. def opener():
  8798. func(fname)
  8799. return opener
  8800. def reset_recent_files():
  8801. # Reset menu
  8802. self.ui.recent.clear()
  8803. self.recent = []
  8804. try:
  8805. f = open(self.data_path + '/recent.json', 'w')
  8806. except IOError:
  8807. App.log.error("Failed to open recent items file for writing.")
  8808. return
  8809. json.dump(self.recent, f)
  8810. def reset_recent_projects():
  8811. # Reset menu
  8812. self.ui.recent_projects.clear()
  8813. self.recent_projects = []
  8814. try:
  8815. fp = open(self.data_path + '/recent_projects.json', 'w')
  8816. except IOError:
  8817. App.log.error("Failed to open recent projects items file for writing.")
  8818. return
  8819. json.dump(self.recent, fp)
  8820. # Reset menu
  8821. self.ui.recent.clear()
  8822. self.ui.recent_projects.clear()
  8823. # Create menu items for projects
  8824. for recent in self.recent_projects:
  8825. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8826. if recent['kind'] == 'project':
  8827. try:
  8828. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8829. # Attach callback
  8830. o = make_callback(openers[recent["kind"]], recent['filename'])
  8831. action.triggered.connect(o)
  8832. self.ui.recent_projects.addAction(action)
  8833. except KeyError:
  8834. App.log.error("Unsupported file type: %s" % recent["kind"])
  8835. # Last action in Recent Files menu is one that Clear the content
  8836. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  8837. clear_action_proj.triggered.connect(reset_recent_projects)
  8838. self.ui.recent_projects.addSeparator()
  8839. self.ui.recent_projects.addAction(clear_action_proj)
  8840. # Create menu items for files
  8841. for recent in self.recent:
  8842. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8843. if recent['kind'] != 'project':
  8844. try:
  8845. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8846. # Attach callback
  8847. o = make_callback(openers[recent["kind"]], recent['filename'])
  8848. action.triggered.connect(o)
  8849. self.ui.recent.addAction(action)
  8850. except KeyError:
  8851. App.log.error("Unsupported file type: %s" % recent["kind"])
  8852. # Last action in Recent Files menu is one that Clear the content
  8853. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  8854. clear_action.triggered.connect(reset_recent_files)
  8855. self.ui.recent.addSeparator()
  8856. self.ui.recent.addAction(clear_action)
  8857. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8858. # self.ui.menufilerecent.set_submenu(recent_menu)
  8859. # recent_menu.show_all()
  8860. # self.ui.recent.show()
  8861. self.log.debug("Recent items list has been populated.")
  8862. def setup_component_editor(self):
  8863. # label = QtWidgets.QLabel("Choose an item from Project")
  8864. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8865. sel_title = QtWidgets.QTextEdit(
  8866. _('<b>Shortcut Key List</b>'))
  8867. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8868. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8869. settings = QSettings("Open Source", "FlatCAM")
  8870. if settings.contains("notebook_font_size"):
  8871. fsize = settings.value('notebook_font_size', type=int)
  8872. else:
  8873. fsize = 12
  8874. tsize = fsize + int(fsize / 2)
  8875. # selected_text = (_('''
  8876. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  8877. #
  8878. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8879. # The normal flow when working in FlatCAM is the following:</span></p>
  8880. #
  8881. # <ol>
  8882. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  8883. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  8884. # even dragging and dropping the files on the GUI.<br />
  8885. # <br />
  8886. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  8887. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  8888. # &nbsp;</li>
  8889. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  8890. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  8891. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  8892. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  8893. # <br />
  8894. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  8895. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  8896. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  8897. # it even if it was out of focus.<br />
  8898. # <br />
  8899. # You can change the parameters in this screen and the flow direction is like this:<br />
  8900. # <br />
  8901. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  8902. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  8903. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  8904. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  8905. # </ol>
  8906. #
  8907. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  8908. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  8909. # <strong>F3</strong>.</span></p>
  8910. #
  8911. # ''').format(fsize=fsize, tsize=tsize))
  8912. selected_text = '''
  8913. <p><span style="font-size:{tsize}px"><strong>%s</strong></span></p>
  8914. <p><span style="font-size:{fsize}px"><strong>%s</strong>:<br />
  8915. %s:</span></p>
  8916. <ol>
  8917. <li><span style="font-size:{fsize}px">%s menu&#39;s, %s.<br />
  8918. <br />
  8919. %s &amp; %s.</span><br />
  8920. &nbsp;</li>
  8921. <li><span style="font-size:{fsize}px">%s <strong>%s</strong> (%s), <strong>%s</strong> %s it-s %s.<br />
  8922. <br />
  8923. %s <strong>%s</strong> %s <strong>%s</strong> %s.<br />
  8924. <br />
  8925. %s:<br />
  8926. <br />
  8927. <strong>%s</strong> -&gt; %s -&gt; %s -&gt;<strong> %s </strong> -&gt; %s -&gt; %s -&gt;<strong> %s
  8928. </strong>-&gt; %s <strong>%s)&nbsp;</strong>-&gt; %s</span></li>
  8929. </ol>
  8930. <p><span style="font-size:{fsize}px">%s <strong>%s -&gt; %s</strong>&nbsp;%s it&#39;s %s:
  8931. <strong>F3</strong>.</span></p>
  8932. ''' % (
  8933. _("Selected Tab - Choose an Item from Project Tab"), _("Details"),
  8934. _("The normal flow when working in FlatCAM is the following"),
  8935. _("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the"),
  8936. _("toolbars, key shortcuts or even dragging and dropping the files on the GUI"),
  8937. _("You can also load a FlatCAM project by double clicking on the project file, drag"),
  8938. _("drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app"),
  8939. _("Once an object is available in the Project Tab, by selecting it and then focusing on"),
  8940. _("SELECTED TAB"), _("more simpler is to double click the object name in the Project Tab"),
  8941. _("SELECTED TAB"), _("will be updated with the object properties according to"),
  8942. _("kind: Gerber, Excellon, Geometry or CNCJob object"),
  8943. _("If the selection of the object is done on the canvas by single click instead, and the"),
  8944. _("SELECTED TAB"),
  8945. _("is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, "
  8946. "double clicking on the object on the canvas will bring the"),
  8947. _("SELECTED TAB"), _("and populate it even if it was out of focus"),
  8948. _("You can change the parameters in this screen and the flow direction is like this"),
  8949. _("Gerber/Excellon Object"), _("Change Parameter"), _("Generate Geometry"), _("Geometry Object"),
  8950. _("Add tools (change param in Selected Tab)"), _("Generate CNCJob"), _("CNCJob Object"),
  8951. _("Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in"), _("SELECTED TAB"),
  8952. _("Save GCode"), _("A list of key shortcuts is available through an menu entry in"), _("Help"),
  8953. _("Shortcuts List"), _("or through"), _("own key shortcut"),
  8954. )
  8955. sel_title.setText(selected_text)
  8956. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8957. self.ui.selected_scroll_area.setWidget(sel_title)
  8958. def setup_obj_classes(self):
  8959. """
  8960. Sets up application specifics on the FlatCAMObj class.
  8961. :return: None
  8962. """
  8963. FlatCAMObj.app = self
  8964. ObjectCollection.app = self
  8965. Gerber.app = self
  8966. Excellon.app = self
  8967. Geometry.app = self
  8968. CNCjob.app = self
  8969. FCProcess.app = self
  8970. FCProcessContainer.app = self
  8971. def version_check(self):
  8972. """
  8973. Checks for the latest version of the program. Alerts the
  8974. user if theirs is outdated. This method is meant to be run
  8975. in a separate thread.
  8976. :return: None
  8977. """
  8978. self.log.debug("version_check()")
  8979. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8980. full_url = App.version_url + \
  8981. "?s=" + str(self.defaults['global_serial']) + \
  8982. "&v=" + str(self.version) + \
  8983. "&os=" + str(self.os) + \
  8984. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  8985. else:
  8986. # no_stats dict; just so it won't break things on website
  8987. no_ststs_dict = {}
  8988. no_ststs_dict["global_ststs"] = {}
  8989. full_url = App.version_url + \
  8990. "?s=" + str(self.defaults['global_serial']) + \
  8991. "&v=" + str(self.version) + \
  8992. "&os=" + str(self.os) + \
  8993. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8994. App.log.debug("Checking for updates @ %s" % full_url)
  8995. # ## Get the data
  8996. try:
  8997. f = urllib.request.urlopen(full_url)
  8998. except:
  8999. # App.log.warning("Failed checking for latest version. Could not connect.")
  9000. self.log.warning("Failed checking for latest version. Could not connect.")
  9001. self.inform.emit('[WARNING_NOTCL] %s' %
  9002. _("Failed checking for latest version. Could not connect."))
  9003. return
  9004. try:
  9005. data = json.load(f)
  9006. except Exception as e:
  9007. App.log.error("Could not parse information about latest version.")
  9008. self.inform.emit('[ERROR_NOTCL] %s' %
  9009. _("Could not parse information about latest version."))
  9010. App.log.debug("json.load(): %s" % str(e))
  9011. f.close()
  9012. return
  9013. f.close()
  9014. # ## Latest version?
  9015. if self.version >= data["version"]:
  9016. App.log.debug("FlatCAM is up to date!")
  9017. self.inform.emit('[success] %s' %
  9018. _("FlatCAM is up to date!"))
  9019. return
  9020. App.log.debug("Newer version available.")
  9021. self.message.emit(
  9022. _("Newer Version Available"),
  9023. _("There is a newer version of FlatCAM available for download:\n\n") +
  9024. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  9025. _("info")
  9026. )
  9027. def on_plotcanvas_setup(self, container=None):
  9028. """
  9029. This is doing the setup for the plot area (VisPy canvas)
  9030. :param container: widget where to install the canvas
  9031. :return: None
  9032. """
  9033. if container:
  9034. plot_container = container
  9035. else:
  9036. plot_container = self.ui.right_layout
  9037. self.plotcanvas = PlotCanvas(plot_container, self)
  9038. # So it can receive key presses
  9039. self.plotcanvas.native.setFocus()
  9040. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  9041. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  9042. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  9043. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  9044. # Keys over plot enabled
  9045. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  9046. self.app_cursor = self.plotcanvas.new_cursor()
  9047. self.app_cursor.enabled = False
  9048. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  9049. def on_zoom_fit(self, event):
  9050. """
  9051. Callback for zoom-out request. This can be either from the corresponding
  9052. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  9053. with axes limits from the geometry bounds of all objects.
  9054. :param event: Ignored.
  9055. :return: None
  9056. """
  9057. self.plotcanvas.fit_view()
  9058. def on_zoom_in(self):
  9059. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  9060. def on_zoom_out(self):
  9061. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  9062. def disable_all_plots(self):
  9063. self.report_usage("disable_all_plots()")
  9064. self.disable_plots(self.collection.get_list())
  9065. self.inform.emit('[success] %s' %
  9066. _("All plots disabled."))
  9067. def disable_other_plots(self):
  9068. self.report_usage("disable_other_plots()")
  9069. self.disable_plots(self.collection.get_non_selected())
  9070. self.inform.emit('[success] %s' %
  9071. _("All non selected plots disabled."))
  9072. def enable_all_plots(self):
  9073. self.report_usage("enable_all_plots()")
  9074. self.enable_plots(self.collection.get_list())
  9075. self.inform.emit('[success] %s' %
  9076. _("All plots enabled."))
  9077. def on_enable_sel_plots(self):
  9078. log.debug("App.on_enable_sel_plot()")
  9079. object_list = self.collection.get_selected()
  9080. self.enable_plots(objects=object_list)
  9081. self.inform.emit('[success] %s' %
  9082. _("Selected plots enabled..."))
  9083. def on_disable_sel_plots(self):
  9084. log.debug("App.on_disable_sel_plot()")
  9085. # self.inform.emit(_("Disabling plots ..."))
  9086. object_list = self.collection.get_selected()
  9087. self.disable_plots(objects=object_list)
  9088. self.inform.emit('[success] %s' %
  9089. _("Selected plots disabled..."))
  9090. def enable_plots(self, objects):
  9091. """
  9092. Disables plots
  9093. :param objects: list of Objects to be enabled
  9094. :return:
  9095. """
  9096. log.debug("Enabling plots ...")
  9097. # self.inform.emit(_("Working ..."))
  9098. for obj in objects:
  9099. if obj.options['plot'] is False:
  9100. obj.options.set_change_callback(lambda x: None)
  9101. obj.options['plot'] = True
  9102. obj.options.set_change_callback(obj.on_options_change)
  9103. def worker_task(objects):
  9104. with self.proc_container.new(_("Enabling plots ...")):
  9105. for obj in objects:
  9106. # obj.options['plot'] = True
  9107. if isinstance(obj, FlatCAMCNCjob):
  9108. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  9109. else:
  9110. obj.plot(visible=True)
  9111. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9112. # self.plots_updated.emit()
  9113. def disable_plots(self, objects):
  9114. """
  9115. Disables plots
  9116. :param objects: list of Objects to be disabled
  9117. :return:
  9118. """
  9119. # if no objects selected then do nothing
  9120. if not self.collection.get_selected():
  9121. return
  9122. log.debug("Disabling plots ...")
  9123. # self.inform.emit(_("Working ..."))
  9124. for obj in objects:
  9125. if obj.options['plot'] is True:
  9126. obj.options.set_change_callback(lambda x: None)
  9127. obj.options['plot'] = False
  9128. obj.options.set_change_callback(obj.on_options_change)
  9129. try:
  9130. self.delete_selection_shape()
  9131. except Exception as e:
  9132. log.debug("App.disable_plots() --> %s" % str(e))
  9133. # self.plots_updated.emit()
  9134. def worker_task(objects):
  9135. with self.proc_container.new(_("Disabling plots ...")):
  9136. for obj in objects:
  9137. # obj.options['plot'] = True
  9138. if isinstance(obj, FlatCAMCNCjob):
  9139. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  9140. else:
  9141. obj.plot(visible=False)
  9142. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9143. def toggle_plots(self, objects):
  9144. """
  9145. Toggle plots visibility
  9146. :param objects: list of Objects for which to be toggled the visibility
  9147. :return:
  9148. """
  9149. # if no objects selected then do nothing
  9150. if not self.collection.get_selected():
  9151. return
  9152. log.debug("Toggling plots ...")
  9153. self.inform.emit(_("Working ..."))
  9154. for obj in objects:
  9155. if obj.options['plot'] is False:
  9156. obj.options['plot'] = True
  9157. else:
  9158. obj.options['plot'] = False
  9159. self.plots_updated.emit()
  9160. def clear_plots(self):
  9161. objects = self.collection.get_list()
  9162. for obj in objects:
  9163. obj.clear(obj == objects[-1])
  9164. # Clear pool to free memory
  9165. self.clear_pool()
  9166. def generate_cnc_job(self, objects):
  9167. self.report_usage("generate_cnc_job()")
  9168. # for obj in objects:
  9169. # obj.generatecncjob()
  9170. for obj in objects:
  9171. obj.on_generatecnc_button_click()
  9172. def save_project(self, filename, quit_action=False, silent=False):
  9173. """
  9174. Saves the current project to the specified file.
  9175. :param filename: Name of the file in which to save.
  9176. :type filename: str
  9177. :param quit_action: if the project saving will be followed by an app quit; boolean
  9178. :param silent: if True will not display status messages
  9179. :return: None
  9180. """
  9181. self.log.debug("save_project()")
  9182. self.save_in_progress = True
  9183. with self.proc_container.new(_("Saving FlatCAM Project")):
  9184. # Capture the latest changes
  9185. # Current object
  9186. try:
  9187. self.collection.get_active().read_form()
  9188. except:
  9189. self.log.debug("There was no active object")
  9190. pass
  9191. # Project options
  9192. self.options_read_form()
  9193. # Serialize the whole project
  9194. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  9195. "options": self.options,
  9196. "version": self.version}
  9197. if self.defaults["global_save_compressed"] is True:
  9198. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  9199. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  9200. # # Write
  9201. f.write(g)
  9202. self.inform.emit('[success] %s: %s' %
  9203. (_("Project saved to"), filename))
  9204. else:
  9205. # Open file
  9206. try:
  9207. f = open(filename, 'w')
  9208. except IOError:
  9209. App.log.error("Failed to open file for saving: %s", filename)
  9210. return
  9211. # Write
  9212. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  9213. f.close()
  9214. # verification of the saved project
  9215. # Open and parse
  9216. try:
  9217. saved_f = open(filename, 'r')
  9218. except IOError:
  9219. if silent is False:
  9220. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9221. (_("Failed to verify project file"), filename, _("Retry to save it."))
  9222. )
  9223. return
  9224. try:
  9225. saved_d = json.load(saved_f, object_hook=dict2obj)
  9226. except:
  9227. if silent is False:
  9228. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9229. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9230. )
  9231. f.close()
  9232. return
  9233. saved_f.close()
  9234. if silent is False:
  9235. if 'version' in saved_d:
  9236. self.inform.emit('[success] %s: %s' %
  9237. (_("Project saved to"), filename))
  9238. else:
  9239. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9240. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9241. )
  9242. settings = QSettings("Open Source", "FlatCAM")
  9243. lock_state = self.ui.lock_action.isChecked()
  9244. settings.setValue('toolbar_lock', lock_state)
  9245. # This will write the setting to the platform specific storage.
  9246. del settings
  9247. # if quit:
  9248. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  9249. # t.start()
  9250. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  9251. def start_delayed_quit(self, delay, filename, should_quit=None):
  9252. """
  9253. :param delay: period of checking if project file size is more than zero; in seconds
  9254. :param filename: the name of the project file to be checked periodically for size more than zero
  9255. :param should_quit: if the task finished will be followed by an app quit; boolean
  9256. :return:
  9257. """
  9258. to_quit = should_quit
  9259. self.save_timer = QtCore.QTimer()
  9260. self.save_timer.setInterval(delay)
  9261. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  9262. self.save_timer.start()
  9263. def check_project_file_size(self, filename, should_quit=None):
  9264. """
  9265. :param filename: the name of the project file to be checked periodically for size more than zero
  9266. :param should_quit: will quit the app if True; boolean
  9267. :return:
  9268. """
  9269. try:
  9270. if os.stat(filename).st_size > 0:
  9271. self.save_in_progress = False
  9272. self.save_timer.stop()
  9273. if should_quit:
  9274. self.app_quit.emit()
  9275. except Exception as e:
  9276. traceback.print_exc()
  9277. def on_options_app2project(self):
  9278. """
  9279. Callback for Options->Transfer Options->App=>Project. Copies options
  9280. from application defaults to project defaults.
  9281. :return: None
  9282. """
  9283. self.report_usage("on_options_app2project")
  9284. self.defaults_read_form()
  9285. self.options.update(self.defaults)
  9286. self.options_write_form()
  9287. def on_options_project2app(self):
  9288. """
  9289. Callback for Options->Transfer Options->Project=>App. Copies options
  9290. from project defaults to application defaults.
  9291. :return: None
  9292. """
  9293. self.report_usage("on_options_project2app")
  9294. self.options_read_form()
  9295. self.defaults.update(self.options)
  9296. self.defaults_write_form()
  9297. def on_options_project2object(self):
  9298. """
  9299. Callback for Options->Transfer Options->Project=>Object. Copies options
  9300. from project defaults to the currently selected object.
  9301. :return: None
  9302. """
  9303. self.report_usage("on_options_project2object")
  9304. self.options_read_form()
  9305. obj = self.collection.get_active()
  9306. if obj is None:
  9307. self.inform.emit('[WARNING_NOTCL] %s' %
  9308. _("No object selected."))
  9309. return
  9310. for option in self.options:
  9311. if option.find(obj.kind + "_") == 0:
  9312. oname = option[len(obj.kind) + 1:]
  9313. obj.options[oname] = self.options[option]
  9314. obj.to_form() # Update UI
  9315. def on_options_object2project(self):
  9316. """
  9317. Callback for Options->Transfer Options->Object=>Project. Copies options
  9318. from the currently selected object to project defaults.
  9319. :return: None
  9320. """
  9321. self.report_usage("on_options_object2project")
  9322. obj = self.collection.get_active()
  9323. if obj is None:
  9324. self.inform.emit('[WARNING_NOTCL] %s' %
  9325. _("No object selected."))
  9326. return
  9327. obj.read_form()
  9328. for option in obj.options:
  9329. if option in ['name']: # TODO: Handle this better...
  9330. continue
  9331. self.options[obj.kind + "_" + option] = obj.options[option]
  9332. self.options_write_form()
  9333. def on_options_object2app(self):
  9334. """
  9335. Callback for Options->Transfer Options->Object=>App. Copies options
  9336. from the currently selected object to application defaults.
  9337. :return: None
  9338. """
  9339. self.report_usage("on_options_object2app")
  9340. obj = self.collection.get_active()
  9341. if obj is None:
  9342. self.inform.emit('[WARNING_NOTCL] %s' %
  9343. _("No object selected."))
  9344. return
  9345. obj.read_form()
  9346. for option in obj.options:
  9347. if option in ['name']: # TODO: Handle this better...
  9348. continue
  9349. self.defaults[obj.kind + "_" + option] = obj.options[option]
  9350. self.defaults_write_form()
  9351. def on_options_app2object(self):
  9352. """
  9353. Callback for Options->Transfer Options->App=>Object. Copies options
  9354. from application defaults to the currently selected object.
  9355. :return: None
  9356. """
  9357. self.report_usage("on_options_app2object")
  9358. self.defaults_read_form()
  9359. obj = self.collection.get_active()
  9360. if obj is None:
  9361. self.inform.emit('[WARNING_NOTCL] %s' %
  9362. _("No object selected."))
  9363. return
  9364. for option in self.defaults:
  9365. if option.find(obj.kind + "_") == 0:
  9366. oname = option[len(obj.kind) + 1:]
  9367. obj.options[oname] = self.defaults[option]
  9368. obj.to_form() # Update UI
  9369. class ArgsThread(QtCore.QObject):
  9370. open_signal = pyqtSignal(list)
  9371. start = pyqtSignal()
  9372. if sys.platform == 'win32':
  9373. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  9374. else:
  9375. address = ('/tmp/testipc', 'AF_UNIX')
  9376. def __init__(self):
  9377. super(ArgsThread, self).__init__()
  9378. self.start.connect(self.run)
  9379. def my_loop(self, address):
  9380. try:
  9381. listener = Listener(*address)
  9382. while True:
  9383. conn = listener.accept()
  9384. self.serve(conn)
  9385. except socket.error as e:
  9386. conn = Client(*address)
  9387. conn.send(sys.argv)
  9388. conn.send('close')
  9389. # close the current instance only if there are args
  9390. if len(sys.argv) > 1:
  9391. sys.exit()
  9392. def serve(self, conn):
  9393. while True:
  9394. msg = conn.recv()
  9395. if msg == 'close':
  9396. break
  9397. self.open_signal.emit(msg)
  9398. conn.close()
  9399. # the decorator is a must; without it this technique will not work unless the start signal is connected
  9400. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  9401. @pyqtSlot()
  9402. def run(self):
  9403. self.my_loop(self.address)
  9404. class GracefulException(Exception):
  9405. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  9406. def __init__(self):
  9407. super().__init__()
  9408. def __str__(self):
  9409. return ('\n\n%s' % _("The user requested a graceful exit of the current task."))
  9410. # end of file