FlatCAMApp.py 510 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328
  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_headless = None
  67. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  68. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  69. "FlatCam.py --headless=1"
  70. try:
  71. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  72. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  73. "shellvar=",
  74. "headless=",
  75. "multiprocessing-fork="])
  76. except getopt.GetoptError:
  77. print(cmd_line_help)
  78. sys.exit(2)
  79. for opt, arg in cmd_line_options:
  80. if opt == '-h':
  81. print(cmd_line_help)
  82. sys.exit()
  83. elif opt == '--shellfile':
  84. cmd_line_shellfile = arg
  85. elif opt == '--shellvar':
  86. cmd_line_shellvar = arg
  87. elif opt == '--headless':
  88. try:
  89. cmd_line_headless = eval(arg)
  90. except NameError:
  91. pass
  92. # ## Logging ###
  93. log = logging.getLogger('base')
  94. log.setLevel(logging.DEBUG)
  95. # log.setLevel(logging.WARNING)
  96. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  97. handler = logging.StreamHandler()
  98. handler.setFormatter(formatter)
  99. log.addHandler(handler)
  100. # ##########################################################################
  101. # ################## Version and VERSION DATE ##############################
  102. # ##########################################################################
  103. version = 8.97
  104. version_date = "2019/09/20"
  105. beta = True
  106. # current date now
  107. date = str(datetime.today()).rpartition('.')[0]
  108. date = ''.join(c for c in date if c not in ':-')
  109. date = date.replace(' ', '_')
  110. # URL for update checks and statistics
  111. version_url = "http://flatcam.org/version"
  112. # App URL
  113. app_url = "http://flatcam.org"
  114. # Manual URL
  115. manual_url = "http://flatcam.org/manual/index.html"
  116. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  117. gerber_spec_url ="https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  118. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  119. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  120. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  121. # this variable will hold the project status
  122. # if True it will mean that the project was modified and not saved
  123. should_we_save = False
  124. # flag is True if saving action has been triggered
  125. save_in_progress = False
  126. # ###########################################################################
  127. # ############################# Signals ################################
  128. # ###########################################################################
  129. # Inform the user
  130. # Handled by:
  131. # * App.info() --> Print on the status bar
  132. inform = QtCore.pyqtSignal(str)
  133. app_quit = QtCore.pyqtSignal()
  134. # General purpose background task
  135. worker_task = QtCore.pyqtSignal(dict)
  136. # File opened
  137. # Handled by:
  138. # * register_folder()
  139. # * register_recent()
  140. # Note: Setting the parameters to unicode does not seem
  141. # to have an effect. Then are received as Qstring
  142. # anyway.
  143. # File type and filename
  144. file_opened = QtCore.pyqtSignal(str, str)
  145. # File type and filename
  146. file_saved = QtCore.pyqtSignal(str, str)
  147. # Percentage of progress
  148. progress = QtCore.pyqtSignal(int)
  149. plots_updated = QtCore.pyqtSignal()
  150. # Emitted by new_object() and passes the new object as argument, plot flag.
  151. # on_object_created() adds the object to the collection, plots on appropriate flag
  152. # and emits new_object_available.
  153. object_created = QtCore.pyqtSignal(object, bool, bool)
  154. # Emitted when a object has been changed (like scaled, mirrored)
  155. object_changed = QtCore.pyqtSignal(object)
  156. # Emitted after object has been plotted.
  157. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  158. object_plotted = QtCore.pyqtSignal(object)
  159. # Emitted when a new object has been added or deleted from/to the collection
  160. object_status_changed = QtCore.pyqtSignal(object, str)
  161. message = QtCore.pyqtSignal(str, str, str)
  162. # Emmited when shell command is finished(one command only)
  163. shell_command_finished = QtCore.pyqtSignal(object)
  164. # Emitted when multiprocess pool has been recreated
  165. pool_recreated = QtCore.pyqtSignal(object)
  166. # Emitted when an unhandled exception happens
  167. # in the worker task.
  168. thread_exception = QtCore.pyqtSignal(object)
  169. # used to signal that there are arguments for the app
  170. args_at_startup = QtCore.pyqtSignal(list)
  171. # a reusable signal to replot a list of objects
  172. # should be disconnected after use so it can be reused
  173. replot_signal = pyqtSignal(list)
  174. def __init__(self, user_defaults=True, post_gui=None):
  175. """
  176. Starts the application.
  177. :return: app
  178. :rtype: App
  179. """
  180. App.log.info("FlatCAM Starting...")
  181. self.main_thread = QtWidgets.QApplication.instance().thread()
  182. # ############################################################################
  183. # # ################# OS-specific ############################################
  184. # ############################################################################
  185. portable = False
  186. # Folder for user settings.
  187. if sys.platform == 'win32':
  188. # #########################################################################
  189. # Setup the listening thread for another instance launching with args #####
  190. # #########################################################################
  191. # make sure the thread is stored by using a self. otherwise it's garbage collected
  192. self.th = QtCore.QThread()
  193. self.th.start(priority=QtCore.QThread.LowestPriority)
  194. self.new_launch = ArgsThread()
  195. self.new_launch.open_signal[list].connect(self.on_startup_args)
  196. self.new_launch.moveToThread(self.th)
  197. self.new_launch.start.emit()
  198. from win32com.shell import shell, shellcon
  199. if platform.architecture()[0] == '32bit':
  200. App.log.debug("Win32!")
  201. else:
  202. App.log.debug("Win64!")
  203. # #########################################################################
  204. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  205. # #########################################################################
  206. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  207. try:
  208. with open(config_file, 'r'):
  209. pass
  210. except FileNotFoundError:
  211. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  212. try:
  213. with open(config_file, 'r') as f:
  214. try:
  215. for line in f:
  216. param = str(line).replace('\n', '').rpartition('=')
  217. if param[0] == 'portable':
  218. try:
  219. portable = eval(param[2])
  220. except NameError:
  221. portable = False
  222. if param[0] == 'headless':
  223. if param[2].lower() == 'true':
  224. self.cmd_line_headless = 1
  225. else:
  226. self.cmd_line_headless = None
  227. except Exception as e:
  228. log.debug('App.__init__() -->%s' % str(e))
  229. return
  230. except FileNotFoundError as e:
  231. log.debug(str(e))
  232. pass
  233. if portable is False:
  234. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  235. else:
  236. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  237. self.os = 'windows'
  238. else: # Linux/Unix/MacOS
  239. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  240. self.os = 'unix'
  241. # ##########################################################################
  242. # ################## Setup folders and files ###############################
  243. # ##########################################################################
  244. if not os.path.exists(self.data_path):
  245. os.makedirs(self.data_path)
  246. App.log.debug('Created data folder: ' + self.data_path)
  247. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  248. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  249. self.postprocessorpaths = os.path.join(self.data_path, 'postprocessors')
  250. if not os.path.exists(self.postprocessorpaths):
  251. os.makedirs(self.postprocessorpaths)
  252. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  253. # create current_defaults.FlatConfig file if there is none
  254. try:
  255. f = open(self.data_path + '/current_defaults.FlatConfig')
  256. f.close()
  257. except IOError:
  258. App.log.debug('Creating empty current_defaults.FlatConfig')
  259. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  260. json.dump({}, f)
  261. f.close()
  262. # create factory_defaults.FlatConfig file if there is none
  263. try:
  264. f = open(self.data_path + '/factory_defaults.FlatConfig')
  265. f.close()
  266. except IOError:
  267. App.log.debug('Creating empty factory_defaults.FlatConfig')
  268. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  269. json.dump({}, f)
  270. f.close()
  271. # create a recent files json file if there is none
  272. try:
  273. f = open(self.data_path + '/recent.json')
  274. f.close()
  275. except IOError:
  276. App.log.debug('Creating empty recent.json')
  277. f = open(self.data_path + '/recent.json', 'w')
  278. json.dump([], f)
  279. f.close()
  280. # create a recent projects json file if there is none
  281. try:
  282. fp = open(self.data_path + '/recent_projects.json')
  283. fp.close()
  284. except IOError:
  285. App.log.debug('Creating empty recent_projects.json')
  286. fp = open(self.data_path + '/recent_projects.json', 'w')
  287. json.dump([], fp)
  288. fp.close()
  289. # Application directory. CHDIR to it. Otherwise, trying to load
  290. # GUI icons will fail as their path is relative.
  291. # This will fail under cx_freeze ...
  292. self.app_home = os.path.dirname(os.path.realpath(__file__))
  293. App.log.debug("Application path is " + self.app_home)
  294. App.log.debug("Started in " + os.getcwd())
  295. # cx_freeze workaround
  296. if os.path.isfile(self.app_home):
  297. self.app_home = os.path.dirname(self.app_home)
  298. os.chdir(self.app_home)
  299. # #############################################################################
  300. # ##################### CREATE MULTIPROCESSING POOL ###########################
  301. # #############################################################################
  302. self.pool = Pool()
  303. # ##########################################################################
  304. # ################## Setting the Splash Screen #############################
  305. # ##########################################################################
  306. settings = QSettings("Open Source", "FlatCAM")
  307. if settings.contains("splash_screen"):
  308. show_splash = settings.value("splash_screen")
  309. else:
  310. settings.setValue('splash_screen', 1)
  311. # This will write the setting to the platform specific storage.
  312. del settings
  313. show_splash = 1
  314. if show_splash and self.cmd_line_headless != 1:
  315. splash_pix = QtGui.QPixmap('share/splash.png')
  316. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  317. # self.splash.setMask(splash_pix.mask())
  318. # move splashscreen to the current monitor
  319. desktop = QtWidgets.QApplication.desktop()
  320. screen = desktop.screenNumber(QtGui.QCursor.pos())
  321. current_screen_center = desktop.availableGeometry(screen).center()
  322. self.splash.move(current_screen_center - self.splash.rect().center())
  323. self.splash.show()
  324. self.splash.showMessage(_("FlatCAM is initializing ..."),
  325. alignment=Qt.AlignBottom | Qt.AlignLeft,
  326. color=QtGui.QColor("gray"))
  327. else:
  328. show_splash = 0
  329. # #############################################################################
  330. # ##################### Initialize GUI ########################################
  331. # #############################################################################
  332. # FlatCAM colors used in plotting
  333. self.FC_light_green = '#BBF268BF'
  334. self.FC_dark_green = '#006E20BF'
  335. self.FC_light_blue = '#a5a5ffbf'
  336. self.FC_dark_blue = '#0000ffbf'
  337. QtCore.QObject.__init__(self)
  338. self.ui = FlatCAMGUI(self.version, self.beta, self)
  339. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  340. self.ui.final_save.connect(self.final_save)
  341. # #############################################################################
  342. # ############################## Data #########################################
  343. # #############################################################################
  344. self.recent = []
  345. self.recent_projects = []
  346. self.clipboard = QtWidgets.QApplication.clipboard()
  347. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  348. self.project_filename = None
  349. self.toggle_units_ignore = False
  350. # self.defaults_form = PreferencesUI()
  351. # when adding entries here read the comments in the method found bellow named:
  352. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  353. self.defaults_form_fields = {
  354. # General App
  355. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  356. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  357. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  358. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  359. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  360. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  361. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  362. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  363. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  364. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  365. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  366. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  367. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  368. # General GUI Preferences
  369. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  370. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  371. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  372. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  373. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  374. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  375. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  376. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  377. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  378. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  379. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  380. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  381. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  382. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  383. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  384. # General GUI Settings
  385. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  386. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  387. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  388. "global_systray_icon": self.ui.general_defaults_form.general_gui_set_group.systray_cb,
  389. "global_shell_at_startup": self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb,
  390. "global_project_at_startup": self.ui.general_defaults_form.general_gui_set_group.project_startup_cb,
  391. "global_project_autohide": self.ui.general_defaults_form.general_gui_set_group.project_autohide_cb,
  392. "global_toggle_tooltips": self.ui.general_defaults_form.general_gui_set_group.toggle_tooltips_cb,
  393. "global_delete_confirmation": self.ui.general_defaults_form.general_gui_set_group.delete_conf_cb,
  394. # Gerber General
  395. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  396. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  397. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  398. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  399. # Gerber Options
  400. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  401. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  402. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  403. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  404. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  405. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  406. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  407. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  408. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  409. # Gerber Advanced Options
  410. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  411. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  412. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  413. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  414. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  415. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  416. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  417. # Gerber Export
  418. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  419. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  420. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  421. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  422. # Gerber Editor
  423. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  424. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  425. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  426. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  427. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  428. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  429. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  430. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  431. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  432. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  433. "gerber_editor_circ_angle":
  434. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  435. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  436. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  437. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  438. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  439. # Excellon General
  440. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  441. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  442. "excellon_format_upper_in":
  443. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  444. "excellon_format_lower_in":
  445. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  446. "excellon_format_upper_mm":
  447. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  448. "excellon_format_lower_mm":
  449. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  450. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  451. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  452. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  453. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  454. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  455. # Excellon Options
  456. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  457. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  458. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.eendz_entry,
  459. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  460. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  461. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  462. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  463. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  464. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  465. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  466. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  467. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  468. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  469. # Excellon Advanced Options
  470. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  471. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  472. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  473. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  474. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  475. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  476. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  477. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  478. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  479. # Excellon Export
  480. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  481. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  482. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  483. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  484. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  485. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  486. # Excellon Editor
  487. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  488. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  489. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  490. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  491. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  492. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  493. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  494. "excellon_editor_circ_angle":
  495. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  496. # Excellon Slots
  497. "excellon_editor_slot_direction":
  498. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  499. "excellon_editor_slot_angle":
  500. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  501. "excellon_editor_slot_length":
  502. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  503. # Excellon Slots
  504. "excellon_editor_slot_array_size":
  505. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  506. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  507. "excellon_editor_slot_lin_pitch":
  508. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  509. "excellon_editor_slot_lin_angle":
  510. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  511. "excellon_editor_slot_circ_dir":
  512. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  513. "excellon_editor_slot_circ_angle":
  514. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  515. # Geometry General
  516. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  517. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  518. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  519. # Geometry Options
  520. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  521. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  522. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  523. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  524. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  525. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  526. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  527. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  528. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  529. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  530. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.gendz_entry,
  531. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  532. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  533. # Geometry Advanced Options
  534. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  535. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  536. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  537. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  538. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  539. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  540. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  541. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  542. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  543. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  544. # Geometry Editor
  545. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  546. # CNCJob General
  547. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  548. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  549. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  550. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  551. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  552. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  553. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  554. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  555. # CNC Job Options
  556. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  557. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  558. # CNC Job Advanced Options
  559. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  560. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  561. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  562. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  563. # NCC Tool
  564. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  565. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  566. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  567. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  568. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  569. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  570. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  571. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  572. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  573. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  574. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  575. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  576. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  577. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  578. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  579. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  580. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  581. # CutOut Tool
  582. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  583. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  584. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  585. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  586. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  587. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  588. # Paint Area Tool
  589. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  590. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  591. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  592. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  593. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  594. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  595. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  596. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  597. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  598. # 2-sided Tool
  599. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  600. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  601. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  602. # Film Tool
  603. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  604. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  605. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  606. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  607. # Panelize Tool
  608. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  609. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  610. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  611. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  612. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  613. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  614. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  615. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  616. # Calculators Tool
  617. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  618. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  619. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  620. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  621. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  622. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  623. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  624. # Transformations Tool
  625. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  626. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  627. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  628. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  629. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  630. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  631. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  632. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  633. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  634. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  635. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  636. # SolderPaste Dispensing Tool
  637. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  638. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  639. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  640. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  641. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  642. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  643. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  644. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  645. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  646. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  647. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  648. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  649. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  650. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  651. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  652. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  653. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  654. # Utilities
  655. # File associations
  656. "fa_excellon": self.ui.util_defaults_form.fa_excellon_group.exc_list_text,
  657. "fa_gcode": self.ui.util_defaults_form.fa_gcode_group.gco_list_text,
  658. # "fa_geometry": self.ui.util_defaults_form.fa_geometry_group.close_paths_cb,
  659. "fa_gerber": self.ui.util_defaults_form.fa_gerber_group.grb_list_text,
  660. "util_autocomplete_keywords": self.ui.util_defaults_form.kw_group.kw_list_text,
  661. }
  662. # ############################
  663. # ### LOAD POSTPROCESSORS ####
  664. # ############################
  665. self.postprocessors = load_postprocessors(self)
  666. for name in list(self.postprocessors.keys()):
  667. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  668. if name.partition('_')[0] == 'Paste':
  669. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  670. continue
  671. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  672. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  673. if name == 'hpgl':
  674. continue
  675. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  676. # ############################
  677. # ### LOAD LANGUAGES ####
  678. # ############################
  679. self.languages = fcTranslate.load_languages()
  680. for name in sorted(self.languages.values()):
  681. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  682. self.defaults = LoudDict()
  683. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  684. self.defaults.update({
  685. # Global APP Preferences
  686. "first_run": True,
  687. "units": "IN",
  688. "global_serial": 0,
  689. "global_stats": {},
  690. "global_tabs_detachable": True,
  691. "global_app_level": 'b',
  692. "global_portable": False,
  693. "global_language": 'English',
  694. "global_version_check": True,
  695. "global_send_stats": True,
  696. "global_pan_button": '2',
  697. "global_mselect_key": 'Control',
  698. "global_project_at_startup": False,
  699. "global_systray_icon": True,
  700. "global_project_autohide": True,
  701. "global_toggle_tooltips": True,
  702. "global_worker_number": 2,
  703. "global_tolerance": 0.005,
  704. "global_open_style": True,
  705. "global_delete_confirmation": True,
  706. "global_compression_level": 3,
  707. "global_save_compressed": True,
  708. # Global GUI Preferences
  709. "global_gridx": 0.0393701,
  710. "global_gridy": 0.0393701,
  711. "global_snap_max": 0.001968504,
  712. "global_workspace": False,
  713. "global_workspaceT": "A4P",
  714. "global_grid_context_menu": {
  715. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  716. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  717. },
  718. "global_plot_fill": '#BBF268BF',
  719. "global_plot_line": '#006E20BF',
  720. "global_sel_fill": '#a5a5ffbf',
  721. "global_sel_line": '#0000ffbf',
  722. "global_alt_sel_fill": '#BBF268BF',
  723. "global_alt_sel_line": '#006E20BF',
  724. "global_draw_color": '#FF0000',
  725. "global_sel_draw_color": '#0000FF',
  726. "global_proj_item_color": '#000000',
  727. "global_proj_item_dis_color": '#b7b7cb',
  728. "global_toolbar_view": 511,
  729. "global_background_timeout": 300000, # Default value is 5 minutes
  730. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  731. # (python trace only for unknown errors),
  732. # 1 = show trace(show trace always),
  733. # 2 = (For the future).
  734. # Persistence
  735. "global_last_folder": None,
  736. "global_last_save_folder": None,
  737. # Default window geometry
  738. "global_def_win_x": 100,
  739. "global_def_win_y": 100,
  740. "global_def_win_w": 1024,
  741. "global_def_win_h": 650,
  742. "global_def_notebook_width": 1,
  743. # Constants...
  744. "global_defaults_save_period_ms": 20000, # Time between default saves.
  745. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  746. "global_shell_at_startup": False, # Show the shell at startup.
  747. "global_recent_limit": 10, # Max. items in recent list.
  748. "fit_key": 'V',
  749. "zoom_out_key": '-',
  750. "zoom_in_key": '=',
  751. "grid_toggle_key": 'G',
  752. "global_zoom_ratio": 1.5,
  753. "global_point_clipboard_format": "(%.4f, %.4f)",
  754. "global_zdownrate": None,
  755. # General GUI Settings
  756. "global_hover": False,
  757. "global_selection_shape": True,
  758. "global_layout": "compact",
  759. # Gerber General
  760. "gerber_plot": True,
  761. "gerber_solid": True,
  762. "gerber_multicolored": False,
  763. "gerber_circle_steps": 128,
  764. "gerber_use_buffer_for_union": True,
  765. # Gerber Options
  766. "gerber_isotooldia": 0.00787402,
  767. "gerber_isopasses": 1,
  768. "gerber_isooverlap": 0.00393701,
  769. "gerber_milling_type": "cl",
  770. "gerber_combine_passes": False,
  771. "gerber_noncoppermargin": 0.00393701,
  772. "gerber_noncopperrounded": False,
  773. "gerber_bboxmargin": 0.00393701,
  774. "gerber_bboxrounded": False,
  775. # Gerber Advanced Options
  776. "gerber_aperture_display": False,
  777. "gerber_aperture_scale_factor": 1.0,
  778. "gerber_aperture_buffer_factor": 0.0,
  779. "gerber_follow": False,
  780. "gerber_buffering": "full",
  781. "gerber_simplification": False,
  782. "gerber_simp_tolerance": 0.0005,
  783. # Gerber Export
  784. "gerber_exp_units": 'IN',
  785. "gerber_exp_integer": 2,
  786. "gerber_exp_decimals": 4,
  787. "gerber_exp_zeros": 'L',
  788. # Gerber Editor
  789. "gerber_editor_sel_limit": 30,
  790. "gerber_editor_newcode": 10,
  791. "gerber_editor_newsize": 0.8,
  792. "gerber_editor_newtype": 'C',
  793. "gerber_editor_newdim": "0.5, 0.5",
  794. "gerber_editor_array_size": 5,
  795. "gerber_editor_lin_axis": 'X',
  796. "gerber_editor_lin_pitch": 1,
  797. "gerber_editor_lin_angle": 0.0,
  798. "gerber_editor_circ_dir": 'CW',
  799. "gerber_editor_circ_angle": 0.0,
  800. "gerber_editor_scale_f": 1.0,
  801. "gerber_editor_buff_f": 0.1,
  802. "gerber_editor_ma_low": 0.0,
  803. "gerber_editor_ma_high": 1.0,
  804. # Excellon General
  805. "excellon_plot": True,
  806. "excellon_solid": True,
  807. "excellon_format_upper_in": 2,
  808. "excellon_format_lower_in": 4,
  809. "excellon_format_upper_mm": 3,
  810. "excellon_format_lower_mm": 3,
  811. "excellon_zeros": "L",
  812. "excellon_units": "INCH",
  813. "excellon_update": True,
  814. "excellon_optimization_type": 'B',
  815. "excellon_search_time": 3,
  816. # Excellon Options
  817. "excellon_drillz": -0.0590551,
  818. "excellon_travelz": 0.0787402,
  819. "excellon_endz": 0.5,
  820. "excellon_feedrate": 3.14961,
  821. "excellon_spindlespeed": None,
  822. "excellon_dwell": False,
  823. "excellon_dwelltime": 1,
  824. "excellon_toolchange": False,
  825. "excellon_toolchangez": 0.5,
  826. "excellon_ppname_e": 'default',
  827. "excellon_tooldia": 0.0314961,
  828. "excellon_slot_tooldia": 0.0708661,
  829. "excellon_gcode_type": "drills",
  830. # Excellon Advanced Options
  831. "excellon_offset": 0.0,
  832. "excellon_toolchangexy": "0.0, 0.0",
  833. "excellon_startz": None,
  834. "excellon_feedrate_rapid": 31.4961,
  835. "excellon_z_pdepth": -0.02,
  836. "excellon_feedrate_probe": 3.14961,
  837. "excellon_spindledir": 'CW',
  838. "excellon_f_plunge": False,
  839. "excellon_f_retract": False,
  840. # Excellon Export
  841. "excellon_exp_units": 'INCH',
  842. "excellon_exp_format": 'ndec',
  843. "excellon_exp_integer": 2,
  844. "excellon_exp_decimals": 4,
  845. "excellon_exp_zeros": 'LZ',
  846. "excellon_exp_slot_type": 'routing',
  847. # Excellon Editor
  848. "excellon_editor_sel_limit": 30,
  849. "excellon_editor_newdia": 0.039,
  850. "excellon_editor_array_size": 5,
  851. "excellon_editor_lin_dir": 'X',
  852. "excellon_editor_lin_pitch": 0.1,
  853. "excellon_editor_lin_angle": 0.0,
  854. "excellon_editor_circ_dir": 'CW',
  855. "excellon_editor_circ_angle": 12,
  856. # Excellon Slots
  857. "excellon_editor_slot_direction": 'X',
  858. "excellon_editor_slot_angle": 0.0,
  859. "excellon_editor_slot_length": 5.0,
  860. # Excellon Slot Array
  861. "excellon_editor_slot_array_size": 5,
  862. "excellon_editor_slot_lin_dir": 'X',
  863. "excellon_editor_slot_lin_pitch": 0.1,
  864. "excellon_editor_slot_lin_angle": 0.0,
  865. "excellon_editor_slot_circ_dir": 'CW',
  866. "excellon_editor_slot_circ_angle": 0.0,
  867. # Geometry General
  868. "geometry_plot": True,
  869. "geometry_circle_steps": 128,
  870. "geometry_cnctooldia": "0.0944882",
  871. # Geometry Options
  872. "geometry_cutz": -0.0944882,
  873. "geometry_vtipdia": 0.1,
  874. "geometry_vtipangle": 30,
  875. "geometry_multidepth": False,
  876. "geometry_depthperpass": 0.0314961,
  877. "geometry_travelz": 0.0787402,
  878. "geometry_toolchange": False,
  879. "geometry_toolchangez": 0.5,
  880. "geometry_endz": 0.5,
  881. "geometry_feedrate": 3.14961,
  882. "geometry_feedrate_z": 3.14961,
  883. "geometry_spindlespeed": None,
  884. "geometry_dwell": False,
  885. "geometry_dwelltime": 1,
  886. "geometry_ppname_g": 'default',
  887. # Geometry Advanced Options
  888. "geometry_toolchangexy": "0.0, 0.0",
  889. "geometry_startz": None,
  890. "geometry_feedrate_rapid": 3.14961,
  891. "geometry_extracut": False,
  892. "geometry_z_pdepth": -0.02,
  893. "geometry_f_plunge": False,
  894. "geometry_spindledir": 'CW',
  895. "geometry_feedrate_probe": 3.14961,
  896. "geometry_segx": 0.0,
  897. "geometry_segy": 0.0,
  898. # Geometry Editor
  899. "geometry_editor_sel_limit": 30,
  900. # CNC Job General
  901. "cncjob_plot": True,
  902. "cncjob_plot_kind": 'all',
  903. "cncjob_annotation": True,
  904. "cncjob_tooldia": 0.0393701,
  905. "cncjob_coords_type": "G90",
  906. "cncjob_coords_decimals": 4,
  907. "cncjob_fr_decimals": 2,
  908. "cncjob_steps_per_circle": 128,
  909. # CNC Job Options
  910. "cncjob_prepend": "",
  911. "cncjob_append": "",
  912. # CNC Job Advanced Options
  913. "cncjob_toolchange_macro": "",
  914. "cncjob_toolchange_macro_enable": False,
  915. "cncjob_annotation_fontsize": 9,
  916. "cncjob_annotation_fontcolor": '#990000',
  917. # NCC Tool
  918. "tools_ncctools": "0.0393701, 0.019685",
  919. "tools_nccorder": 'rev',
  920. "tools_nccoverlap": 0.015748,
  921. "tools_nccmargin": 0.0393701,
  922. "tools_nccmethod": "seed",
  923. "tools_nccconnect": True,
  924. "tools_ncccontour": True,
  925. "tools_nccrest": False,
  926. "tools_ncc_offset_choice": False,
  927. "tools_ncc_offset_value": 0.0000,
  928. "tools_nccref": 'itself',
  929. "tools_ncc_plotting": 'normal',
  930. "tools_nccmilling_type": 'cl',
  931. "tools_ncctool_type": 'V',
  932. "tools_ncccutz": -0.001968504,
  933. "tools_ncctipdia": 0.00393701,
  934. "tools_ncctipangle": 30,
  935. # Cutout Tool
  936. "tools_cutouttooldia": 0.0944882,
  937. "tools_cutoutkind": "single",
  938. "tools_cutoutmargin": 0.00393701,
  939. "tools_cutoutgapsize": 0.15748,
  940. "tools_gaps_ff": "4",
  941. "tools_cutout_convexshape": False,
  942. # Paint Tool
  943. "tools_painttooldia": 0.023622,
  944. "tools_paintorder": 'rev',
  945. "tools_paintoverlap": 0.015748,
  946. "tools_paintmargin": 0.0,
  947. "tools_paintmethod": "seed",
  948. "tools_selectmethod": "single",
  949. "tools_pathconnect": True,
  950. "tools_paintcontour": True,
  951. "tools_paint_plotting": 'normal',
  952. # 2-Sided Tool
  953. "tools_2sided_mirror_axis": "X",
  954. "tools_2sided_axis_loc": "point",
  955. "tools_2sided_drilldia": 0.11811,
  956. # Film Tool
  957. "tools_film_type": 'neg',
  958. "tools_film_boundary": 0.0393701,
  959. "tools_film_scale": 0,
  960. "tools_film_color": '#000000',
  961. # Panel Tool
  962. "tools_panelize_spacing_columns": 0,
  963. "tools_panelize_spacing_rows": 0,
  964. "tools_panelize_columns": 1,
  965. "tools_panelize_rows": 1,
  966. "tools_panelize_constrain": False,
  967. "tools_panelize_constrainx": 0.0,
  968. "tools_panelize_constrainy": 0.0,
  969. "tools_panelize_panel_type": 'gerber',
  970. # Calculators Tool
  971. "tools_calc_vshape_tip_dia": 0.007874,
  972. "tools_calc_vshape_tip_angle": 30,
  973. "tools_calc_vshape_cut_z": 0.000787,
  974. "tools_calc_electro_length": 10.0,
  975. "tools_calc_electro_width": 10.0,
  976. "tools_calc_electro_cdensity": 13.0,
  977. "tools_calc_electro_growth": 10.0,
  978. # Transform Tool
  979. "tools_transform_rotate": 90,
  980. "tools_transform_skew_x": 0.0,
  981. "tools_transform_skew_y": 0.0,
  982. "tools_transform_scale_x": 1.0,
  983. "tools_transform_scale_y": 1.0,
  984. "tools_transform_scale_link": True,
  985. "tools_transform_scale_reference": True,
  986. "tools_transform_offset_x": 0.0,
  987. "tools_transform_offset_y": 0.0,
  988. "tools_transform_mirror_reference": False,
  989. "tools_transform_mirror_point": (0, 0),
  990. # SolderPaste Tool
  991. "tools_solderpaste_tools": "0.0393701, 0.011811",
  992. "tools_solderpaste_new": 0.011811,
  993. "tools_solderpaste_z_start": 0.00019685039,
  994. "tools_solderpaste_z_dispense": 0.00393701,
  995. "tools_solderpaste_z_stop": 0.00019685039,
  996. "tools_solderpaste_z_travel": 0.00393701,
  997. "tools_solderpaste_z_toolchange": 0.0393701,
  998. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  999. "tools_solderpaste_frxy": 3.0,
  1000. "tools_solderpaste_frz": 3.0,
  1001. "tools_solderpaste_frz_dispense": 0.0393701,
  1002. "tools_solderpaste_speedfwd": 20,
  1003. "tools_solderpaste_dwellfwd": 1,
  1004. "tools_solderpaste_speedrev": 10,
  1005. "tools_solderpaste_dwellrev": 1,
  1006. "tools_solderpaste_pp": 'Paste_1',
  1007. # Subtract Tool
  1008. "tools_sub_close_paths": True,
  1009. # Utilities
  1010. # file associations
  1011. "fa_excellon": 'drd, drl, exc, ncd, tap, xln',
  1012. "fa_gcode": 'cnc, din, dnc, ecs, eia, fan, fgc, fnc, gc, gcd, gcode, h, hnc, i, min, mpf, mpr, nc, ncc, '
  1013. 'ncg, ncp, out, plt, ply, rol, sbp, tap, xpi',
  1014. "fa_gerber": 'art, bot, bsm, cmp, crc, crs, dim, g4, gb0, gb1, gb2, gb3, gb5, gb6, gb7, gb8, gb9, gbd, '
  1015. 'gbl, gbo, gbp, gbr, gbs, gdo, ger, gko, gm1, gm2, gm3, grb, gtl, gto, gtp, gts, ly15, ly2, '
  1016. 'mil, pho, plc, pls, smb, smt, sol, spb, spt, ssb, sst, stc, sts, top, tsm',
  1017. # Keyword list
  1018. "util_autocomplete_keywords": 'Desktop, Documents, FlatConfig, FlatPrj, Marius, My Documents, Paste_1, '
  1019. 'Repetier, Roland_MDX_20, Toolchange_Custom, Toolchange_Probe_MACH3, '
  1020. 'Toolchange_manual, Users, all, angle_x, angle_y, axis, axisoffset, box, '
  1021. 'center_x, center_y, columns, combine, connect, contour, default, '
  1022. 'depthperpass, dia, diatol, dist, drilled_dias, drillz, dwell, dwelltime, '
  1023. 'feedrate_z, grbl_11, grbl_laser, gridoffsety, gridx, gridy, has_offset, '
  1024. 'holes, hpgl, iso_type, line_xyz, margin, marlin, method, milled_dias, '
  1025. 'minoffset, multidepth, name, offset, opt_type, order, outname, overlap, '
  1026. 'passes, postamble, pp, ppname_e, ppname_g, preamble, radius, ref, rest, '
  1027. 'rows, shellvar_, scale_factor, spacing_columns, spacing_rows, spindlespeed, '
  1028. 'toolchange_xy, use_threads, value, x, x0, x1, y, y0, y1, z_cut, z_move'
  1029. ,
  1030. })
  1031. # ############################################################
  1032. # ############### Load defaults from file ####################
  1033. # ############################################################
  1034. if user_defaults:
  1035. self.load_defaults(filename='current_defaults')
  1036. # #############################################################
  1037. # ############## APPLY APP LANGUAGE ###########################
  1038. # #############################################################
  1039. ret_val = fcTranslate.apply_language('strings')
  1040. if ret_val == "no language":
  1041. self.inform.emit('[ERROR] %s' %
  1042. _("Could not find the Language files. The App strings are missing."))
  1043. log.debug("Could not find the Language files. The App strings are missing.")
  1044. else:
  1045. # make the current language the current selection on the language combobox
  1046. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1047. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1048. # ##############################################################
  1049. # ################# CREATE UNIQUE SERIAL NUMBER ################
  1050. # ##############################################################
  1051. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1052. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1053. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  1054. self.save_defaults(silent=True)
  1055. self.propagate_defaults(silent=True)
  1056. self.restore_main_win_geom()
  1057. def auto_save_defaults():
  1058. try:
  1059. self.save_defaults(silent=True)
  1060. self.propagate_defaults(silent=True)
  1061. finally:
  1062. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1063. # the following lines activates automatic defaults save
  1064. # if user_defaults:
  1065. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1066. # self.options_form = PreferencesUI()
  1067. self.options_form_fields = {
  1068. "units": self.ui.general_options_form.general_app_group.units_radio,
  1069. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  1070. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  1071. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  1072. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  1073. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  1074. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  1075. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  1076. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  1077. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  1078. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  1079. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  1080. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  1081. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  1082. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  1083. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  1084. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  1085. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  1086. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  1087. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  1088. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  1089. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  1090. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  1091. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  1092. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  1093. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  1094. "excellon_endz": self.ui.excellon_options_form.excellon_opt_group.eendz_entry,
  1095. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  1096. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  1097. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  1098. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  1099. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  1100. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  1101. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  1102. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  1103. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1104. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  1105. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  1106. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  1107. "excellon_spindledir": self.ui.excellon_options_form.excellon_adv_opt_group.spindledir_radio,
  1108. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  1109. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  1110. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  1111. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  1112. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  1113. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  1114. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  1115. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  1116. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  1117. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  1118. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  1119. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  1120. "geometry_endz": self.ui.geometry_options_form.geometry_opt_group.gendz_entry,
  1121. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  1122. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  1123. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  1124. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  1125. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1126. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  1127. "geometry_spindledir": self.ui.geometry_options_form.geometry_adv_opt_group.spindledir_radio,
  1128. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  1129. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  1130. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  1131. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  1132. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  1133. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  1134. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  1135. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  1136. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  1137. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  1138. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  1139. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  1140. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  1141. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  1142. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  1143. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  1144. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  1145. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  1146. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  1147. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  1148. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  1149. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  1150. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  1151. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  1152. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  1153. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  1154. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  1155. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  1156. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  1157. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  1158. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  1159. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  1160. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  1161. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  1162. }
  1163. for name in list(self.postprocessors.keys()):
  1164. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1165. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1166. self.options = LoudDict()
  1167. self.options.set_change_callback(self.on_options_dict_change)
  1168. self.options.update({
  1169. "units": "IN",
  1170. "global_gridx": 1.0,
  1171. "global_gridy": 1.0,
  1172. "global_snap_max": 0.05,
  1173. "global_background_timeout": 300000, # Default value is 5 minutes
  1174. "global_verbose_error_level": 0, # Shell verbosity:
  1175. # 0 = default(python trace only for unknown errors),
  1176. # 1 = show trace(show trace allways), 2 = (For the future).
  1177. "gerber_plot": True,
  1178. "gerber_solid": True,
  1179. "gerber_multicolored": False,
  1180. "gerber_isotooldia": 0.016,
  1181. "gerber_isopasses": 1,
  1182. "gerber_isooverlap": 0.15,
  1183. "gerber_combine_passes": True,
  1184. "gerber_noncoppermargin": 0.0,
  1185. "gerber_noncopperrounded": False,
  1186. "gerber_bboxmargin": 0.0,
  1187. "gerber_bboxrounded": False,
  1188. "excellon_plot": True,
  1189. "excellon_solid": False,
  1190. "excellon_format_upper_in": 2,
  1191. "excellon_format_lower_in": 4,
  1192. "excellon_format_upper_mm": 3,
  1193. "excellon_format_lower_mm": 3,
  1194. "excellon_units": 'INCH',
  1195. "excellon_optimization_type": 'B',
  1196. "excellon_search_time": 3,
  1197. "excellon_zeros": "L",
  1198. "excellon_drillz": -0.1,
  1199. "excellon_travelz": 0.1,
  1200. "excellon_feedrate": 3.0,
  1201. "excellon_feedrate_rapid": 3.0,
  1202. "excellon_spindlespeed": None,
  1203. "excellon_spindledir": 'CW',
  1204. "excellon_dwell": True,
  1205. "excellon_dwelltime": 1000,
  1206. "excellon_toolchange": False,
  1207. "excellon_toolchangez": 1.0,
  1208. "excellon_toolchangexy": "0.0, 0.0",
  1209. "excellon_tooldia": 0.016,
  1210. "excellon_ppname_e": 'default',
  1211. "excellon_f_plunge": False,
  1212. "excellon_startz": None,
  1213. "excellon_endz": 2.0,
  1214. "geometry_plot": True,
  1215. "geometry_segx": 0.0,
  1216. "geometry_segy": 0.0,
  1217. "geometry_cutz": -0.002,
  1218. "geometry_vtipdia": 0.1,
  1219. "geometry_vtipangle": 30,
  1220. "geometry_travelz": 0.1,
  1221. "geometry_feedrate": 3.0,
  1222. "geometry_feedrate_z": 3.0,
  1223. "geometry_feedrate_rapid": 3.0,
  1224. "geometry_spindlespeed": None,
  1225. "geometry_spindledir": 'CW',
  1226. "geometry_dwell": True,
  1227. "geometry_dwelltime": 1000,
  1228. "geometry_cnctooldia": 0.016,
  1229. "geometry_toolchange": False,
  1230. "geometry_toolchangez": 2.0,
  1231. "geometry_toolchangexy": "0.0, 0.0",
  1232. "geometry_startz": None,
  1233. "geometry_endz": 2.0,
  1234. "geometry_ppname_g": "default",
  1235. "geometry_f_plunge": False,
  1236. "geometry_depthperpass": 0.002,
  1237. "geometry_multidepth": False,
  1238. "geometry_extracut": False,
  1239. "cncjob_plot": True,
  1240. "cncjob_tooldia": 0.016,
  1241. "cncjob_prepend": "",
  1242. "cncjob_append": "",
  1243. "tools_ncctools": "1.0, 0.5",
  1244. "tools_nccoverlap": 0.4,
  1245. "tools_nccmargin": 1,
  1246. "tools_cutouttooldia": 0.07,
  1247. "tools_cutoutmargin": 0.1,
  1248. "tools_cutoutgapsize": 0.15,
  1249. "tools_gaps_ff": "8",
  1250. "tools_painttooldia": 0.07,
  1251. "tools_paintoverlap": 0.15,
  1252. "tools_paintmargin": 0.0,
  1253. "tools_paintmethod": "seed",
  1254. "tools_selectmethod": "single",
  1255. "tools_pathconnect": True,
  1256. "tools_paintcontour": True,
  1257. "tools_2sided_mirror_axis": "X",
  1258. "tools_2sided_axis_loc": 'point',
  1259. "tools_2sided_drilldia": 1,
  1260. "tools_film_type": 'neg',
  1261. "tools_film_boundary": 1,
  1262. "tools_film_scale": 0,
  1263. "tools_panelize_spacing_columns": 0,
  1264. "tools_panelize_spacing_rows": 0,
  1265. "tools_panelize_columns": 1,
  1266. "tools_panelize_rows": 1,
  1267. "tools_panelize_constrain": False,
  1268. "tools_panelize_constrainx": 0.0,
  1269. "tools_panelize_constrainy": 0.0
  1270. })
  1271. self.options.update(self.defaults) # Copy app defaults to project options
  1272. self.gen_form = None
  1273. self.ger_form = None
  1274. self.exc_form = None
  1275. self.geo_form = None
  1276. self.cnc_form = None
  1277. self.tools_form = None
  1278. self.fa_form = None
  1279. self.on_options_combo_change(0) # Will show the initial form
  1280. # ################################
  1281. # ### Initialize the color box's color in Preferences -> Global -> Color
  1282. # Init Plot Colors
  1283. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  1284. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  1285. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  1286. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  1287. int(self.defaults['global_plot_fill'][7:9], 16))
  1288. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  1289. int(self.defaults['global_plot_fill'][7:9], 16))
  1290. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  1291. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  1292. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  1293. # Init Left-Right Selection colors
  1294. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  1295. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  1296. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  1297. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1298. int(self.defaults['global_sel_fill'][7:9], 16))
  1299. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1300. int(self.defaults['global_sel_fill'][7:9], 16))
  1301. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1302. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1303. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  1304. # Init Right-Left Selection colors
  1305. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1306. self.defaults['global_alt_sel_fill'])
  1307. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1308. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  1309. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1310. int(self.defaults['global_sel_fill'][7:9], 16))
  1311. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1312. int(self.defaults['global_sel_fill'][7:9], 16))
  1313. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1314. self.defaults['global_alt_sel_line'])
  1315. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1316. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  1317. # Init Draw color and Selection Draw Color
  1318. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1319. self.defaults['global_draw_color'])
  1320. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1321. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1322. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1323. self.defaults['global_sel_draw_color'])
  1324. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1325. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1326. # Init Project Items color
  1327. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1328. self.defaults['global_proj_item_color'])
  1329. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1330. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1331. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1332. self.defaults['global_proj_item_dis_color'])
  1333. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1334. "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1335. # Init the Annotation CNC Job color
  1336. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  1337. self.defaults['cncjob_annotation_fontcolor'])
  1338. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  1339. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  1340. # Init the Tool Film color
  1341. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  1342. self.defaults['tools_film_color'])
  1343. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  1344. "background-color:%s" % str(self.defaults['tools_film_color'])[:7])
  1345. # ### End of Data ####
  1346. # ###############################################
  1347. # ############# SETUP Plot Area #################
  1348. # ###############################################
  1349. if show_splash:
  1350. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1351. "Canvas initialization started."),
  1352. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1353. color=QtGui.QColor("gray"))
  1354. start_plot_time = time.time() # debug
  1355. self.plotcanvas = None
  1356. self.app_cursor = None
  1357. self.hover_shapes = None
  1358. self.on_plotcanvas_setup()
  1359. end_plot_time = time.time()
  1360. self.used_time = end_plot_time - start_plot_time
  1361. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1362. if show_splash:
  1363. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1364. "Canvas initialization started.\n"
  1365. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1366. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1367. color=QtGui.QColor("gray"))
  1368. self.ui.splitter.setStretchFactor(1, 2)
  1369. # #################################################################
  1370. # ####################### SYS TRAY ################################
  1371. # #################################################################
  1372. if self.defaults["global_systray_icon"]:
  1373. self.parent_w = QtWidgets.QWidget()
  1374. if self.cmd_line_headless == 1:
  1375. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1376. headless=True,
  1377. parent=self.parent_w)
  1378. else:
  1379. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1380. parent=self.parent_w)
  1381. # ##############################################
  1382. # ######### SETUP OBJECT COLLECTION ############
  1383. # ##############################################
  1384. self.collection = ObjectCollection(self)
  1385. self.ui.project_tab_layout.addWidget(self.collection.view)
  1386. # ### Adjust tabs width ## ##
  1387. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1388. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1389. self.collection.view.setMinimumWidth(290)
  1390. self.log.debug("Finished creating Object Collection.")
  1391. # ###############################################
  1392. # ############# Worker SETUP ####################
  1393. # ###############################################
  1394. if self.defaults["global_worker_number"]:
  1395. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1396. else:
  1397. self.workers = WorkerStack(workers_number=2)
  1398. self.worker_task.connect(self.workers.add_task)
  1399. self.log.debug("Finished creating Workers crew.")
  1400. # ################################################
  1401. # ############### Signal handling ################
  1402. # ################################################
  1403. # ############# Custom signals ##################
  1404. # signal for displaying messages in status bar
  1405. self.inform.connect(self.info)
  1406. # signal to be called when the app is quiting
  1407. self.app_quit.connect(self.quit_application)
  1408. self.message.connect(self.message_dialog)
  1409. self.progress.connect(self.set_progress_bar)
  1410. # signals that are emitted when object state changes
  1411. self.object_created.connect(self.on_object_created)
  1412. self.object_changed.connect(self.on_object_changed)
  1413. self.object_plotted.connect(self.on_object_plotted)
  1414. self.plots_updated.connect(self.on_plots_updated)
  1415. # signals emitted when file state change
  1416. self.file_opened.connect(self.register_recent)
  1417. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1418. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1419. # ############# Standard signals ###################
  1420. # ### Menu
  1421. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1422. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1423. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1424. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1425. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1426. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1427. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1428. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1429. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1430. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1431. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1432. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1433. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1434. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1435. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1436. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1437. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1438. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1439. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1440. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1441. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1442. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1443. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1444. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1445. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1446. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1447. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1448. self.ui.menufile_exit.triggered.connect(self.final_save)
  1449. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1450. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1451. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1452. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1453. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1454. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1455. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1456. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1457. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1458. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1459. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1460. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1461. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1462. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1463. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1464. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1465. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1466. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1467. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1468. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1469. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1470. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1471. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1472. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1473. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1474. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1475. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1476. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1477. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1478. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1479. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1480. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1481. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1482. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1483. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1484. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1485. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1486. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1487. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1488. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1489. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1490. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1491. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1492. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1493. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1494. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1495. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1496. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1497. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1498. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1499. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1500. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1501. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1502. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1503. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1504. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1505. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1506. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1507. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1508. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1509. # ToolBar signals
  1510. self.connect_toolbar_signals()
  1511. # Notebook signals
  1512. # make the right click on the notebook tab connect to a function
  1513. self.ui.notebook.setupContextMenu()
  1514. self.ui.notebook.addContextMenu(
  1515. _("Detachable Tabs"), self.on_notebook_tab_rmb_click,
  1516. initial_checked=self.defaults["global_tabs_detachable"])
  1517. # activate initial state
  1518. self.on_notebook_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1519. # Context Menu
  1520. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1521. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1522. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1523. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1524. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1525. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1526. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1527. self.ui.clearplot.triggered.connect(self.clear_plots)
  1528. self.ui.replot.triggered.connect(self.plot_all)
  1529. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1530. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1531. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1532. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1533. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1534. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1535. # Preferences Plot Area TAB
  1536. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1537. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1538. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1539. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1540. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1541. # ##############################
  1542. # ### GUI PREFERENCES SIGNALS ##
  1543. # ##############################
  1544. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1545. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1546. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1547. )
  1548. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1549. lambda: self.on_toggle_units(no_pref=False))
  1550. # ###############################################################
  1551. # ################### GUI COLORS SIGNALS ########################
  1552. # ###############################################################
  1553. # Setting plot colors signals
  1554. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1555. self.on_pf_color_entry)
  1556. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1557. self.on_pf_color_button)
  1558. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1559. self.on_pf_color_spinner)
  1560. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1561. self.on_pf_color_slider)
  1562. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1563. self.on_pl_color_entry)
  1564. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1565. self.on_pl_color_button)
  1566. # Setting selection (left - right) colors signals
  1567. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1568. self.on_sf_color_entry)
  1569. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1570. self.on_sf_color_button)
  1571. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1572. self.on_sf_color_spinner)
  1573. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1574. self.on_sf_color_slider)
  1575. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1576. self.on_sl_color_entry)
  1577. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1578. self.on_sl_color_button)
  1579. # Setting selection (right - left) colors signals
  1580. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1581. self.on_alt_sf_color_entry)
  1582. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1583. self.on_alt_sf_color_button)
  1584. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1585. self.on_alt_sf_color_spinner)
  1586. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1587. self.on_alt_sf_color_slider)
  1588. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1589. self.on_alt_sl_color_entry)
  1590. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1591. self.on_alt_sl_color_button)
  1592. # Setting Editor Draw colors signals
  1593. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1594. self.on_draw_color_entry)
  1595. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1596. self.on_draw_color_button)
  1597. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1598. self.on_sel_draw_color_entry)
  1599. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1600. self.on_sel_draw_color_button)
  1601. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1602. self.on_proj_color_entry)
  1603. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1604. self.on_proj_color_button)
  1605. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1606. self.on_proj_color_dis_entry)
  1607. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1608. self.on_proj_color_dis_button)
  1609. # ########## workspace setting signals ###########
  1610. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1611. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1612. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1613. # ########## CNC Job related signals #############
  1614. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1615. self.on_cnc_custom_parameters)
  1616. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.editingFinished.connect(
  1617. self.on_annotation_fontcolor_entry)
  1618. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.clicked.connect(
  1619. self.on_annotation_fontcolor_button)
  1620. # ########## Tools related signals #############
  1621. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1622. self.on_film_color_entry)
  1623. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1624. self.on_film_color_button)
  1625. # ########## Modify G-CODE Plot Area TAB ###########
  1626. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1627. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1628. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1629. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1630. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1631. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1632. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1633. # portability changed signal
  1634. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1635. # Object list
  1636. self.collection.view.activated.connect(self.on_row_activated)
  1637. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1638. self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1639. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1640. # Export Excellon parameters.
  1641. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1642. self.on_update_exc_export
  1643. )
  1644. # call it once to make sure it is updated at startup
  1645. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1646. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1647. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1648. self.on_excellon_defaults_button)
  1649. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1650. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1651. self.on_excellon_options_button)
  1652. # when there are arguments at application startup this get launched
  1653. self.args_at_startup[list].connect(self.on_startup_args)
  1654. # ##############################################################
  1655. # ############### FILE ASSOCIATIONS SIGNALS ####################
  1656. # ##############################################################
  1657. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1658. lambda: self.restore_extensions(ext_type='excellon'))
  1659. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1660. lambda: self.restore_extensions(ext_type='gcode'))
  1661. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1662. lambda: self.restore_extensions(ext_type='gerber'))
  1663. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1664. lambda: self.delete_all_extensions(ext_type='excellon'))
  1665. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1666. lambda: self.delete_all_extensions(ext_type='gcode'))
  1667. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1668. lambda: self.delete_all_extensions(ext_type='gerber'))
  1669. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1670. lambda: self.add_extension(ext_type='excellon'))
  1671. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1672. lambda: self.add_extension(ext_type='gcode'))
  1673. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1674. lambda: self.add_extension(ext_type='gerber'))
  1675. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1676. lambda: self.del_extension(ext_type='excellon'))
  1677. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1678. lambda: self.del_extension(ext_type='gcode'))
  1679. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1680. lambda: self.del_extension(ext_type='gerber'))
  1681. # connect the 'Apply' buttons from the Preferences/File Associations
  1682. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1683. lambda: self.on_register_files(obj_type='excellon'))
  1684. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1685. lambda: self.on_register_files(obj_type='gcode'))
  1686. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1687. lambda: self.on_register_files(obj_type='gerber'))
  1688. # ##############################################################
  1689. # ###################### KEYWORDS SIGNALS ######################
  1690. # ##############################################################
  1691. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1692. lambda: self.restore_extensions(ext_type='keyword'))
  1693. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1694. lambda: self.delete_all_extensions(ext_type='keyword'))
  1695. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1696. lambda: self.add_extension(ext_type='keyword'))
  1697. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1698. lambda: self.del_extension(ext_type='keyword'))
  1699. # splash screen button signal
  1700. self.ui.general_defaults_form.general_gui_set_group.splash_cb.stateChanged.connect(self.on_splash_changed)
  1701. # connect the abort_all_tasks related slots to the related signals
  1702. self.proc_container.idle_flag.connect(self.app_is_idle)
  1703. # #####################################################################################
  1704. # ########### FINISHED CONNECTING SIGNALS #############################################
  1705. # #####################################################################################
  1706. self.log.debug("Finished connecting Signals.")
  1707. # #####################################################################################
  1708. # ########################## Other setups #############################################
  1709. # #####################################################################################
  1710. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  1711. # depending on from where those tools are called different actions can be done
  1712. self.call_source = 'app'
  1713. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1714. self.tool_tab_locked = False
  1715. # decide if to show or hide the Notebook side of the screen at startup
  1716. if self.defaults["global_project_at_startup"] is True:
  1717. self.ui.splitter.setSizes([1, 1])
  1718. else:
  1719. self.ui.splitter.setSizes([0, 1])
  1720. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1721. self.setup_obj_classes()
  1722. self.setup_recent_items()
  1723. self.setup_component_editor()
  1724. # #####################################################################################
  1725. # ######################### Auto-complete KEYWORDS ####################################
  1726. # #####################################################################################
  1727. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1728. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1729. 'delete', 'drillcncjob', 'export_gcode', 'export_svg', 'ext', 'exteriors', 'follow',
  1730. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1731. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1732. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1733. 'mirror', 'ncc',
  1734. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1735. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'paint',
  1736. 'pan', 'panel', 'panelize', 'plot_all', 'plot_objects', 'quit_flatcam',
  1737. 'save', 'save_project',
  1738. 'save_sys', 'scale',
  1739. 'set_active', 'set_sys', 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1740. 'version', 'write_gcode'
  1741. ]
  1742. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'Marius', 'My Documents', 'Paste_1',
  1743. 'Repetier', 'Roland_MDX_20', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  1744. 'Toolchange_manual', 'Users', 'all', 'angle_x', 'angle_y', 'axis', 'axisoffset',
  1745. 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect', 'contour', 'default',
  1746. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dwell',
  1747. 'dwelltime', 'feedrate_z', 'grbl_11', 'grbl_laser', 'gridoffsety', 'gridx', 'gridy',
  1748. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  1749. 'milled_dias', 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order',
  1750. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  1751. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  1752. 'spacing_columns',
  1753. 'spacing_rows', 'spindlespeed', 'toolchange_xy', 'use_threads', 'value', 'x',
  1754. 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1755. ]
  1756. self.tcl_keywords = [
  1757. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1758. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1759. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1760. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1761. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1762. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1763. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1764. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1765. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1766. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1767. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1768. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1769. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1770. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1771. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1772. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1773. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1774. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1775. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1776. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1777. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1778. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1779. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1780. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1781. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1782. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1783. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1784. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1785. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1786. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1787. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1788. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1789. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1790. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1791. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1792. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1793. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1794. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1795. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1796. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1797. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1798. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1799. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1800. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1801. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1802. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1803. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1804. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1805. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1806. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1807. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1808. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1809. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1810. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1811. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1812. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1813. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1814. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1815. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1816. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1817. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1818. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1819. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1820. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1821. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1822. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1823. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1824. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1825. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1826. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1827. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1828. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1829. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1830. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1831. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1832. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1833. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1834. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1835. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1836. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1837. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1838. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1839. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1840. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1841. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1842. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1843. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1844. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1845. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1846. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1847. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1848. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1849. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1850. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1851. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1852. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1853. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1854. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1855. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1856. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1857. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1858. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1859. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1860. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1861. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1862. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1863. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1864. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1865. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1866. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1867. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1868. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1869. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1870. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1871. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1872. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1873. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1874. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1875. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1876. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1877. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1878. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1879. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1880. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1881. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1882. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1883. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1884. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1885. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1886. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1887. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1888. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1889. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1890. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1891. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1892. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1893. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1894. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1895. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1896. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1897. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1898. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1899. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1900. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1901. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1902. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1903. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1904. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1905. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1906. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1907. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1908. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1909. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1910. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1911. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1912. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1913. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1914. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1915. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1916. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1917. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1918. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1919. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1920. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1921. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1922. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1923. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1924. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1925. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1926. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1927. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1928. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1929. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1930. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1931. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1932. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1933. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1934. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1935. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1936. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1937. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1938. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1939. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1940. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1941. ]
  1942. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1943. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1944. # ####################################################################################
  1945. # ####################### Shell SETUP ################################################
  1946. # ####################################################################################
  1947. self.shell = FCShell(self, version=self.version)
  1948. self.shell._edit.set_model_data(self.myKeywords)
  1949. self.ui.code_editor.set_model_data(self.myKeywords)
  1950. self.shell.setWindowIcon(self.ui.app_icon)
  1951. self.shell.setWindowTitle("FlatCAM Shell")
  1952. self.shell.resize(*self.defaults["global_shell_shape"])
  1953. self.shell.append_output("FlatCAM %s - " % self.version)
  1954. self.shell.append_output(_("Open Source Software - Type help to get started\n\n"))
  1955. self.init_tcl()
  1956. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1957. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1958. self.ui.shell_dock.setWidget(self.shell)
  1959. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1960. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1961. QtWidgets.QDockWidget.DockWidgetFloatable |
  1962. QtWidgets.QDockWidget.DockWidgetClosable)
  1963. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1964. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1965. if self.defaults["global_shell_at_startup"]:
  1966. self.ui.shell_dock.show()
  1967. else:
  1968. self.ui.shell_dock.hide()
  1969. # ##################################################################################
  1970. # ###################### Tools and Plugins #########################################
  1971. # ##################################################################################
  1972. self.dblsidedtool = None
  1973. self.measurement_tool = None
  1974. self.panelize_tool = None
  1975. self.film_tool = None
  1976. self.paste_tool = None
  1977. self.calculator_tool = None
  1978. self.sub_tool = None
  1979. self.move_tool = None
  1980. self.cutout_tool = None
  1981. self.ncclear_tool = None
  1982. self.paint_tool = None
  1983. self.transform_tool = None
  1984. self.properties_tool = None
  1985. self.pdf_tool = None
  1986. self.image_tool = None
  1987. self.pcb_wizard_tool = None
  1988. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1989. self.install_tools()
  1990. # ### System Font Parsing ###
  1991. # self.f_parse = ParseFont(self)
  1992. # self.parse_system_fonts()
  1993. # #####################################################################################
  1994. # ######################## Check for updates ##########################################
  1995. # #####################################################################################
  1996. # Separate thread (Not worker)
  1997. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1998. if (self.beta is False or self.beta is None) and \
  1999. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  2000. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  2001. self.thr2 = QtCore.QThread()
  2002. self.worker_task.emit({'fcn': self.version_check,
  2003. 'params': []})
  2004. self.thr2.start(QtCore.QThread.LowPriority)
  2005. # #####################################################################################
  2006. # ######################### Register files with FlatCAM; #############################
  2007. # ######################### It works only for Windows for now ########################
  2008. # #####################################################################################
  2009. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  2010. self.on_register_files()
  2011. # #####################################################################################
  2012. # ###################### Variables for global usage ###################################
  2013. # #####################################################################################
  2014. # coordinates for relative position display
  2015. self.rel_point1 = (0, 0)
  2016. self.rel_point2 = (0, 0)
  2017. # variable to store coordinates
  2018. self.pos = (0, 0)
  2019. self.pos_jump = (0, 0)
  2020. # variable to store mouse coordinates
  2021. self.mouse = [0, 0]
  2022. # decide if we have a double click or single click
  2023. self.doubleclick = False
  2024. # variable to store if a command is active (then the var is not None) and which one it is
  2025. self.command_active = None
  2026. # variable to store the status of moving selection action
  2027. # None value means that it's not an selection action
  2028. # True value = a selection from left to right
  2029. # False value = a selection from right to left
  2030. self.selection_type = None
  2031. # List to store the objects that are currently loaded in FlatCAM
  2032. # This list is updated on each object creation or object delete
  2033. self.all_objects_list = list()
  2034. # List to store the objects that are selected
  2035. self.sel_objects_list = list()
  2036. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  2037. self.key_modifiers = None
  2038. # Variable to hold the status of the axis
  2039. self.toggle_axis = True
  2040. # Variable to store the status of the fullscreen event
  2041. self.toggle_fscreen = False
  2042. # Variable to store the status of the code editor
  2043. self.toggle_codeeditor = False
  2044. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  2045. self.click_noproject = False
  2046. self.cursor = None
  2047. # Variable to store the GCODE that was edited
  2048. self.gcode_edited = ""
  2049. # reference for the self.ui.code_editor
  2050. self.reference_code_editor = None
  2051. self.script_code = ''
  2052. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  2053. self.preferences_changed_flag = False
  2054. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  2055. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  2056. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'pho',
  2057. 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top', 'tsm']
  2058. self.exc_list = ['drd', 'drl', 'exc', 'ncd', 'tap', 'txt', 'xln']
  2059. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  2060. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ncp', 'out', 'plt', 'ply', 'rol', 'sbp',
  2061. 'tap', 'xpi']
  2062. self.svg_list = ['svg']
  2063. self.dxf_list = ['dxf']
  2064. self.pdf_list = ['pdf']
  2065. self.prj_list = ['flatprj']
  2066. self.conf_list = ['flatconfig']
  2067. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  2068. # flag for polygons not cleared
  2069. self.poly_not_cleared = False
  2070. # VisPy visuals
  2071. self.isHovering = False
  2072. self.notHovering = True
  2073. # when True, the app has to return from any thread
  2074. self.abort_flag = False
  2075. # ###############################################################################
  2076. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  2077. # ############# It's done only once after install ###############
  2078. # ###############################################################################
  2079. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  2080. fac_def_from_file = factory_file.read()
  2081. factory_defaults = json.loads(fac_def_from_file)
  2082. # if the file contain an empty dictionary then save the factory defaults into the file
  2083. if not factory_defaults:
  2084. self.save_factory_defaults(silent=False)
  2085. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  2086. initial_lay = 'compact'
  2087. self.on_layout(lay=initial_lay)
  2088. # Set the combobox in Preferences to the current layout
  2089. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  2090. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  2091. factory_file.close()
  2092. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  2093. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  2094. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  2095. # after the first run, this object should be False
  2096. self.defaults["first_run"] = False
  2097. # ###############################################################################
  2098. # ################# ADDING FlatCAM EDITORS section ##############################
  2099. # ###############################################################################
  2100. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2101. # at the first launch of the App , the editors will not be functional.
  2102. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  2103. self.exc_editor = FlatCAMExcEditor(self)
  2104. self.grb_editor = FlatCAMGrbEditor(self)
  2105. self.log.debug("Finished adding FlatCAM Editor's.")
  2106. self.set_ui_title(name=_("New Project - Not saved"))
  2107. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2108. current_platform = platform.architecture()[0]
  2109. if current_platform != '64bit':
  2110. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2111. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2112. # ###############################################################################
  2113. # ####################### Finished the CONSTRUCTOR ##############################
  2114. # ###############################################################################
  2115. App.log.debug("END of constructor. Releasing control.")
  2116. # #####################################################################################
  2117. # ########################## SHOW GUI #################################################
  2118. # #####################################################################################
  2119. # if the app is not started as headless, show it
  2120. if self.cmd_line_headless != 1:
  2121. # finish the splash
  2122. self.splash.finish(self.ui)
  2123. settings = QSettings("Open Source", "FlatCAM")
  2124. if settings.contains("maximized_gui"):
  2125. maximized_ui = settings.value('maximized_gui', type=bool)
  2126. if maximized_ui is True:
  2127. self.ui.showMaximized()
  2128. else:
  2129. self.ui.show()
  2130. else:
  2131. self.ui.show()
  2132. if self.defaults["global_systray_icon"]:
  2133. self.trayIcon.show()
  2134. else:
  2135. log.warning("******************* RUNNING HEADLESS *******************")
  2136. # #####################################################################################
  2137. # ########################## START-UP ARGUMENTS #######################################
  2138. # #####################################################################################
  2139. # test if the program was started with a script as parameter
  2140. if self.cmd_line_shellvar:
  2141. try:
  2142. cnt = 0
  2143. command_tcl = 0
  2144. for i in self.cmd_line_shellvar.split(','):
  2145. if i is not None:
  2146. try:
  2147. command_tcl = eval(i)
  2148. except:
  2149. command_tcl = i
  2150. command_tcl_formatted = 'set shellvar_{nr} {cmd}'.format(cmd=str(command_tcl), nr=str(cnt))
  2151. cnt += 1
  2152. # if there are Windows paths then replace the path separator with a Unix like one
  2153. if sys.platform == 'win32':
  2154. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  2155. self.shell._sysShell.exec_command(command_tcl_formatted, no_echo=True)
  2156. except Exception as ext:
  2157. print("ERROR: ", ext)
  2158. sys.exit(2)
  2159. if self.cmd_line_shellfile:
  2160. try:
  2161. if self.ui.shell_dock.isHidden():
  2162. self.ui.shell_dock.show()
  2163. with open(self.cmd_line_shellfile, "r") as myfile:
  2164. if show_splash:
  2165. self.splash.showMessage('%s: %ssec\n%s' % (
  2166. _("Canvas initialization started.\n"
  2167. "Canvas initialization finished in"), '%.2f' % self.used_time,
  2168. _("Executing Tcl Script ...")),
  2169. alignment=Qt.AlignBottom | Qt.AlignLeft,
  2170. color=QtGui.QColor("gray"))
  2171. cmd_line_shellfile_text = myfile.read()
  2172. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  2173. except Exception as ext:
  2174. print("ERROR: ", ext)
  2175. sys.exit(2)
  2176. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2177. # the path/file_name must be enclosed in quotes if it contain spaces
  2178. if App.args:
  2179. self.args_at_startup.emit(App.args)
  2180. @staticmethod
  2181. def copy_and_overwrite(from_path, to_path):
  2182. """
  2183. From here:
  2184. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2185. :param from_path: source path
  2186. :param to_path: destination path
  2187. :return: None
  2188. """
  2189. if os.path.exists(to_path):
  2190. shutil.rmtree(to_path)
  2191. try:
  2192. shutil.copytree(from_path, to_path)
  2193. except FileNotFoundError:
  2194. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2195. shutil.copytree(from_new_path, to_path)
  2196. def on_startup_args(self, args, silent=False):
  2197. """
  2198. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2199. :param args: a list containing the application args at startup
  2200. :return: None
  2201. """
  2202. if args is not None:
  2203. args_to_process = args
  2204. else:
  2205. args_to_process = App.args
  2206. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2207. for argument in args_to_process:
  2208. if '.FlatPrj'.lower() in argument.lower():
  2209. try:
  2210. project_name = str(argument)
  2211. if project_name == "":
  2212. if silent is False:
  2213. self.inform.emit(_("Open cancelled."))
  2214. else:
  2215. # self.open_project(project_name)
  2216. run_from_arg = True
  2217. # self.worker_task.emit({'fcn': self.open_project,
  2218. # 'params': [project_name, run_from_arg]})
  2219. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2220. except Exception as e:
  2221. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2222. elif '.FlatConfig'.lower() in argument.lower():
  2223. try:
  2224. file_name = str(argument)
  2225. if file_name == "":
  2226. if silent is False:
  2227. self.inform.emit(_("Open Config file failed."))
  2228. else:
  2229. run_from_arg = True
  2230. # self.worker_task.emit({'fcn': self.open_config_file,
  2231. # 'params': [file_name, run_from_arg]})
  2232. self.open_config_file(file_name, run_from_arg=run_from_arg)
  2233. except Exception as e:
  2234. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2235. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  2236. try:
  2237. file_name = str(argument)
  2238. if file_name == "":
  2239. if silent is False:
  2240. self.inform.emit(_("Open Script file failed."))
  2241. else:
  2242. if silent is False:
  2243. self.on_fileopenscript(name=file_name)
  2244. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  2245. self.on_filerunscript(name=file_name)
  2246. except Exception as e:
  2247. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2248. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  2249. log.debug("App.on_startup_args() --> Quit event.")
  2250. sys.exit()
  2251. elif 'save'.lower() in argument.lower():
  2252. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  2253. self.save_defaults()
  2254. else:
  2255. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2256. proc_arg = argument.lower()
  2257. for ext in exc_list:
  2258. proc_ext = ext.replace(' ', '')
  2259. proc_ext = '.%s' % proc_ext
  2260. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2261. file_name = str(argument)
  2262. if file_name == "":
  2263. if silent is False:
  2264. self.inform.emit(_("Open Excellon file failed."))
  2265. else:
  2266. self.on_fileopenexcellon(name=file_name)
  2267. return
  2268. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2269. for ext in gco_list:
  2270. proc_ext = ext.replace(' ', '')
  2271. proc_ext = '.%s' % proc_ext
  2272. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2273. print(proc_ext, proc_arg)
  2274. file_name = str(argument)
  2275. if file_name == "":
  2276. if silent is False:
  2277. self.inform.emit(_("Open GCode file failed."))
  2278. else:
  2279. self.on_fileopengcode(name=file_name)
  2280. return
  2281. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2282. for ext in grb_list:
  2283. proc_ext = ext.replace(' ', '')
  2284. proc_ext = '.%s' % proc_ext
  2285. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2286. file_name = str(argument)
  2287. if file_name == "":
  2288. if silent is False:
  2289. self.inform.emit(_("Open Gerber file failed."))
  2290. else:
  2291. self.on_fileopengerber(name=file_name)
  2292. return
  2293. # if it reached here without already returning then the app was registered with a file that it does not
  2294. # recognize therefore we must quit
  2295. sys.exit(2)
  2296. def set_ui_title(self, name):
  2297. """
  2298. Sets the title of the main window.
  2299. :param name: String that store the project path and project name
  2300. :return: None
  2301. """
  2302. self.ui.setWindowTitle('FlatCAM %s %s - %s %s' %
  2303. (self.version,
  2304. ('BETA' if self.beta else ''),
  2305. platform.architecture()[0],
  2306. name)
  2307. )
  2308. def defaults_read_form(self):
  2309. """
  2310. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2311. :return: None
  2312. """
  2313. for option in self.defaults_form_fields:
  2314. try:
  2315. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2316. except Exception as e:
  2317. log.debug("App.defaults_read_form() --> %s" % str(e))
  2318. def defaults_write_form(self, factor=None, fl_units=None):
  2319. """
  2320. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2321. self.defaults dictionary.
  2322. :param factor: will apply a factor to the values that written in the GUI elements
  2323. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2324. :return: None
  2325. """
  2326. for option in self.defaults:
  2327. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2328. # try:
  2329. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2330. # except KeyError:
  2331. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2332. # # TODO: Rethink this?
  2333. # pass
  2334. def defaults_write_form_field(self, field, factor=None, units=None):
  2335. """
  2336. Basically it is the worker in the self.defaults_write_form()
  2337. :param field: the GUI element in Preferences GUI to be updated
  2338. :param factor: factor to be applied to the field parameter
  2339. :param units: current FLatCAM measuring units
  2340. :return: None, it updates GUI elements
  2341. """
  2342. try:
  2343. if factor is None:
  2344. if units is None:
  2345. self.defaults_form_fields[field].set_value(self.defaults[field])
  2346. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2347. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=6)
  2348. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2349. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=4)
  2350. else:
  2351. if units is None:
  2352. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2353. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2354. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=6)
  2355. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2356. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=4)
  2357. except KeyError:
  2358. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2359. # TODO: Rethink this?
  2360. pass
  2361. except AttributeError:
  2362. log.debug(field)
  2363. def clear_pool(self):
  2364. """
  2365. Clear the multiprocessing pool and calls garbage collector.
  2366. :return: None
  2367. """
  2368. self.pool.close()
  2369. self.pool = Pool()
  2370. self.pool_recreated.emit(self.pool)
  2371. gc.collect()
  2372. def install_tools(self):
  2373. """
  2374. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2375. Instantiation of the Tools classes.
  2376. The order that the tools are installed is important as they can depend on each other install position.
  2377. :return: None
  2378. """
  2379. self.dblsidedtool = DblSidedTool(self)
  2380. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2381. self.measurement_tool = Measurement(self)
  2382. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  2383. self.panelize_tool = Panelize(self)
  2384. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  2385. self.film_tool = Film(self)
  2386. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2387. self.paste_tool = SolderPaste(self)
  2388. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2389. self.calculator_tool = ToolCalculator(self)
  2390. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'), separator=True)
  2391. self.sub_tool = ToolSub(self)
  2392. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2393. self.move_tool = ToolMove(self)
  2394. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2395. before=self.ui.menueditorigin)
  2396. self.cutout_tool = CutOut(self)
  2397. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2398. before=self.measurement_tool.menuAction)
  2399. self.ncclear_tool = NonCopperClear(self)
  2400. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2401. before=self.measurement_tool.menuAction, separator=True)
  2402. self.paint_tool = ToolPaint(self)
  2403. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2404. before=self.measurement_tool.menuAction, separator=True)
  2405. self.transform_tool = ToolTransform(self)
  2406. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2407. self.properties_tool = Properties(self)
  2408. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2409. self.pdf_tool = ToolPDF(self)
  2410. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2411. separator=True)
  2412. self.image_tool = ToolImage(self)
  2413. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2414. separator=True)
  2415. self.pcb_wizard_tool = PcbWizard(self)
  2416. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2417. self.log.debug("Tools are installed.")
  2418. def remove_tools(self):
  2419. """
  2420. Will remove all the actions in the Tool menu.
  2421. :return: None
  2422. """
  2423. for act in self.ui.menutool.actions():
  2424. self.ui.menutool.removeAction(act)
  2425. def init_tools(self):
  2426. """
  2427. Initialize the Tool tab in the notebook side of the central widget.
  2428. Remove the actions in the Tools menu.
  2429. Instantiate again the FlatCAM tools (plugins).
  2430. All this is required when changing the layout: standard, compact etc.
  2431. :return: None
  2432. """
  2433. log.debug("init_tools()")
  2434. # delete the data currently in the Tools Tab and the Tab itself
  2435. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2436. if widget is not None:
  2437. widget.deleteLater()
  2438. self.ui.notebook.removeTab(2)
  2439. # rebuild the Tools Tab
  2440. self.ui.tool_tab = QtWidgets.QWidget()
  2441. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2442. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2443. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2444. self.ui.tool_scroll_area = VerticalScrollArea()
  2445. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2446. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2447. # first remove all of them
  2448. self.remove_tools()
  2449. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2450. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2451. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2452. # third install all of them
  2453. self.install_tools()
  2454. self.log.debug("Tools are initialized.")
  2455. # def parse_system_fonts(self):
  2456. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2457. # 'params': []})
  2458. def connect_toolbar_signals(self):
  2459. """
  2460. Reconnect the signals to the actions in the toolbar.
  2461. This has to be done each time after the FlatCAM tools are removed/installed.
  2462. :return: None
  2463. """
  2464. # Toolbar
  2465. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2466. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2467. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2468. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2469. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2470. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2471. self.ui.replot_btn.triggered.connect(self.plot_all)
  2472. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2473. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2474. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2475. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2476. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2477. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2478. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2479. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2480. self.ui.delete_btn.triggered.connect(self.on_delete)
  2481. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2482. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2483. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2484. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2485. # Tools Toolbar Signals
  2486. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2487. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2488. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2489. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2490. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2491. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2492. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2493. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2494. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2495. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2496. def object2editor(self):
  2497. """
  2498. Send the current Geometry or Excellon object (if any) into the it's editor.
  2499. :return: None
  2500. """
  2501. self.report_usage("object2editor()")
  2502. edited_object = self.collection.get_active()
  2503. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2504. isinstance(edited_object, FlatCAMExcellon):
  2505. pass
  2506. else:
  2507. self.inform.emit('[WARNING_NOTCL] %s' %
  2508. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2509. return
  2510. if isinstance(edited_object, FlatCAMGeometry):
  2511. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2512. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2513. # we set the notebook to hidden
  2514. self.ui.splitter.setSizes([0, 1])
  2515. if edited_object.multigeo is True:
  2516. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  2517. if len(edited_tools) > 1:
  2518. self.inform.emit('[WARNING_NOTCL] %s' %
  2519. _("Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  2520. "is not possible.\n"
  2521. "Edit only one geometry at a time."))
  2522. # determine the tool dia of the selected tool
  2523. selected_tooldia = float(edited_object.ui.geo_tools_table.item((edited_tools[0] - 1), 1).text())
  2524. # now find the key in the edited_object.tools that has this tooldia
  2525. multi_tool = 1
  2526. for tool in edited_object.tools:
  2527. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2528. multi_tool = tool
  2529. break
  2530. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2531. else:
  2532. self.geo_editor.edit_fcgeometry(edited_object)
  2533. # set call source to the Editor we go into
  2534. self.call_source = 'geo_editor'
  2535. elif isinstance(edited_object, FlatCAMExcellon):
  2536. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2537. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2538. if self.ui.splitter.sizes()[0] == 0:
  2539. self.ui.splitter.setSizes([1, 1])
  2540. self.exc_editor.edit_fcexcellon(edited_object)
  2541. # set call source to the Editor we go into
  2542. self.call_source = 'exc_editor'
  2543. elif isinstance(edited_object, FlatCAMGerber):
  2544. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2545. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2546. if self.ui.splitter.sizes()[0] == 0:
  2547. self.ui.splitter.setSizes([1, 1])
  2548. self.grb_editor.edit_fcgerber(edited_object)
  2549. # set call source to the Editor we go into
  2550. self.call_source = 'grb_editor'
  2551. # make sure that we can't select another object while in Editor Mode:
  2552. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2553. self.ui.project_frame.setDisabled(True)
  2554. # delete any selection shape that might be active as they are not relevant in Editor
  2555. self.delete_selection_shape()
  2556. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2557. self.ui.plot_tab_area.protectTab(0)
  2558. self.inform.emit('[WARNING_NOTCL] %s' %
  2559. _("Editor is activated ..."))
  2560. self.should_we_save = True
  2561. def editor2object(self, cleanup=None):
  2562. """
  2563. Transfers the Geometry or Excellon from it's editor to the current object.
  2564. :return: None
  2565. """
  2566. self.report_usage("editor2object()")
  2567. # do not update a geometry or excellon object unless it comes out of an editor
  2568. if self.call_source != 'app':
  2569. edited_obj = self.collection.get_active()
  2570. if cleanup is None:
  2571. msgbox = QtWidgets.QMessageBox()
  2572. msgbox.setText(_("Do you want to save the edited object?"))
  2573. msgbox.setWindowTitle(_("Close Editor"))
  2574. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2575. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2576. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2577. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2578. msgbox.setDefaultButton(bt_yes)
  2579. msgbox.exec_()
  2580. response = msgbox.clickedButton()
  2581. if response == bt_yes:
  2582. # clean the Tools Tab
  2583. self.ui.tool_scroll_area.takeWidget()
  2584. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2585. self.ui.notebook.setTabText(2, "Tool")
  2586. if isinstance(edited_obj, FlatCAMGeometry):
  2587. obj_type = "Geometry"
  2588. if cleanup is None:
  2589. self.geo_editor.update_fcgeometry(edited_obj)
  2590. self.geo_editor.update_options(edited_obj)
  2591. self.geo_editor.deactivate()
  2592. # update the geo object options so it is including the bounding box values
  2593. try:
  2594. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2595. edited_obj.options['xmin'] = xmin
  2596. edited_obj.options['ymin'] = ymin
  2597. edited_obj.options['xmax'] = xmax
  2598. edited_obj.options['ymax'] = ymax
  2599. except AttributeError as e:
  2600. self.inform.emit('[WARNING] %s' %
  2601. _("Object empty after edit."))
  2602. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2603. elif isinstance(edited_obj, FlatCAMGerber):
  2604. obj_type = "Gerber"
  2605. if cleanup is None:
  2606. self.grb_editor.update_fcgerber()
  2607. self.grb_editor.update_options(edited_obj)
  2608. self.grb_editor.deactivate_grb_editor()
  2609. # delete the old object (the source object) if it was an empty one
  2610. if len(edited_obj.solid_geometry) == 0:
  2611. old_name = edited_obj.options['name']
  2612. self.collection.set_active(old_name)
  2613. self.collection.delete_active()
  2614. elif isinstance(edited_obj, FlatCAMExcellon):
  2615. obj_type = "Excellon"
  2616. if cleanup is None:
  2617. self.exc_editor.update_fcexcellon(edited_obj)
  2618. self.exc_editor.update_options(edited_obj)
  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. self.inform.emit('[selected] %s %s' %
  2625. (obj_type, _("is updated, returning to App...")))
  2626. elif response == bt_no:
  2627. # clean the Tools Tab
  2628. self.ui.tool_scroll_area.takeWidget()
  2629. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2630. self.ui.notebook.setTabText(2, "Tool")
  2631. if isinstance(edited_obj, FlatCAMGeometry):
  2632. self.geo_editor.deactivate()
  2633. elif isinstance(edited_obj, FlatCAMGerber):
  2634. self.grb_editor.deactivate_grb_editor()
  2635. elif isinstance(edited_obj, FlatCAMExcellon):
  2636. self.exc_editor.deactivate()
  2637. # set focus on the project tab
  2638. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  2639. else:
  2640. self.inform.emit('[WARNING_NOTCL] %s' %
  2641. _("Select a Gerber, Geometry or Excellon Object to update."))
  2642. return
  2643. elif response == bt_cancel:
  2644. return
  2645. else:
  2646. if isinstance(edited_obj, FlatCAMGeometry):
  2647. self.geo_editor.deactivate()
  2648. elif isinstance(edited_obj, FlatCAMGerber):
  2649. self.grb_editor.deactivate_grb_editor()
  2650. elif isinstance(edited_obj, FlatCAMExcellon):
  2651. self.exc_editor.deactivate()
  2652. else:
  2653. self.inform.emit('[WARNING_NOTCL] %s' %
  2654. _("Select a Gerber, Geometry or Excellon Object to update."))
  2655. return
  2656. # if notebook is hidden we show it
  2657. if self.ui.splitter.sizes()[0] == 0:
  2658. self.ui.splitter.setSizes([1, 1])
  2659. # restore the call_source to app
  2660. self.call_source = 'app'
  2661. edited_obj.plot()
  2662. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2663. self.ui.plot_tab_area.protectTab(0)
  2664. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2665. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2666. self.ui.project_frame.setDisabled(False)
  2667. def get_last_folder(self):
  2668. """
  2669. Get the folder path from where the last file was opened.
  2670. :return: String, last opened folder path
  2671. """
  2672. return self.defaults["global_last_folder"]
  2673. def get_last_save_folder(self):
  2674. """
  2675. Get the folder path from where the last file was saved.
  2676. :return: String, last saved folder path
  2677. """
  2678. loc = self.defaults["global_last_save_folder"]
  2679. if loc is None:
  2680. loc = self.defaults["global_last_folder"]
  2681. if loc is None:
  2682. loc = os.path.dirname(__file__)
  2683. return loc
  2684. def report_usage(self, resource):
  2685. """
  2686. Increments usage counter for the given resource
  2687. in self.defaults['global_stats'].
  2688. :param resource: Name of the resource.
  2689. :return: None
  2690. """
  2691. if resource in self.defaults['global_stats']:
  2692. self.defaults['global_stats'][resource] += 1
  2693. else:
  2694. self.defaults['global_stats'][resource] = 1
  2695. def init_tcl(self):
  2696. """
  2697. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2698. :return: None
  2699. """
  2700. if hasattr(self, 'tcl'):
  2701. # self.tcl = None
  2702. # TODO we need to clean non default variables and procedures here
  2703. # new object cannot be used here as it will not remember values created for next passes,
  2704. # because tcl was execudted in old instance of TCL
  2705. pass
  2706. else:
  2707. self.tcl = tk.Tcl()
  2708. self.setup_shell()
  2709. self.log.debug("TCL Shell has been initialized.")
  2710. # TODO: This shouldn't be here.
  2711. class TclErrorException(Exception):
  2712. """
  2713. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2714. """
  2715. pass
  2716. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2717. """
  2718. Shows a message on the FlatCAM Shell
  2719. :param msg: Message to display.
  2720. :param show: Opens the shell.
  2721. :param error: Shows the message as an error.
  2722. :param warning: Shows the message as an warning.
  2723. :param success: Shows the message as an success.
  2724. :param selected: Indicate that something was selected on canvas
  2725. :return: None
  2726. """
  2727. if show:
  2728. self.ui.shell_dock.show()
  2729. try:
  2730. if error:
  2731. self.shell.append_error(msg + "\n")
  2732. elif warning:
  2733. self.shell.append_warning(msg + "\n")
  2734. elif success:
  2735. self.shell.append_success(msg + "\n")
  2736. elif selected:
  2737. self.shell.append_selected(msg + "\n")
  2738. else:
  2739. self.shell.append_output(msg + "\n")
  2740. except AttributeError:
  2741. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2742. def raise_tcl_unknown_error(self, unknownException):
  2743. """
  2744. Raise exception if is different type than TclErrorException
  2745. this is here mainly to show unknown errors inside TCL shell console.
  2746. :param unknownException:
  2747. :return:
  2748. """
  2749. if not isinstance(unknownException, self.TclErrorException):
  2750. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2751. else:
  2752. raise unknownException
  2753. def display_tcl_error(self, error, error_info=None):
  2754. """
  2755. Escape bracket [ with '\' otherwise there is error
  2756. "ERROR: missing close-bracket" instead of real error
  2757. :param error: it may be text or exception
  2758. :param error_info: Some informations about the error
  2759. :return: None
  2760. """
  2761. if isinstance(error, Exception):
  2762. exc_type, exc_value, exc_traceback = error_info
  2763. if not isinstance(error, self.TclErrorException):
  2764. show_trace = 1
  2765. else:
  2766. show_trace = int(self.defaults['global_verbose_error_level'])
  2767. if show_trace > 0:
  2768. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2769. trc_formated = []
  2770. for a in reversed(trc):
  2771. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2772. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2773. else:
  2774. text = "%s" % error
  2775. else:
  2776. text = error
  2777. text = text.replace('[', '\\[').replace('"', '\\"')
  2778. self.tcl.eval('return -code error "%s"' % text)
  2779. def raise_tcl_error(self, text):
  2780. """
  2781. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2782. :param text: text of error
  2783. :return: raise exception
  2784. """
  2785. self.display_tcl_error(text)
  2786. raise self.TclErrorException(text)
  2787. def exec_command(self, text, no_echo=False):
  2788. """
  2789. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2790. Also handles execution in separated threads
  2791. :param text: FlatCAM TclCommand with parameters
  2792. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2793. will create crashes of the _Expandable_Edit widget
  2794. :return: output if there was any
  2795. """
  2796. self.report_usage('exec_command')
  2797. result = self.exec_command_test(text, False, no_echo=no_echo)
  2798. # MS: added this method call so the geometry is updated once the TCL command is executed
  2799. # if no_plot is None:
  2800. # self.plot_all()
  2801. return result
  2802. def exec_command_test(self, text, reraise=True, no_echo=False):
  2803. """
  2804. Same as exec_command(...) with additional control over exceptions.
  2805. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2806. :param text: Input command
  2807. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2808. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2809. will create crashes of the _Expandable_Edit widget
  2810. :return: Output from the command
  2811. """
  2812. tcl_command_string = str(text)
  2813. try:
  2814. if no_echo is False:
  2815. self.shell.open_proccessing() # Disables input box.
  2816. result = self.tcl.eval(str(tcl_command_string))
  2817. if result != 'None' and no_echo is False:
  2818. self.shell.append_output(result + '\n')
  2819. except tk.TclError as e:
  2820. # This will display more precise answer if something in TCL shell fails
  2821. result = self.tcl.eval("set errorInfo")
  2822. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2823. if no_echo is False:
  2824. self.shell.append_error('ERROR: ' + result + '\n')
  2825. # Show error in console and just return or in test raise exception
  2826. if reraise:
  2827. raise e
  2828. finally:
  2829. if no_echo is False:
  2830. self.shell.close_proccessing()
  2831. pass
  2832. return result
  2833. # """
  2834. # Code below is unsused. Saved for later.
  2835. # """
  2836. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2837. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2838. # self.log.debug(parts)
  2839. # try:
  2840. # if parts[0] not in commands:
  2841. # self.shell.append_error("Unknown command\n")
  2842. # return
  2843. #
  2844. # #import inspect
  2845. # #inspect.getargspec(someMethod)
  2846. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2847. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2848. # self.shell.append_error(
  2849. # "Command %s takes %d arguments. %d given.\n" %
  2850. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2851. # )
  2852. # return
  2853. #
  2854. # cmdfcn = commands[parts[0]]["fcn"]
  2855. # cmdconv = commands[parts[0]]["converters"]
  2856. # if len(parts) - 1 > 0:
  2857. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2858. # else:
  2859. # retval = cmdfcn()
  2860. # retfcn = commands[parts[0]]["retfcn"]
  2861. # if retval and retfcn(retval):
  2862. # self.shell.append_output(retfcn(retval) + "\n")
  2863. #
  2864. # except Exception as e:
  2865. # #self.shell.append_error(''.join(traceback.format_exc()))
  2866. # #self.shell.append_error("?\n")
  2867. # self.shell.append_error(str(e) + "\n")
  2868. def info(self, msg):
  2869. """
  2870. Informs the user. Normally on the status bar, optionally
  2871. also on the shell.
  2872. :param msg: Text to write.
  2873. :return: None
  2874. """
  2875. # Type of message in brackets at the beginning of the message.
  2876. match = re.search("\[([^\]]+)\](.*)", msg)
  2877. if match:
  2878. level = match.group(1)
  2879. msg_ = match.group(2)
  2880. self.ui.fcinfo.set_status(str(msg_), level=level)
  2881. if level.lower() == "error":
  2882. self.shell_message(msg, error=True, show=True)
  2883. elif level.lower() == "warning":
  2884. self.shell_message(msg, warning=True, show=True)
  2885. elif level.lower() == "error_notcl":
  2886. self.shell_message(msg, error=True, show=False)
  2887. elif level.lower() == "warning_notcl":
  2888. self.shell_message(msg, warning=True, show=False)
  2889. elif level.lower() == "success":
  2890. self.shell_message(msg, success=True, show=False)
  2891. elif level.lower() == "selected":
  2892. self.shell_message(msg, selected=True, show=False)
  2893. else:
  2894. self.shell_message(msg, show=False)
  2895. else:
  2896. self.ui.fcinfo.set_status(str(msg), level="info")
  2897. # make sure that if the message is to clear the infobar with a space
  2898. # is not printed over and over on the shell
  2899. if msg != '':
  2900. self.shell_message(msg)
  2901. def restore_toolbar_view(self):
  2902. """
  2903. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  2904. was saved in the defaults dictionary.
  2905. :return: None
  2906. """
  2907. tb = self.defaults["global_toolbar_view"]
  2908. if tb & 1:
  2909. self.ui.toolbarfile.setVisible(True)
  2910. else:
  2911. self.ui.toolbarfile.setVisible(False)
  2912. if tb & 2:
  2913. self.ui.toolbargeo.setVisible(True)
  2914. else:
  2915. self.ui.toolbargeo.setVisible(False)
  2916. if tb & 4:
  2917. self.ui.toolbarview.setVisible(True)
  2918. else:
  2919. self.ui.toolbarview.setVisible(False)
  2920. if tb & 8:
  2921. self.ui.toolbartools.setVisible(True)
  2922. else:
  2923. self.ui.toolbartools.setVisible(False)
  2924. if tb & 16:
  2925. self.ui.exc_edit_toolbar.setVisible(True)
  2926. else:
  2927. self.ui.exc_edit_toolbar.setVisible(False)
  2928. if tb & 32:
  2929. self.ui.geo_edit_toolbar.setVisible(True)
  2930. else:
  2931. self.ui.geo_edit_toolbar.setVisible(False)
  2932. if tb & 64:
  2933. self.ui.grb_edit_toolbar.setVisible(True)
  2934. else:
  2935. self.ui.grb_edit_toolbar.setVisible(False)
  2936. if tb & 128:
  2937. self.ui.snap_toolbar.setVisible(True)
  2938. else:
  2939. self.ui.snap_toolbar.setVisible(False)
  2940. if tb & 256:
  2941. self.ui.toolbarshell.setVisible(True)
  2942. else:
  2943. self.ui.toolbarshell.setVisible(False)
  2944. def load_defaults(self, filename):
  2945. """
  2946. Loads the aplication's default settings from current_defaults.FlatConfig into
  2947. ``self.defaults``.
  2948. :return: None
  2949. """
  2950. try:
  2951. f = open(self.data_path + "/" + filename + ".FlatConfig")
  2952. options = f.read()
  2953. f.close()
  2954. except IOError:
  2955. self.log.error("Could not load defaults file.")
  2956. self.inform.emit('[ERROR] %s' %
  2957. _("Could not load defaults file."))
  2958. # in case the defaults file can't be loaded, show all toolbars
  2959. self.defaults["global_toolbar_view"] = 511
  2960. return
  2961. try:
  2962. defaults = json.loads(options)
  2963. except:
  2964. # in case the defaults file can't be loaded, show all toolbars
  2965. self.defaults["global_toolbar_view"] = 511
  2966. e = sys.exc_info()[0]
  2967. App.log.error(str(e))
  2968. self.inform.emit('[ERROR] %s' %
  2969. _("Failed to parse defaults file."))
  2970. return
  2971. self.defaults.update(defaults)
  2972. log.debug("FlatCAM defaults loaded from: %s" % filename)
  2973. # restore the toolbar view
  2974. self.restore_toolbar_view()
  2975. def on_import_preferences(self):
  2976. """
  2977. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  2978. ``self.defaults``.
  2979. :return: None
  2980. """
  2981. self.report_usage("on_import_preferences")
  2982. App.log.debug("on_import_preferences()")
  2983. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2984. try:
  2985. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2986. directory=self.data_path,
  2987. filter=filter_)
  2988. except TypeError:
  2989. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2990. filter=filter_)
  2991. filename = str(filename)
  2992. if filename == "":
  2993. self.inform.emit('[WARNING_NOTCL] %s' %
  2994. _("FlatCAM preferences import cancelled."))
  2995. else:
  2996. try:
  2997. f = open(filename)
  2998. options = f.read()
  2999. f.close()
  3000. except IOError:
  3001. self.log.error("Could not load defaults file.")
  3002. self.inform.emit('[ERROR_NOTCL] %s' %
  3003. _("Could not load defaults file."))
  3004. return
  3005. try:
  3006. defaults_from_file = json.loads(options)
  3007. except Exception as e:
  3008. e = sys.exc_info()[0]
  3009. App.log.error(str(e))
  3010. self.inform.emit('[ERROR_NOTCL] %s' %
  3011. _("Failed to parse defaults file."))
  3012. return
  3013. self.defaults.update(defaults_from_file)
  3014. self.on_preferences_edited()
  3015. self.inform.emit('[success] %s: %s' %
  3016. (_("Imported Defaults from"), filename))
  3017. def on_export_preferences(self):
  3018. """
  3019. Save the defaults dictionary to a file.
  3020. :return: None
  3021. """
  3022. self.report_usage("on_export_preferences")
  3023. App.log.debug("on_export_preferences()")
  3024. defaults_file_content = None
  3025. self.date = str(datetime.today()).rpartition('.')[0]
  3026. self.date = ''.join(c for c in self.date if c not in ':-')
  3027. self.date = self.date.replace(' ', '_')
  3028. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  3029. try:
  3030. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  3031. caption=_("Export FlatCAM Preferences"),
  3032. directory=self.data_path + '/preferences_' + self.date,
  3033. filter=filter__
  3034. )
  3035. except TypeError:
  3036. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  3037. filter=filter__)
  3038. filename = str(filename)
  3039. defaults_from_file = {}
  3040. if filename == "":
  3041. self.inform.emit('[WARNING_NOTCL] %s' %
  3042. _("FlatCAM preferences export cancelled."))
  3043. return
  3044. else:
  3045. try:
  3046. f = open(filename, 'w')
  3047. defaults_file_content = f.read()
  3048. f.close()
  3049. except PermissionError:
  3050. self.inform.emit('[WARNING] %s' %
  3051. _("Permission denied, saving not possible.\n"
  3052. "Most likely another app is holding the file open and not accessible."))
  3053. return
  3054. except IOError:
  3055. App.log.debug('Creating a new preferences file ...')
  3056. f = open(filename, 'w')
  3057. json.dump({}, f)
  3058. f.close()
  3059. except:
  3060. e = sys.exc_info()[0]
  3061. App.log.error("Could not load defaults file.")
  3062. App.log.error(str(e))
  3063. self.inform.emit('[ERROR_NOTCL] %s' %
  3064. _("Could not load preferences file."))
  3065. return
  3066. try:
  3067. defaults_from_file = json.loads(defaults_file_content)
  3068. except:
  3069. App.log.warning("Trying to read an empty Preferences file. Continue.")
  3070. # Update options
  3071. self.defaults_read_form()
  3072. defaults_from_file.update(self.defaults)
  3073. self.propagate_defaults(silent=True)
  3074. # Save update options
  3075. try:
  3076. f = open(filename, "w")
  3077. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  3078. f.close()
  3079. except:
  3080. self.inform.emit('[ERROR_NOTCL] %s' %
  3081. _("Failed to write defaults to file."))
  3082. return
  3083. if self.defaults["global_open_style"] is False:
  3084. self.file_opened.emit("preferences", filename)
  3085. self.file_saved.emit("preferences", filename)
  3086. self.inform.emit('[success] %s: %s' %
  3087. (_("Exported preferences to"), filename))
  3088. def on_preferences_open_folder(self):
  3089. """
  3090. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  3091. :return: None
  3092. """
  3093. self.report_usage("on_preferences_open_folder()")
  3094. if sys.platform == 'win32':
  3095. subprocess.Popen('explorer %s' % self.data_path)
  3096. elif sys.platform == 'darwin':
  3097. os.system('open "%s"' % self.data_path)
  3098. else:
  3099. subprocess.Popen(['xdg-open', self.data_path])
  3100. self.inform.emit('[success] %s' %
  3101. _("FlatCAM Preferences Folder opened."))
  3102. def save_geometry(self, x, y, width, height, notebook_width):
  3103. """
  3104. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  3105. launch of the application.
  3106. :param x: X position of the main window
  3107. :param y: Y position of the main window
  3108. :param width: width of the main window
  3109. :param height: height of the main window
  3110. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  3111. :return: None
  3112. """
  3113. self.defaults["global_def_win_x"] = x
  3114. self.defaults["global_def_win_y"] = y
  3115. self.defaults["global_def_win_w"] = width
  3116. self.defaults["global_def_win_h"] = height
  3117. self.defaults["global_def_notebook_width"] = notebook_width
  3118. self.save_defaults()
  3119. def message_dialog(self, title, message, kind="info"):
  3120. """
  3121. Builds and show a custom QMessageBox to be used in FlatCAM.
  3122. :param title: title of the QMessageBox
  3123. :param message: message to be displayed
  3124. :param kind: type of QMessageBox; will display a specific icon.
  3125. :return:
  3126. """
  3127. icon = {"info": QtWidgets.QMessageBox.Information,
  3128. "warning": QtWidgets.QMessageBox.Warning,
  3129. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3130. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  3131. dlg.setText(message)
  3132. dlg.exec_()
  3133. def register_recent(self, kind, filename):
  3134. """
  3135. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  3136. dictionary.
  3137. :param kind: type of file that was opened
  3138. :param filename: the path and file name for the file that was opened
  3139. :return:
  3140. """
  3141. self.log.debug("register_recent()")
  3142. self.log.debug(" %s" % kind)
  3143. self.log.debug(" %s" % filename)
  3144. record = {'kind': str(kind), 'filename': str(filename)}
  3145. if record in self.recent:
  3146. return
  3147. if record in self.recent_projects:
  3148. return
  3149. if record['kind'] == 'project':
  3150. self.recent_projects.insert(0, record)
  3151. else:
  3152. self.recent.insert(0, record)
  3153. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3154. self.recent.pop()
  3155. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3156. self.recent_projects.pop()
  3157. try:
  3158. f = open(self.data_path + '/recent.json', 'w')
  3159. except IOError:
  3160. App.log.error("Failed to open recent items file for writing.")
  3161. self.inform.emit('[ERROR_NOTCL] %s' %
  3162. _('Failed to open recent files file for writing.'))
  3163. return
  3164. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3165. f.close()
  3166. try:
  3167. fp = open(self.data_path + '/recent_projects.json', 'w')
  3168. except IOError:
  3169. App.log.error("Failed to open recent items file for writing.")
  3170. self.inform.emit('[ERROR_NOTCL] %s' %
  3171. _('Failed to open recent projects file for writing.'))
  3172. return
  3173. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3174. fp.close()
  3175. # Re-build the recent items menu
  3176. self.setup_recent_items()
  3177. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3178. """
  3179. Creates a new specialized FlatCAMObj and attaches it to the application,
  3180. this is, updates the GUI accordingly, any other records and plots it.
  3181. This method is thread-safe.
  3182. Notes:
  3183. * If the name is in use, the self.collection will modify it
  3184. when appending it to the collection. There is no need to handle
  3185. name conflicts here.
  3186. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3187. :type kind: str
  3188. :param name: Name for the object.
  3189. :type name: str
  3190. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3191. The function is called with 2 parameters: the new object and the App instance.
  3192. :type initialize: function
  3193. :param active:
  3194. :param fit:
  3195. :param plot: If to plot the resulting object
  3196. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3197. self.colleaction
  3198. :return: None
  3199. :rtype: None
  3200. """
  3201. App.log.debug("new_object()")
  3202. obj_plot = plot
  3203. obj_autoselected = autoselected
  3204. t0 = time.time() # Debug
  3205. # ## Create object
  3206. classdict = {
  3207. "gerber": FlatCAMGerber,
  3208. "excellon": FlatCAMExcellon,
  3209. "cncjob": FlatCAMCNCjob,
  3210. "geometry": FlatCAMGeometry
  3211. }
  3212. App.log.debug("Calling object constructor...")
  3213. obj = classdict[kind](name)
  3214. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3215. # Set options from "Project options" form
  3216. self.options_read_form()
  3217. # IMPORTANT
  3218. # The key names in defaults and options dictionary's are not random:
  3219. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3220. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  3221. # the options from project options form into the self.options. After that, below, depending on the type of
  3222. # object that is created, it will strip the name of the object and the underline (if the original key was
  3223. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3224. # "toolchange"
  3225. for option in self.options:
  3226. if option.find(kind + "_") == 0:
  3227. oname = option[len(kind) + 1:]
  3228. obj.options[oname] = self.options[option]
  3229. obj.isHovering = False
  3230. obj.notHovering = True
  3231. # Initialize as per user request
  3232. # User must take care to implement initialize
  3233. # in a thread-safe way as is is likely that we
  3234. # have been invoked in a separate thread.
  3235. t1 = time.time()
  3236. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3237. try:
  3238. return_value = initialize(obj, self)
  3239. except Exception as e:
  3240. msg = '[ERROR_NOTCL] %s' % \
  3241. _("An internal error has ocurred. See shell.\n")
  3242. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3243. msg += traceback.format_exc()
  3244. self.inform.emit(msg)
  3245. # if str(e) == "Empty Geometry":
  3246. # self.inform.emit("[ERROR_NOTCL] )
  3247. # else:
  3248. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  3249. return "fail"
  3250. t2 = time.time()
  3251. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3252. if return_value == 'fail':
  3253. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3254. return "fail"
  3255. # Check units and convert if necessary
  3256. # This condition CAN be true because initialize() can change obj.units
  3257. if self.options["units"].upper() != obj.units.upper():
  3258. self.inform.emit('%s: %s' %
  3259. (_("Converting units to "), self.options["units"]))
  3260. obj.convert_units(self.options["units"])
  3261. t3 = time.time()
  3262. self.log.debug("%f seconds converting units." % (t3 - t2))
  3263. # Create the bounding box for the object and then add the results to the obj.options
  3264. try:
  3265. xmin, ymin, xmax, ymax = obj.bounds()
  3266. obj.options['xmin'] = xmin
  3267. obj.options['ymin'] = ymin
  3268. obj.options['xmax'] = xmax
  3269. obj.options['ymax'] = ymax
  3270. except Exception as e:
  3271. log.warning("The object has no bounds properties. %s" % str(e))
  3272. return "fail"
  3273. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3274. # Move the object to the main thread and let the app know that it is available.
  3275. obj.moveToThread(self.main_thread)
  3276. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3277. return obj
  3278. def new_excellon_object(self):
  3279. """
  3280. Creates a new, blank Excellon object.
  3281. :return: None
  3282. """
  3283. self.report_usage("new_excellon_object()")
  3284. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3285. def new_geometry_object(self):
  3286. """
  3287. Creates a new, blank and single-tool Geometry object.
  3288. :return: None
  3289. """
  3290. self.report_usage("new_geometry_object()")
  3291. def initialize(obj, self):
  3292. obj.multitool = False
  3293. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3294. def new_gerber_object(self):
  3295. """
  3296. Creates a new, blank Gerber object.
  3297. :return: None
  3298. """
  3299. self.report_usage("new_gerber_object()")
  3300. def initialize(grb_obj, self):
  3301. grb_obj.multitool = False
  3302. grb_obj.source_file = []
  3303. grb_obj.multigeo = False
  3304. grb_obj.follow = False
  3305. grb_obj.apertures = {}
  3306. grb_obj.solid_geometry = []
  3307. try:
  3308. grb_obj.options['xmin'] = 0
  3309. grb_obj.options['ymin'] = 0
  3310. grb_obj.options['xmax'] = 0
  3311. grb_obj.options['ymax'] = 0
  3312. except KeyError:
  3313. pass
  3314. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3315. def on_object_created(self, obj, plot, autoselect):
  3316. """
  3317. Event callback for object creation.
  3318. It will add the new object to the collection. After that it will plot the object in a threaded way
  3319. :param obj: The newly created FlatCAM object.
  3320. :param plot: if the newly create object t obe plotted
  3321. :param autoselect: if the newly created object to be autoselected after creation
  3322. :return: None
  3323. """
  3324. t0 = time.time() # DEBUG
  3325. self.log.debug("on_object_created()")
  3326. # The Collection might change the name if there is a collision
  3327. self.collection.append(obj)
  3328. # after adding the object to the collection always update the list of objects that are in the collection
  3329. self.all_objects_list = self.collection.get_list()
  3330. # self.inform.emit('[selected] %s created & selected: %s' %
  3331. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3332. if obj.kind == 'gerber':
  3333. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3334. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3335. elif obj.kind == 'excellon':
  3336. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3337. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3338. elif obj.kind == 'cncjob':
  3339. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3340. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3341. elif obj.kind == 'geometry':
  3342. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3343. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3344. # update the SHELL auto-completer model with the name of the new object
  3345. self.myKeywords.append(obj.options['name'])
  3346. self.shell._edit.set_model_data(self.myKeywords)
  3347. self.ui.code_editor.set_model_data(self.myKeywords)
  3348. if autoselect:
  3349. # select the just opened object but deselect the previous ones
  3350. self.collection.set_all_inactive()
  3351. self.collection.set_active(obj.options["name"])
  3352. else:
  3353. self.collection.set_all_inactive()
  3354. # here it is done the object plotting
  3355. def worker_task(t_obj):
  3356. with self.proc_container.new(_("Plotting")):
  3357. if isinstance(t_obj, FlatCAMCNCjob):
  3358. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3359. else:
  3360. t_obj.plot()
  3361. t1 = time.time() # DEBUG
  3362. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3363. self.object_plotted.emit(t_obj)
  3364. # Send to worker
  3365. # self.worker.add_task(worker_task, [self])
  3366. if plot is True:
  3367. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3368. def on_object_changed(self, obj):
  3369. """
  3370. Called whenever the geometry of the object was changed in some way.
  3371. This require the update of it's bounding values so it can be the selected on canvas.
  3372. Update the bounding box data from obj.options
  3373. :param obj: the object that was changed
  3374. :return: None
  3375. """
  3376. xmin, ymin, xmax, ymax = obj.bounds()
  3377. obj.options['xmin'] = xmin
  3378. obj.options['ymin'] = ymin
  3379. obj.options['xmax'] = xmax
  3380. obj.options['ymax'] = ymax
  3381. log.debug("Object changed, updating the bounding box data on self.options")
  3382. # delete the old selection shape
  3383. self.delete_selection_shape()
  3384. self.should_we_save = True
  3385. def on_object_plotted(self, obj):
  3386. """
  3387. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3388. :param obj: object to be fit into view
  3389. :return: None
  3390. """
  3391. self.on_zoom_fit(None)
  3392. def options_read_form(self):
  3393. """
  3394. Same as it's equivalent from the defaults.
  3395. self.options use to store the preferences per project. No longer used.
  3396. :return: None
  3397. """
  3398. for option in self.options_form_fields:
  3399. self.options[option] = self.options_form_fields[option].get_value()
  3400. def options_write_form(self):
  3401. """
  3402. Same as it's equivalent from the defaults.
  3403. self.options use to store the preferences per project. No longer used.
  3404. :return: None
  3405. """
  3406. for option in self.options:
  3407. self.options_write_form_field(option)
  3408. def options_write_form_field(self, field):
  3409. """
  3410. Same as it's equivalent from the defaults.
  3411. self.options use to store the preferences per project. No longer used.
  3412. :return: None
  3413. """
  3414. try:
  3415. self.options_form_fields[field].set_value(self.options[field])
  3416. except KeyError:
  3417. # Changed from error to debug. This allows to have data stored
  3418. # which is not user-editable.
  3419. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  3420. pass
  3421. def on_about(self):
  3422. """
  3423. Displays the "about" dialog found in the Menu --> Help.
  3424. :return: None
  3425. """
  3426. self.report_usage("on_about")
  3427. version = self.version
  3428. version_date = self.version_date
  3429. beta = self.beta
  3430. class AboutDialog(QtWidgets.QDialog):
  3431. def __init__(self, parent=None):
  3432. QtWidgets.QDialog.__init__(self, parent)
  3433. # Icon and title
  3434. self.setWindowIcon(parent.app_icon)
  3435. self.setWindowTitle(_("About FlatCAM"))
  3436. self.resize(600, 200)
  3437. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3438. # self.setStyleSheet(
  3439. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3440. # "background-attachment: fixed"
  3441. # )
  3442. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3443. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3444. # palette = QtGui.QPalette()
  3445. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3446. # self.setPalette(palette)
  3447. logo = QtWidgets.QLabel()
  3448. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3449. title = QtWidgets.QLabel(
  3450. "<font size=8><B>FlatCAM</B></font><BR>"
  3451. "{title}<BR>"
  3452. "<BR>"
  3453. "<BR>"
  3454. # "<B>{devel}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3455. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3456. # "<b>{down}</B> area &nbsp;&nbsp;&nbsp;&nbsp;"
  3457. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3458. # "<b> {issue}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3459. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3460. "<B>{issue}</B></a><BR>".format(
  3461. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3462. devel=_("Development"),
  3463. down=_("DOWNLOAD"),
  3464. issue=_("Issue tracker"))
  3465. )
  3466. title.setOpenExternalLinks(True)
  3467. closebtn = QtWidgets.QPushButton(_("Close"))
  3468. tab_widget = QtWidgets.QTabWidget()
  3469. description_label = QtWidgets.QLabel(
  3470. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3471. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3472. version=version,
  3473. beta=('BETA' if beta else ''),
  3474. date=version_date,
  3475. arch=platform.architecture()[0])
  3476. )
  3477. description_label.setOpenExternalLinks(True)
  3478. license_label = QtWidgets.QLabel(
  3479. _(
  3480. '(c) Copyright 2014 Juan Pablo Caram.\n\n'
  3481. 'Licensed under the MIT license:\n'
  3482. 'http://www.opensource.org/licenses/mit-license.php\n\n'
  3483. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3484. 'of this software and associated documentation files (the "Software"), to deal\n'
  3485. 'in the Software without restriction, including without limitation the rights\n'
  3486. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3487. 'copies of the Software, and to permit persons to whom the Software is\n'
  3488. ' furnished to do so, subject to the following conditions:\n\n'
  3489. 'The above copyright notice and this permission notice shall be included in\n'
  3490. 'all copies or substantial portions of the Software.\n\n'
  3491. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3492. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3493. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3494. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3495. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3496. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3497. 'THE SOFTWARE.'
  3498. )
  3499. )
  3500. license_label.setOpenExternalLinks(True)
  3501. # layouts
  3502. layout1 = QtWidgets.QVBoxLayout()
  3503. layout1_1 = QtWidgets.QHBoxLayout()
  3504. layout1_2 = QtWidgets.QHBoxLayout()
  3505. layout2 = QtWidgets.QHBoxLayout()
  3506. layout3 = QtWidgets.QHBoxLayout()
  3507. self.setLayout(layout1)
  3508. layout1.addLayout(layout1_1)
  3509. layout1.addLayout(layout1_2)
  3510. layout1.addLayout(layout2)
  3511. layout1.addLayout(layout3)
  3512. layout1_1.addStretch()
  3513. layout1_1.addWidget(description_label)
  3514. layout1_2.addWidget(tab_widget)
  3515. self.splash_tab = QtWidgets.QWidget()
  3516. self.splash_tab.setObjectName("splash_about")
  3517. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3518. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3519. tab_widget.addTab(self.splash_tab, _("Splash"))
  3520. self.programmmers_tab = QtWidgets.QWidget()
  3521. self.programmmers_tab.setObjectName("programmers_about")
  3522. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3523. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3524. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3525. self.translators_tab = QtWidgets.QWidget()
  3526. self.translators_tab.setObjectName("translators_about")
  3527. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3528. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3529. tab_widget.addTab(self.translators_tab, _("Translators"))
  3530. self.license_tab = QtWidgets.QWidget()
  3531. self.license_tab.setObjectName("license_about")
  3532. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3533. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3534. tab_widget.addTab(self.license_tab, _("License"))
  3535. self.splash_tab_layout.addWidget(logo, stretch=0)
  3536. self.splash_tab_layout.addWidget(title, stretch=1)
  3537. pal = QtGui.QPalette()
  3538. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3539. self.prog_form_lay = QtWidgets.QFormLayout()
  3540. self.prog_form_lay.setHorizontalSpacing(20)
  3541. prog_widget = QtWidgets.QWidget()
  3542. prog_widget.setLayout(self.prog_form_lay)
  3543. prog_scroll = QtWidgets.QScrollArea()
  3544. prog_scroll.setWidget(prog_widget)
  3545. prog_scroll.setWidgetResizable(True)
  3546. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3547. prog_scroll.setPalette(pal)
  3548. self.programmmers_tab_layout.addWidget(prog_scroll)
  3549. self.prog_form_lay.addRow(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")),
  3550. QtWidgets.QLabel('<b>%s</b>' % _("Status")))
  3551. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Juan Pablo Caram"),
  3552. QtWidgets.QLabel('%s' % _("Program Author")))
  3553. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Denis Hayrullin"))
  3554. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Kamil Sopko"))
  3555. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marius Stanciu"),
  3556. QtWidgets.QLabel('%s' % _("Maintainer >=2019")))
  3557. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3558. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Alexandru Lazar"))
  3559. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Matthieu Berthomé"))
  3560. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Evans"))
  3561. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Victor Benso"))
  3562. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3563. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Barnaby Walters"))
  3564. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"))
  3565. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lei Zheng"))
  3566. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marco A Quezada"))
  3567. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3568. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Cedric Dussud"))
  3569. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Chris Hemingway"))
  3570. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Damian Wrobel"))
  3571. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Daniel Sallin"))
  3572. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3573. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Bruno Vunderl"))
  3574. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Gonzalo Lopez"))
  3575. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jakob Staudt"))
  3576. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Smith"))
  3577. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3578. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lubos Medovarsky"))
  3579. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Steve Martina"))
  3580. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Thomas Duffin"))
  3581. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3582. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Idechix"))
  3583. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@SM"))
  3584. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@grbf"))
  3585. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Symonty"))
  3586. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@mgix"))
  3587. self.translator_grid_lay = QtWidgets.QGridLayout()
  3588. # trans_widget = QtWidgets.QWidget()
  3589. # trans_widget.setLayout(self.translator_grid_lay)
  3590. # self.translators_tab_layout.addWidget(trans_widget)
  3591. # self.translators_tab_layout.addStretch()
  3592. trans_widget = QtWidgets.QWidget()
  3593. trans_widget.setLayout(self.translator_grid_lay)
  3594. trans_scroll = QtWidgets.QScrollArea()
  3595. trans_scroll.setWidget(trans_widget)
  3596. trans_scroll.setWidgetResizable(True)
  3597. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3598. trans_scroll.setPalette(pal)
  3599. self.translators_tab_layout.addWidget(trans_scroll)
  3600. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  3601. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  3602. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3603. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Brasilian - Portuguese"), 1, 0)
  3604. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  3605. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 1, 2)
  3606. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 2, 0)
  3607. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 2, 1)
  3608. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 2)
  3609. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 3, 0)
  3610. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 3, 1)
  3611. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  3612. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 4, 0)
  3613. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 4, 1)
  3614. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 4, 2)
  3615. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 5, 0)
  3616. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 5, 1)
  3617. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 2)
  3618. self.translator_grid_lay.setColumnStretch(0, 0)
  3619. self.translators_tab_layout.addStretch()
  3620. self.license_tab_layout.addWidget(license_label)
  3621. self.license_tab_layout.addStretch()
  3622. layout3.addStretch()
  3623. layout3.addWidget(closebtn)
  3624. closebtn.clicked.connect(self.accept)
  3625. AboutDialog(self.ui).exec_()
  3626. def on_file_savedefaults(self):
  3627. """
  3628. Callback for menu item File->Save Defaults. Saves application default options
  3629. ``self.defaults`` to current_defaults.FlatConfig.
  3630. :return: None
  3631. """
  3632. self.save_defaults()
  3633. # def on_app_exit(self):
  3634. # self.report_usage("on_app_exit()")
  3635. #
  3636. # if self.collection.get_list():
  3637. # msgbox = QtWidgets.QMessageBox()
  3638. # # msgbox.setText("<B>Save changes ...</B>")
  3639. # msgbox.setText("There are files/objects opened in FlatCAM. "
  3640. # "\n"
  3641. # "Do you want to Save the project?")
  3642. # msgbox.setWindowTitle("Save changes")
  3643. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3644. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  3645. # QtWidgets.QMessageBox.Cancel)
  3646. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  3647. #
  3648. # response = msgbox.exec_()
  3649. #
  3650. # if response == QtWidgets.QMessageBox.Yes:
  3651. # self.on_file_saveprojectas(thread=False)
  3652. # elif response == QtWidgets.QMessageBox.Cancel:
  3653. # return
  3654. # self.save_defaults()
  3655. # else:
  3656. # self.save_defaults()
  3657. # log.debug("Application defaults saved ... Exit event.")
  3658. # QtWidgets.qApp.quit()
  3659. def save_defaults(self, silent=False, data_path=None):
  3660. """
  3661. Saves application default options
  3662. ``self.defaults`` to current_defaults.FlatConfig file.
  3663. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  3664. used at the next launch of the application.
  3665. :param silent: whether to display a message in status bar or not; boolean
  3666. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  3667. When the application is portable it should be a mobile location.
  3668. :return: None
  3669. """
  3670. self.report_usage("save_defaults")
  3671. if data_path is None:
  3672. data_path = self.data_path
  3673. # Read options from file
  3674. try:
  3675. f = open(data_path + "/current_defaults.FlatConfig")
  3676. defaults_file_content = f.read()
  3677. f.close()
  3678. except:
  3679. e = sys.exc_info()[0]
  3680. App.log.error("Could not load defaults file.")
  3681. App.log.error(str(e))
  3682. self.inform.emit('[ERROR_NOTCL] %s' %
  3683. _("Could not load defaults file."))
  3684. return
  3685. try:
  3686. defaults = json.loads(defaults_file_content)
  3687. except:
  3688. e = sys.exc_info()[0]
  3689. App.log.error("Failed to parse defaults file.")
  3690. App.log.error(str(e))
  3691. self.inform.emit('[ERROR_NOTCL] %s' %
  3692. _("Failed to parse defaults file."))
  3693. return
  3694. # Update options
  3695. self.defaults_read_form()
  3696. defaults.update(self.defaults)
  3697. self.propagate_defaults(silent=True)
  3698. # Save the toolbar view
  3699. tb_status = 0
  3700. if self.ui.toolbarfile.isVisible():
  3701. tb_status += 1
  3702. if self.ui.toolbargeo.isVisible():
  3703. tb_status += 2
  3704. if self.ui.toolbarview.isVisible():
  3705. tb_status += 4
  3706. if self.ui.toolbartools.isVisible():
  3707. tb_status += 8
  3708. if self.ui.exc_edit_toolbar.isVisible():
  3709. tb_status += 16
  3710. if self.ui.geo_edit_toolbar.isVisible():
  3711. tb_status += 32
  3712. if self.ui.grb_edit_toolbar.isVisible():
  3713. tb_status += 64
  3714. if self.ui.snap_toolbar.isVisible():
  3715. tb_status += 128
  3716. if self.ui.toolbarshell.isVisible():
  3717. tb_status += 256
  3718. self.defaults["global_toolbar_view"] = tb_status
  3719. # Save update options
  3720. try:
  3721. f = open(data_path + "/current_defaults.FlatConfig", "w")
  3722. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  3723. f.close()
  3724. except:
  3725. self.inform.emit('[ERROR_NOTCL] %s' %
  3726. _("Failed to write defaults to file."))
  3727. return
  3728. if not silent:
  3729. self.inform.emit('[success] %s' %
  3730. _("Preferences saved."))
  3731. def save_factory_defaults(self, silent=False, data_path=None):
  3732. """
  3733. Saves application factory default options
  3734. ``self.defaults`` to factory_defaults.FlatConfig.
  3735. It's a one time job done just after the first install.
  3736. :param silent: whether to display a message in status bar or not; boolean
  3737. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  3738. When the application is portable it should be a mobile location.
  3739. :return: None
  3740. """
  3741. self.report_usage("save_factory_defaults")
  3742. if data_path is None:
  3743. data_path = self.data_path
  3744. # Read options from file
  3745. try:
  3746. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  3747. factory_defaults_file_content = f_f_def.read()
  3748. f_f_def.close()
  3749. except:
  3750. e = sys.exc_info()[0]
  3751. App.log.error("Could not load factory defaults file.")
  3752. App.log.error(str(e))
  3753. self.inform.emit('[ERROR_NOTCL] %s' %
  3754. _("Could not load factory defaults file."))
  3755. return
  3756. try:
  3757. factory_defaults = json.loads(factory_defaults_file_content)
  3758. except:
  3759. e = sys.exc_info()[0]
  3760. App.log.error("Failed to parse factory defaults file.")
  3761. App.log.error(str(e))
  3762. self.inform.emit('[ERROR_NOTCL] %s' %
  3763. _("Failed to parse factory defaults file."))
  3764. return
  3765. # Update options
  3766. self.defaults_read_form()
  3767. factory_defaults.update(self.defaults)
  3768. self.propagate_defaults(silent=True)
  3769. # Save update options
  3770. try:
  3771. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  3772. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3773. f_f_def_s.close()
  3774. except:
  3775. self.inform.emit('[ERROR_NOTCL] %s' %
  3776. _("Failed to write factory defaults to file."))
  3777. return
  3778. if silent is False:
  3779. self.inform.emit(_("Factory defaults saved."))
  3780. def final_save(self):
  3781. """
  3782. Callback for doing a preferences save to file whenever the application is about to quit.
  3783. If the project has changes, it will ask the user to save the project.
  3784. :return: None
  3785. """
  3786. if self.save_in_progress:
  3787. self.inform.emit('[WARNING_NOTCL] %s' %
  3788. _("Application is saving the project. Please wait ..."))
  3789. return
  3790. if self.should_we_save and self.collection.get_list():
  3791. msgbox = QtWidgets.QMessageBox()
  3792. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  3793. "\n"
  3794. "Do you want to Save the project?"))
  3795. msgbox.setWindowTitle(_("Save changes"))
  3796. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3797. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  3798. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  3799. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3800. msgbox.setDefaultButton(bt_yes)
  3801. msgbox.exec_()
  3802. response = msgbox.clickedButton()
  3803. if response == bt_yes:
  3804. try:
  3805. self.trayIcon.hide()
  3806. except:
  3807. pass
  3808. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  3809. elif response == bt_no:
  3810. try:
  3811. self.trayIcon.hide()
  3812. except:
  3813. pass
  3814. self.quit_application()
  3815. elif response == bt_cancel:
  3816. return
  3817. else:
  3818. try:
  3819. self.trayIcon.hide()
  3820. except:
  3821. pass
  3822. self.quit_application()
  3823. def quit_application(self):
  3824. """
  3825. Called (as a pyslot or not) when the application is quit.
  3826. :return: None
  3827. """
  3828. self.save_defaults()
  3829. log.debug("App.final_save() --> App Defaults saved.")
  3830. if self.cmd_line_headless != 1:
  3831. # save app state to file
  3832. settings = QSettings("Open Source", "FlatCAM")
  3833. settings.setValue('saved_gui_state', self.ui.saveState())
  3834. settings.setValue('maximized_gui', self.ui.isMaximized())
  3835. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  3836. settings.setValue(
  3837. 'notebook_font_size',
  3838. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  3839. )
  3840. settings.setValue('axis_font_size',
  3841. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value())
  3842. settings.setValue(
  3843. 'textbox_font_size',
  3844. self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  3845. )
  3846. settings.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  3847. # This will write the setting to the platform specific storage.
  3848. del settings
  3849. log.debug("App.final_save() --> App UI state saved.")
  3850. QtWidgets.qApp.quit()
  3851. def on_portable_checked(self, state):
  3852. """
  3853. Callback called when the checkbox in Preferences GUI is checked.
  3854. It will set the application as portable by creating the preferences and recent files in the
  3855. 'config' folder found in the FlatCAM installation folder.
  3856. :param state: boolean, the state of the checkbox when clicked/checked
  3857. :return:
  3858. """
  3859. line_no = 0
  3860. data = None
  3861. if sys.platform != 'win32':
  3862. # this won't work in Linux or MacOS
  3863. return
  3864. # test if the app was frozen and choose the path for the configuration file
  3865. if getattr(sys, "frozen", False) is True:
  3866. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  3867. else:
  3868. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  3869. config_file = current_data_path + '\\configuration.txt'
  3870. try:
  3871. with open(config_file, 'r') as f:
  3872. try:
  3873. data = f.readlines()
  3874. except Exception as e:
  3875. log.debug('App.__init__() -->%s' % str(e))
  3876. return
  3877. except FileNotFoundError:
  3878. pass
  3879. for line in data:
  3880. line = line.strip('\n')
  3881. param = str(line).rpartition('=')
  3882. if param[0] == 'portable':
  3883. break
  3884. line_no += 1
  3885. if state:
  3886. data[line_no] = 'portable=True\n'
  3887. # create the new defauults files
  3888. # create current_defaults.FlatConfig file if there is none
  3889. try:
  3890. f = open(current_data_path + '/current_defaults.FlatConfig')
  3891. f.close()
  3892. except IOError:
  3893. App.log.debug('Creating empty current_defaults.FlatConfig')
  3894. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3895. json.dump({}, f)
  3896. f.close()
  3897. # create factory_defaults.FlatConfig file if there is none
  3898. try:
  3899. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3900. f.close()
  3901. except IOError:
  3902. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3903. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3904. json.dump({}, f)
  3905. f.close()
  3906. try:
  3907. f = open(current_data_path + '/recent.json')
  3908. f.close()
  3909. except IOError:
  3910. App.log.debug('Creating empty recent.json')
  3911. f = open(current_data_path + '/recent.json', 'w')
  3912. json.dump([], f)
  3913. f.close()
  3914. try:
  3915. fp = open(current_data_path + '/recent_projects.json')
  3916. fp.close()
  3917. except IOError:
  3918. App.log.debug('Creating empty recent_projects.json')
  3919. fp = open(current_data_path + '/recent_projects.json', 'w')
  3920. json.dump([], fp)
  3921. fp.close()
  3922. # save the current defaults to the new defaults file
  3923. self.save_defaults(silent=True, data_path=current_data_path)
  3924. self.save_factory_defaults(silent=True, data_path=current_data_path)
  3925. else:
  3926. data[line_no] = 'portable=False\n'
  3927. with open(config_file, 'w') as f:
  3928. f.writelines(data)
  3929. def on_toggle_shell(self):
  3930. """
  3931. Toggle shell: if is visible close it, if it is closed then open it
  3932. :return:
  3933. """
  3934. self.report_usage("on_toggle_shell()")
  3935. if self.ui.shell_dock.isVisible():
  3936. self.ui.shell_dock.hide()
  3937. else:
  3938. self.ui.shell_dock.show()
  3939. def on_register_files(self, obj_type=None):
  3940. """
  3941. Called whenever there is a need to register file extensions with FlatCAM.
  3942. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3943. :param obj_type: the type of object to be register for.
  3944. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3945. :return: None
  3946. """
  3947. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3948. new_reg_path = 'Software\\Classes\\'
  3949. # find if the current user is admin
  3950. try:
  3951. is_admin = os.getuid() == 0
  3952. except AttributeError:
  3953. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3954. if is_admin is True:
  3955. root_path = winreg.HKEY_LOCAL_MACHINE
  3956. else:
  3957. root_path = winreg.HKEY_CURRENT_USER
  3958. # create the keys
  3959. def set_reg(name, root_path, new_reg_path, value):
  3960. try:
  3961. winreg.CreateKey(root_path, new_reg_path)
  3962. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3963. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3964. return True
  3965. except WindowsError:
  3966. return False
  3967. # delete key in registry
  3968. def delete_reg(root_path, reg_path, key_to_del):
  3969. key_to_del_path = reg_path + key_to_del
  3970. try:
  3971. winreg.DeleteKey(root_path, key_to_del_path)
  3972. return True
  3973. except WindowsError:
  3974. return False
  3975. if obj_type is None or obj_type == 'excellon':
  3976. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3977. exc_list = [x for x in exc_list if x != '']
  3978. # register all keys in the Preferences window
  3979. for ext in exc_list:
  3980. new_k = new_reg_path + '.%s' % ext
  3981. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3982. # and unregister those that are no longer in the Preferences windows but are in the file
  3983. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3984. if ext not in exc_list:
  3985. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3986. # now write the updated extensions to the self.defaults
  3987. # new_ext = ''
  3988. # for ext in exc_list:
  3989. # new_ext = new_ext + ext + ', '
  3990. # self.defaults["fa_excellon"] = new_ext
  3991. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3992. if obj_type is None or obj_type == 'gcode':
  3993. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3994. gco_list = [x for x in gco_list if x != '']
  3995. # register all keys in the Preferences window
  3996. for ext in gco_list:
  3997. new_k = new_reg_path + '.%s' % ext
  3998. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3999. # and unregister those that are no longer in the Preferences windows but are in the file
  4000. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  4001. if ext not in gco_list:
  4002. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4003. # now write the updated extensions to the self.defaults
  4004. # new_ext = ''
  4005. # for ext in gco_list:
  4006. # new_ext = new_ext + ext + ', '
  4007. # self.defaults["fa_gcode"] = new_ext
  4008. self.inform.emit('[success] %s' %
  4009. _("Selected GCode file extensions registered with FlatCAM."))
  4010. if obj_type is None or obj_type == 'gerber':
  4011. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4012. grb_list = [x for x in grb_list if x != '']
  4013. # register all keys in the Preferences window
  4014. for ext in grb_list:
  4015. new_k = new_reg_path + '.%s' % ext
  4016. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4017. # and unregister those that are no longer in the Preferences windows but are in the file
  4018. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  4019. if ext not in grb_list:
  4020. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4021. # now write the updated extensions to the self.defaults
  4022. # new_ext = ''
  4023. # for ext in grb_list:
  4024. # new_ext = new_ext + ext + ', '
  4025. # self.defaults["fa_gerber"] = new_ext
  4026. self.inform.emit('[success] %s' %
  4027. _("Selected Gerber file extensions registered with FlatCAM."))
  4028. def add_extension(self, ext_type):
  4029. if ext_type == 'excellon':
  4030. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4031. if new_ext == '':
  4032. return
  4033. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4034. if new_ext in old_val:
  4035. return
  4036. old_val.append(new_ext)
  4037. old_val.sort()
  4038. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4039. if ext_type == 'gcode':
  4040. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4041. if new_ext == '':
  4042. return
  4043. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4044. if new_ext in old_val:
  4045. return
  4046. old_val.append(new_ext)
  4047. old_val.sort()
  4048. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4049. if ext_type == 'gerber':
  4050. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4051. if new_ext == '':
  4052. return
  4053. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4054. if new_ext in old_val:
  4055. return
  4056. old_val.append(new_ext)
  4057. old_val.sort()
  4058. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4059. if ext_type == 'keyword':
  4060. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4061. if new_kw == '':
  4062. return
  4063. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4064. if new_kw in old_val:
  4065. return
  4066. old_val.append(new_kw)
  4067. old_val.sort()
  4068. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4069. # update the self.myKeywords so the model is updated
  4070. self.autocomplete_kw_list = \
  4071. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4072. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4073. self.shell._edit.set_model_data(self.myKeywords)
  4074. self.ui.code_editor.set_model_data(self.myKeywords)
  4075. def del_extension(self, ext_type):
  4076. if ext_type == 'excellon':
  4077. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4078. if new_ext == '':
  4079. return
  4080. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4081. if new_ext not in old_val:
  4082. return
  4083. old_val.remove(new_ext)
  4084. old_val.sort()
  4085. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4086. if ext_type == 'gcode':
  4087. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4088. if new_ext == '':
  4089. return
  4090. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4091. if new_ext not in old_val:
  4092. return
  4093. old_val.remove(new_ext)
  4094. old_val.sort()
  4095. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4096. if ext_type == 'gerber':
  4097. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4098. if new_ext == '':
  4099. return
  4100. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4101. if new_ext not in old_val:
  4102. return
  4103. old_val.remove(new_ext)
  4104. old_val.sort()
  4105. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4106. if ext_type == 'keyword':
  4107. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4108. if new_kw == '':
  4109. return
  4110. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4111. if new_kw not in old_val:
  4112. return
  4113. old_val.remove(new_kw)
  4114. old_val.sort()
  4115. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4116. # update the self.myKeywords so the model is updated
  4117. self.autocomplete_kw_list = \
  4118. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4119. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4120. self.shell._edit.set_model_data(self.myKeywords)
  4121. self.ui.code_editor.set_model_data(self.myKeywords)
  4122. def restore_extensions(self, ext_type):
  4123. if ext_type == 'excellon':
  4124. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  4125. # for the ability to open Excellon files with .txt extension
  4126. new_exc_list = deepcopy(self.exc_list)
  4127. try:
  4128. new_exc_list.remove('txt')
  4129. except ValueError:
  4130. pass
  4131. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  4132. if ext_type == 'gcode':
  4133. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  4134. if ext_type == 'gerber':
  4135. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  4136. if ext_type == 'keyword':
  4137. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  4138. # update the self.myKeywords so the model is updated
  4139. self.autocomplete_kw_list = self.default_keywords
  4140. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4141. self.shell._edit.set_model_data(self.myKeywords)
  4142. self.ui.code_editor.set_model_data(self.myKeywords)
  4143. def delete_all_extensions(self, ext_type):
  4144. if ext_type == 'excellon':
  4145. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4146. if ext_type == 'gcode':
  4147. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4148. if ext_type == 'gerber':
  4149. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4150. if ext_type == 'keyword':
  4151. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4152. # update the self.myKeywords so the model is updated
  4153. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4154. self.shell._edit.set_model_data(self.myKeywords)
  4155. self.ui.code_editor.set_model_data(self.myKeywords)
  4156. def on_edit_join(self, name=None):
  4157. """
  4158. Callback for Edit->Join. Joins the selected geometry objects into
  4159. a new one.
  4160. :return: None
  4161. """
  4162. self.report_usage("on_edit_join()")
  4163. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4164. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4165. tooldias = []
  4166. geo_type_list = set()
  4167. objs = self.collection.get_selected()
  4168. if len(objs) < 2:
  4169. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4170. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4171. return 'fail'
  4172. for obj in objs:
  4173. geo_type_list.add(obj.multigeo)
  4174. # if len(geo_type_list) == 1 means that all list elements are the same
  4175. if len(geo_type_list) != 1:
  4176. self.inform.emit('[ERROR] %s' %
  4177. _("Failed join. The Geometry objects are of different types.\n"
  4178. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4179. "convert from one to another and retry joining \n"
  4180. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4181. "the result may not be what was expected. \n"
  4182. "Check the generated GCODE."))
  4183. return
  4184. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4185. if True in geo_type_list:
  4186. def initialize(obj, app):
  4187. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=True)
  4188. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4189. for v in obj.tools.values():
  4190. v['data']['name'] = obj_name_multi
  4191. self.new_object("geometry", obj_name_multi, initialize)
  4192. else:
  4193. def initialize(obj, app):
  4194. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=False)
  4195. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4196. for v in obj.tools.values():
  4197. v['data']['name'] = obj_name_single
  4198. self.new_object("geometry", obj_name_single, initialize)
  4199. self.should_we_save = True
  4200. def on_edit_join_exc(self):
  4201. """
  4202. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4203. a new Excellon.
  4204. :return: None
  4205. """
  4206. self.report_usage("on_edit_join_exc()")
  4207. objs = self.collection.get_selected()
  4208. for obj in objs:
  4209. if not isinstance(obj, FlatCAMExcellon):
  4210. self.inform.emit('[ERROR_NOTCL] %s' %
  4211. _("Failed. Excellon joining works only on Excellon objects."))
  4212. return
  4213. if len(objs) < 2:
  4214. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4215. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4216. return 'fail'
  4217. def initialize(obj, app):
  4218. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=obj)
  4219. self.new_object("excellon", 'Combo_Excellon', initialize)
  4220. self.should_we_save = True
  4221. def on_edit_join_grb(self):
  4222. """
  4223. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4224. a new Gerber object.
  4225. :return: None
  4226. """
  4227. self.report_usage("on_edit_join_grb()")
  4228. objs = self.collection.get_selected()
  4229. for obj in objs:
  4230. if not isinstance(obj, FlatCAMGerber):
  4231. self.inform.emit('[ERROR_NOTCL] %s' %
  4232. _("Failed. Gerber joining works only on Gerber objects."))
  4233. return
  4234. if len(objs) < 2:
  4235. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4236. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4237. return 'fail'
  4238. def initialize(obj, app):
  4239. FlatCAMGerber.merge(self, grb_list=objs, grb_final=obj)
  4240. self.new_object("gerber", 'Combo_Gerber', initialize)
  4241. self.should_we_save = True
  4242. def on_convert_singlegeo_to_multigeo(self):
  4243. """
  4244. Called for converting a Geometry object from single-geo to multi-geo.
  4245. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4246. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4247. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4248. the solid-geometry of that tool.
  4249. :return: None
  4250. """
  4251. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4252. obj = self.collection.get_active()
  4253. if obj is None:
  4254. self.inform.emit('[ERROR_NOTCL] %s' %
  4255. _("Failed. Select a Geometry Object and try again."))
  4256. return
  4257. if not isinstance(obj, FlatCAMGeometry):
  4258. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4259. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4260. return
  4261. obj.multigeo = True
  4262. for tooluid, dict_value in obj.tools.items():
  4263. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4264. if not isinstance(obj.solid_geometry, list):
  4265. obj.solid_geometry = [obj.solid_geometry]
  4266. obj.solid_geometry[:] = []
  4267. obj.plot()
  4268. self.should_we_save = True
  4269. self.inform.emit('[success] %s' %
  4270. _("A Geometry object was converted to MultiGeo type."))
  4271. def on_convert_multigeo_to_singlegeo(self):
  4272. """
  4273. Called for converting a Geometry object from multi-geo to single-geo.
  4274. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4275. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4276. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4277. the solid-geometry of that tool.
  4278. :return: None
  4279. """
  4280. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4281. obj = self.collection.get_active()
  4282. if obj is None:
  4283. self.inform.emit('[ERROR_NOTCL] %s' %
  4284. _("Failed. Select a Geometry Object and try again."))
  4285. return
  4286. if not isinstance(obj, FlatCAMGeometry):
  4287. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4288. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4289. return
  4290. obj.multigeo = False
  4291. total_solid_geometry = []
  4292. for tooluid, dict_value in obj.tools.items():
  4293. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4294. # clear the original geometry
  4295. dict_value['solid_geometry'][:] = []
  4296. obj.solid_geometry = deepcopy(total_solid_geometry)
  4297. obj.plot()
  4298. self.should_we_save = True
  4299. self.inform.emit('[success] %s' %
  4300. _("A Geometry object was converted to SingleGeo type."))
  4301. def on_options_dict_change(self, field):
  4302. """
  4303. Called whenever a key changed in the self.options dictionary. This dict was used to store the preferences of the
  4304. current project. This feature is no longer used.
  4305. :param field:
  4306. :return:
  4307. """
  4308. self.options_write_form_field(field)
  4309. if field == "units":
  4310. self.set_screen_units(self.options['units'])
  4311. def on_defaults_dict_change(self, field):
  4312. """
  4313. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4314. Edit -> Preferences tab window.
  4315. :param field: the key of the self.defaults dictionary that was changed.
  4316. :return: None
  4317. """
  4318. self.defaults_write_form_field(field)
  4319. if field == "units":
  4320. self.set_screen_units(self.defaults['units'])
  4321. def set_screen_units(self, units):
  4322. """
  4323. Set the FlatCAM units on the status bar.
  4324. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4325. :return: None
  4326. """
  4327. self.ui.units_label.setText("[" + units.lower() + "]")
  4328. def on_toggle_units(self, no_pref=False):
  4329. """
  4330. Callback for the Units radio-button change in the Preferences tab.
  4331. Changes the application's default units adn for the project too.
  4332. If changing the project's units, the change propagates to all of
  4333. the objects in the project.
  4334. :return: None
  4335. """
  4336. self.report_usage("on_toggle_units")
  4337. if self.toggle_units_ignore:
  4338. return
  4339. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4340. # If option is the same, then ignore
  4341. if new_units == self.defaults["units"].upper():
  4342. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4343. return
  4344. # Options to scale
  4345. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  4346. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  4347. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4348. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  4349. "excellon_z_pdepth",
  4350. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4351. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4352. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  4353. "geometry_feedrate_probe",
  4354. 'cncjob_tooldia',
  4355. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4356. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia"
  4357. "tools_2sided_drilldia", "tools_film_boundary",
  4358. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4359. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4360. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4361. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4362. "tools_transform_offset_y",
  4363. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4364. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4365. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4366. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4367. 'global_gridx', 'global_gridy', 'global_snap_max']
  4368. def scale_options(sfactor):
  4369. for dim in dimensions:
  4370. if dim == 'excellon_toolchangexy':
  4371. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4372. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4373. coords_xy[0] *= sfactor
  4374. coords_xy[1] *= sfactor
  4375. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4376. elif dim == 'geometry_toolchangexy':
  4377. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4378. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4379. coords_xy[0] *= sfactor
  4380. coords_xy[1] *= sfactor
  4381. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4382. elif dim == 'geometry_cnctooldia':
  4383. tools_diameters = []
  4384. try:
  4385. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4386. tools_diameters = [eval(a) for a in tools_string if a != '']
  4387. except Exception as e:
  4388. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4389. self.options['geometry_cnctooldia'] = ''
  4390. for t in range(len(tools_diameters)):
  4391. tools_diameters[t] *= sfactor
  4392. self.options['geometry_cnctooldia'] += "%f," % tools_diameters[t]
  4393. elif dim == 'tools_ncctools':
  4394. ncctools = []
  4395. try:
  4396. tools_string = self.defaults["tools_ncctools"].split(",")
  4397. ncctools = [eval(a) for a in tools_string if a != '']
  4398. except Exception as e:
  4399. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4400. self.options['tools_ncctools'] = ''
  4401. for t in range(len(ncctools)):
  4402. ncctools[t] *= sfactor
  4403. self.options['tools_ncctools'] += "%f," % ncctools[t]
  4404. elif dim == 'tools_solderpaste_tools':
  4405. sptools = []
  4406. try:
  4407. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4408. sptools = [eval(a) for a in tools_string if a != '']
  4409. except Exception as e:
  4410. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4411. self.options['tools_solderpaste_tools'] = ""
  4412. for t in range(len(sptools)):
  4413. sptools[t] *= sfactor
  4414. self.options['tools_solderpaste_tools'] += "%f," % sptools[t]
  4415. elif dim == 'tools_solderpaste_xy_toolchange':
  4416. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4417. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4418. sp_coords[0] *= sfactor
  4419. sp_coords[1] *= sfactor
  4420. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  4421. elif dim == 'global_gridx' or dim == 'global_gridy':
  4422. if new_units == 'IN':
  4423. val = 0.1
  4424. try:
  4425. val = float(self.defaults[dim]) * sfactor
  4426. except Exception as e:
  4427. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4428. self.options[dim] = float('%.6f' % val)
  4429. else:
  4430. val = 0.1
  4431. try:
  4432. val = float(self.defaults[dim]) * sfactor
  4433. except Exception as e:
  4434. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4435. self.options[dim] = float('%.4f' % val)
  4436. else:
  4437. val = 0.1
  4438. try:
  4439. val = float(self.options[dim]) * sfactor
  4440. except Exception as e:
  4441. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  4442. self.options[dim] = val
  4443. def scale_defaults(sfactor):
  4444. for dim in dimensions:
  4445. if dim == 'excellon_toolchangexy':
  4446. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4447. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4448. coords_xy[0] *= sfactor
  4449. coords_xy[1] *= sfactor
  4450. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4451. elif dim == 'geometry_toolchangexy':
  4452. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4453. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4454. coords_xy[0] *= sfactor
  4455. coords_xy[1] *= sfactor
  4456. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4457. elif dim == 'geometry_cnctooldia':
  4458. tools_diameters = []
  4459. try:
  4460. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4461. tools_diameters = [eval(a) for a in tools_string if a != '']
  4462. except Exception as e:
  4463. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4464. self.defaults['geometry_cnctooldia'] = ''
  4465. for t in range(len(tools_diameters)):
  4466. tools_diameters[t] *= sfactor
  4467. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  4468. elif dim == 'tools_ncctools':
  4469. ncctools = []
  4470. try:
  4471. tools_string = self.defaults["tools_ncctools"].split(",")
  4472. ncctools = [eval(a) for a in tools_string if a != '']
  4473. except Exception as e:
  4474. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4475. self.defaults['tools_ncctools'] = ''
  4476. for t in range(len(ncctools)):
  4477. ncctools[t] *= sfactor
  4478. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  4479. elif dim == 'tools_solderpaste_tools':
  4480. sptools = []
  4481. try:
  4482. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4483. sptools = [eval(a) for a in tools_string if a != '']
  4484. except Exception as e:
  4485. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4486. self.defaults['tools_solderpaste_tools'] = ""
  4487. for t in range(len(sptools)):
  4488. sptools[t] *= sfactor
  4489. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  4490. elif dim == 'tools_solderpaste_xy_toolchange':
  4491. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4492. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4493. sp_coords[0] *= sfactor
  4494. sp_coords[1] *= sfactor
  4495. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  4496. elif dim == 'global_gridx' or dim == 'global_gridy':
  4497. if new_units == 'IN':
  4498. val = 0.1
  4499. try:
  4500. val = float(self.defaults[dim]) * sfactor
  4501. except Exception as e:
  4502. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4503. self.defaults[dim] = float('%.6f' % val)
  4504. else:
  4505. val = 0.1
  4506. try:
  4507. val = float(self.defaults[dim]) * sfactor
  4508. except Exception as e:
  4509. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4510. self.defaults[dim] = float('%.4f' % val)
  4511. else:
  4512. val = 0.1
  4513. try:
  4514. val = float(self.defaults[dim]) * sfactor
  4515. except Exception as e:
  4516. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4517. self.defaults[dim] = val
  4518. # The scaling factor depending on choice of units.
  4519. factor = 1/25.4
  4520. if new_units == 'MM':
  4521. factor = 25.4
  4522. # Changing project units. Warn user.
  4523. msgbox = QtWidgets.QMessageBox()
  4524. msgbox.setWindowTitle(_("Toggle Units"))
  4525. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  4526. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4527. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  4528. "properties of all objects to be scaled accordingly.\nContinue?"))
  4529. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4530. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4531. msgbox.setDefaultButton(bt_ok)
  4532. msgbox.exec_()
  4533. response = msgbox.clickedButton()
  4534. if response == bt_ok:
  4535. if no_pref is False:
  4536. self.options_read_form()
  4537. scale_options(factor)
  4538. self.options_write_form()
  4539. self.defaults_read_form()
  4540. scale_defaults(factor)
  4541. self.defaults_write_form(fl_units=new_units)
  4542. # save the defaults to file, some may assume that the conversion is enough and it's not
  4543. self.on_save_button()
  4544. self.should_we_save = True
  4545. # change this only if the workspace is active
  4546. if self.defaults['global_workspace'] is True:
  4547. self.plotcanvas.draw_workspace()
  4548. # adjust the grid values on the main toolbar
  4549. dec = 6 if new_units == 'IN'else 4
  4550. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  4551. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  4552. if not self.ui.grid_gap_link_cb.isChecked():
  4553. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  4554. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  4555. for obj in self.collection.get_list():
  4556. obj.convert_units(new_units)
  4557. # make that the properties stored in the object are also updated
  4558. self.object_changed.emit(obj)
  4559. obj.build_ui()
  4560. current = self.collection.get_active()
  4561. if current is not None:
  4562. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4563. if not isinstance(current, FlatCAMGeometry):
  4564. current.to_form()
  4565. self.plot_all()
  4566. self.inform.emit('[success] %s: %s' %
  4567. (_("Converted units to"), new_units))
  4568. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4569. self.set_screen_units(new_units)
  4570. else:
  4571. # Undo toggling
  4572. self.toggle_units_ignore = True
  4573. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4574. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4575. else:
  4576. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4577. self.toggle_units_ignore = False
  4578. self.inform.emit('[WARNING_NOTCL]%s' %
  4579. _(" Units conversion cancelled."))
  4580. self.options_read_form()
  4581. self.defaults_read_form()
  4582. def on_toggle_units_click(self):
  4583. try:
  4584. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4585. except (TypeError, AttributeError):
  4586. pass
  4587. if self.defaults["units"] == 'MM':
  4588. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4589. else:
  4590. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4591. self.on_toggle_units(no_pref=True)
  4592. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4593. lambda: self.on_toggle_units(no_pref=False))
  4594. def on_fullscreen(self):
  4595. self.report_usage("on_fullscreen()")
  4596. if self.toggle_fscreen is False:
  4597. if sys.platform == 'win32':
  4598. self.ui.showFullScreen()
  4599. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4600. tb.setVisible(False)
  4601. self.ui.splitter_left.setVisible(False)
  4602. self.toggle_fscreen = True
  4603. else:
  4604. if sys.platform == 'win32':
  4605. self.ui.showNormal()
  4606. self.restore_toolbar_view()
  4607. self.ui.splitter_left.setVisible(True)
  4608. self.toggle_fscreen = False
  4609. def on_toggle_plotarea(self):
  4610. self.report_usage("on_toggle_plotarea()")
  4611. try:
  4612. name = self.ui.plot_tab_area.widget(0).objectName()
  4613. except AttributeError:
  4614. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4615. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4616. self.ui.plot_tab_area.protectTab(0)
  4617. return
  4618. if name != 'plotarea':
  4619. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4620. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4621. self.ui.plot_tab_area.protectTab(0)
  4622. else:
  4623. self.ui.plot_tab_area.closeTab(0)
  4624. def on_toggle_notebook(self):
  4625. if self.ui.splitter.sizes()[0] == 0:
  4626. self.ui.splitter.setSizes([1, 1])
  4627. else:
  4628. self.ui.splitter.setSizes([0, 1])
  4629. def on_toggle_axis(self):
  4630. self.report_usage("on_toggle_axis()")
  4631. if self.toggle_axis is False:
  4632. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4633. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4634. self.plotcanvas.redraw()
  4635. self.toggle_axis = True
  4636. else:
  4637. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4638. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4639. self.plotcanvas.redraw()
  4640. self.toggle_axis = False
  4641. def on_toggle_grid(self):
  4642. self.report_usage("on_toggle_grid()")
  4643. self.ui.grid_snap_btn.trigger()
  4644. def on_options_combo_change(self, sel):
  4645. """
  4646. Called when the combo box to choose between application defaults and
  4647. project option changes value. The corresponding variables are
  4648. copied to the UI.
  4649. :param sel: The option index that was chosen.
  4650. :return: None
  4651. """
  4652. # combo_sel = self.ui.notebook.combo_options.get_active()
  4653. App.log.debug("Options --> %s" % sel)
  4654. # form = [self.defaults_form, self.options_form][sel]
  4655. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  4656. if sel == 0:
  4657. self.gen_form = self.ui.general_defaults_form
  4658. self.ger_form = self.ui.gerber_defaults_form
  4659. self.exc_form = self.ui.excellon_defaults_form
  4660. self.geo_form = self.ui.geometry_defaults_form
  4661. self.cnc_form = self.ui.cncjob_defaults_form
  4662. self.tools_form = self.ui.tools_defaults_form
  4663. self.fa_form = self.ui.util_defaults_form
  4664. elif sel == 1:
  4665. self.gen_form = self.ui.general_options_form
  4666. self.ger_form = self.ui.gerber_options_form
  4667. self.exc_form = self.ui.excellon_options_form
  4668. self.geo_form = self.ui.geometry_options_form
  4669. self.cnc_form = self.ui.cncjob_options_form
  4670. self.tools_form = self.ui.tools_options_form
  4671. self.fa_form = self.ui.util_options_form
  4672. else:
  4673. return
  4674. try:
  4675. self.ui.general_scroll_area.takeWidget()
  4676. except:
  4677. self.log.debug("Nothing to remove")
  4678. self.ui.general_scroll_area.setWidget(self.gen_form)
  4679. self.gen_form.show()
  4680. try:
  4681. self.ui.gerber_scroll_area.takeWidget()
  4682. except:
  4683. self.log.debug("Nothing to remove")
  4684. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  4685. self.ger_form.show()
  4686. try:
  4687. self.ui.excellon_scroll_area.takeWidget()
  4688. except:
  4689. self.log.debug("Nothing to remove")
  4690. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  4691. self.exc_form.show()
  4692. try:
  4693. self.ui.geometry_scroll_area.takeWidget()
  4694. except:
  4695. self.log.debug("Nothing to remove")
  4696. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  4697. self.geo_form.show()
  4698. try:
  4699. self.ui.cncjob_scroll_area.takeWidget()
  4700. except:
  4701. self.log.debug("Nothing to remove")
  4702. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  4703. self.cnc_form.show()
  4704. try:
  4705. self.ui.tools_scroll_area.takeWidget()
  4706. except:
  4707. self.log.debug("Nothing to remove")
  4708. self.ui.tools_scroll_area.setWidget(self.tools_form)
  4709. self.tools_form.show()
  4710. try:
  4711. self.ui.fa_scroll_area.takeWidget()
  4712. except:
  4713. self.log.debug("Nothing to remove")
  4714. self.ui.fa_scroll_area.setWidget(self.fa_form)
  4715. self.fa_form.show()
  4716. self.log.debug("Finished GUI form initialization.")
  4717. # self.options2form()
  4718. def on_excellon_defaults_button(self):
  4719. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  4720. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  4721. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  4722. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  4723. self.defaults_form_fields["excellon_zeros"].set_value('L')
  4724. self.defaults_form_fields["excellon_units"].set_value('INCH')
  4725. log.debug("Excellon app defaults loaded ...")
  4726. def on_excellon_options_button(self):
  4727. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  4728. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  4729. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  4730. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  4731. self.options_form_fields["excellon_zeros"].set_value('L')
  4732. self.options_form_fields["excellon_units"].set_value('INCH')
  4733. log.debug("Excellon options defaults loaded ...")
  4734. def on_update_exc_export(self, state):
  4735. """
  4736. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  4737. if the update_excellon_cb checkbox is checked
  4738. :param state: state of the checkbox whose signals is tied to his slot
  4739. :return:
  4740. """
  4741. if state:
  4742. # first try to disconnect
  4743. try:
  4744. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.\
  4745. disconnect(self.on_excellon_format_changed)
  4746. except TypeError:
  4747. pass
  4748. try:
  4749. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged.\
  4750. disconnect(self.on_excellon_format_changed)
  4751. except TypeError:
  4752. pass
  4753. try:
  4754. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged.\
  4755. disconnect(self.on_excellon_format_changed)
  4756. except TypeError:
  4757. pass
  4758. try:
  4759. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged.\
  4760. disconnect(self.on_excellon_format_changed)
  4761. except TypeError:
  4762. pass
  4763. try:
  4764. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  4765. disconnect(self.on_excellon_zeros_changed)
  4766. except TypeError:
  4767. pass
  4768. try:
  4769. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  4770. disconnect(self.on_excellon_zeros_changed)
  4771. except TypeError:
  4772. pass
  4773. # the connect them
  4774. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.connect(
  4775. self.on_excellon_format_changed)
  4776. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged.connect(
  4777. self.on_excellon_format_changed)
  4778. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged.connect(
  4779. self.on_excellon_format_changed)
  4780. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged.connect(
  4781. self.on_excellon_format_changed)
  4782. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  4783. self.on_excellon_zeros_changed)
  4784. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  4785. self.on_excellon_units_changed)
  4786. else:
  4787. # disconnect the signals
  4788. try:
  4789. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged. \
  4790. disconnect(self.on_excellon_format_changed)
  4791. except TypeError:
  4792. pass
  4793. try:
  4794. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged. \
  4795. disconnect(self.on_excellon_format_changed)
  4796. except TypeError:
  4797. pass
  4798. try:
  4799. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged. \
  4800. disconnect(self.on_excellon_format_changed)
  4801. except TypeError:
  4802. pass
  4803. try:
  4804. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged. \
  4805. disconnect(self.on_excellon_format_changed)
  4806. except TypeError:
  4807. pass
  4808. try:
  4809. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  4810. disconnect(self.on_excellon_zeros_changed)
  4811. except TypeError:
  4812. pass
  4813. try:
  4814. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  4815. disconnect(self.on_excellon_zeros_changed)
  4816. except TypeError:
  4817. pass
  4818. def on_excellon_format_changed(self):
  4819. """
  4820. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  4821. :return: None
  4822. """
  4823. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  4824. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4825. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  4826. )
  4827. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4828. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  4829. )
  4830. else:
  4831. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4832. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  4833. )
  4834. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4835. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  4836. )
  4837. def on_excellon_zeros_changed(self):
  4838. """
  4839. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  4840. :return: None
  4841. """
  4842. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  4843. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  4844. )
  4845. def on_excellon_units_changed(self):
  4846. """
  4847. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  4848. :return: None
  4849. """
  4850. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  4851. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  4852. )
  4853. self.on_excellon_format_changed()
  4854. # Setting plot colors handlers
  4855. def on_pf_color_entry(self):
  4856. self.defaults['global_plot_fill'] = \
  4857. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  4858. self.defaults['global_plot_fill'][7:9]
  4859. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4860. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  4861. def on_pf_color_button(self):
  4862. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  4863. c_dialog = QtWidgets.QColorDialog()
  4864. plot_fill_color = c_dialog.getColor(initial=current_color)
  4865. if plot_fill_color.isValid() is False:
  4866. return
  4867. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4868. "background-color:%s" % str(plot_fill_color.name()))
  4869. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  4870. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  4871. self.defaults['global_plot_fill'] = new_val
  4872. def on_pf_color_spinner(self):
  4873. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  4874. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  4875. self.defaults['global_plot_fill'] = \
  4876. self.defaults['global_plot_fill'][:7] + \
  4877. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4878. self.defaults['global_plot_line'] = \
  4879. self.defaults['global_plot_line'][:7] + \
  4880. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4881. def on_pf_color_slider(self):
  4882. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  4883. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  4884. def on_pl_color_entry(self):
  4885. self.defaults['global_plot_line'] = \
  4886. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  4887. self.defaults['global_plot_line'][7:9]
  4888. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4889. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  4890. def on_pl_color_button(self):
  4891. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  4892. # print(current_color)
  4893. c_dialog = QtWidgets.QColorDialog()
  4894. plot_line_color = c_dialog.getColor(initial=current_color)
  4895. if plot_line_color.isValid() is False:
  4896. return
  4897. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4898. "background-color:%s" % str(plot_line_color.name()))
  4899. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  4900. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  4901. self.defaults['global_plot_line'] = new_val_line
  4902. # Setting selection colors (left - right) handlers
  4903. def on_sf_color_entry(self):
  4904. self.defaults['global_sel_fill'] = \
  4905. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  4906. self.defaults['global_sel_fill'][7:9]
  4907. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4908. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  4909. def on_sf_color_button(self):
  4910. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  4911. c_dialog = QtWidgets.QColorDialog()
  4912. plot_fill_color = c_dialog.getColor(initial=current_color)
  4913. if plot_fill_color.isValid() is False:
  4914. return
  4915. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4916. "background-color:%s" % str(plot_fill_color.name()))
  4917. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  4918. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  4919. self.defaults['global_sel_fill'] = new_val
  4920. def on_sf_color_spinner(self):
  4921. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  4922. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  4923. self.defaults['global_sel_fill'] = \
  4924. self.defaults['global_sel_fill'][:7] + \
  4925. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4926. self.defaults['global_sel_line'] = \
  4927. self.defaults['global_sel_line'][:7] + \
  4928. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4929. def on_sf_color_slider(self):
  4930. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  4931. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  4932. def on_sl_color_entry(self):
  4933. self.defaults['global_sel_line'] = \
  4934. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  4935. self.defaults['global_sel_line'][7:9]
  4936. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4937. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  4938. def on_sl_color_button(self):
  4939. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  4940. c_dialog = QtWidgets.QColorDialog()
  4941. plot_line_color = c_dialog.getColor(initial=current_color)
  4942. if plot_line_color.isValid() is False:
  4943. return
  4944. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4945. "background-color:%s" % str(plot_line_color.name()))
  4946. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  4947. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  4948. self.defaults['global_sel_line'] = new_val_line
  4949. # Setting selection colors (right - left) handlers
  4950. def on_alt_sf_color_entry(self):
  4951. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  4952. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  4953. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4954. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  4955. def on_alt_sf_color_button(self):
  4956. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  4957. c_dialog = QtWidgets.QColorDialog()
  4958. plot_fill_color = c_dialog.getColor(initial=current_color)
  4959. if plot_fill_color.isValid() is False:
  4960. return
  4961. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4962. "background-color:%s" % str(plot_fill_color.name()))
  4963. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  4964. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  4965. self.defaults['global_alt_sel_fill'] = new_val
  4966. def on_alt_sf_color_spinner(self):
  4967. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  4968. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  4969. self.defaults['global_alt_sel_fill'] = \
  4970. self.defaults['global_alt_sel_fill'][:7] + \
  4971. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4972. self.defaults['global_alt_sel_line'] = \
  4973. self.defaults['global_alt_sel_line'][:7] + \
  4974. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4975. def on_alt_sf_color_slider(self):
  4976. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  4977. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  4978. def on_alt_sl_color_entry(self):
  4979. self.defaults['global_alt_sel_line'] = \
  4980. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  4981. self.defaults['global_alt_sel_line'][7:9]
  4982. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  4983. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  4984. def on_alt_sl_color_button(self):
  4985. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  4986. c_dialog = QtWidgets.QColorDialog()
  4987. plot_line_color = c_dialog.getColor(initial=current_color)
  4988. if plot_line_color.isValid() is False:
  4989. return
  4990. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  4991. "background-color:%s" % str(plot_line_color.name()))
  4992. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  4993. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  4994. self.defaults['global_alt_sel_line'] = new_val_line
  4995. # Setting Editor colors
  4996. def on_draw_color_entry(self):
  4997. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  4998. .draw_color_entry.get_value()
  4999. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5000. "background-color:%s" % str(self.defaults['global_draw_color']))
  5001. def on_draw_color_button(self):
  5002. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  5003. c_dialog = QtWidgets.QColorDialog()
  5004. draw_color = c_dialog.getColor(initial=current_color)
  5005. if draw_color.isValid() is False:
  5006. return
  5007. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5008. "background-color:%s" % str(draw_color.name()))
  5009. new_val = str(draw_color.name())
  5010. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  5011. self.defaults['global_draw_color'] = new_val
  5012. def on_sel_draw_color_entry(self):
  5013. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5014. .sel_draw_color_entry.get_value()
  5015. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5016. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  5017. def on_sel_draw_color_button(self):
  5018. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  5019. c_dialog = QtWidgets.QColorDialog()
  5020. sel_draw_color = c_dialog.getColor(initial=current_color)
  5021. if sel_draw_color.isValid() is False:
  5022. return
  5023. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5024. "background-color:%s" % str(sel_draw_color.name()))
  5025. new_val_sel = str(sel_draw_color.name())
  5026. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  5027. self.defaults['global_sel_draw_color'] = new_val_sel
  5028. def on_proj_color_entry(self):
  5029. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  5030. .proj_color_entry.get_value()
  5031. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5032. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  5033. def on_proj_color_button(self):
  5034. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  5035. c_dialog = QtWidgets.QColorDialog()
  5036. proj_color = c_dialog.getColor(initial=current_color)
  5037. if proj_color.isValid() is False:
  5038. return
  5039. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5040. "background-color:%s" % str(proj_color.name()))
  5041. new_val_sel = str(proj_color.name())
  5042. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  5043. self.defaults['global_proj_item_color'] = new_val_sel
  5044. def on_proj_color_dis_entry(self):
  5045. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  5046. .proj_color_dis_entry.get_value()
  5047. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5048. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  5049. def on_proj_color_dis_button(self):
  5050. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  5051. c_dialog = QtWidgets.QColorDialog()
  5052. proj_color = c_dialog.getColor(initial=current_color)
  5053. if proj_color.isValid() is False:
  5054. return
  5055. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5056. "background-color:%s" % str(proj_color.name()))
  5057. new_val_sel = str(proj_color.name())
  5058. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  5059. self.defaults['global_proj_item_dis_color'] = new_val_sel
  5060. def on_annotation_fontcolor_entry(self):
  5061. self.defaults['cncjob_annotation_fontcolor'] = \
  5062. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.get_value()
  5063. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5064. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  5065. def on_annotation_fontcolor_button(self):
  5066. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  5067. c_dialog = QtWidgets.QColorDialog()
  5068. annotation_color = c_dialog.getColor(initial=current_color)
  5069. if annotation_color.isValid() is False:
  5070. return
  5071. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5072. "background-color:%s" % str(annotation_color.name()))
  5073. new_val_sel = str(annotation_color.name())
  5074. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(new_val_sel)
  5075. self.defaults['cncjob_annotation_fontcolor'] = new_val_sel
  5076. def on_film_color_entry(self):
  5077. self.defaults['tools_film_color'] = \
  5078. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  5079. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5080. "background-color:%s" % str(self.defaults['tools_film_color']))
  5081. def on_film_color_button(self):
  5082. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  5083. c_dialog = QtWidgets.QColorDialog()
  5084. film_color = c_dialog.getColor(initial=current_color)
  5085. if film_color.isValid() is False:
  5086. return
  5087. # if new color is different then mark that the Preferences are changed
  5088. if film_color != current_color:
  5089. self.on_preferences_edited()
  5090. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5091. "background-color:%s" % str(film_color.name()))
  5092. new_val_sel = str(film_color.name())
  5093. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  5094. self.defaults['tools_film_color'] = new_val_sel
  5095. def on_splash_changed(self, state):
  5096. settings = QSettings("Open Source", "FlatCAM")
  5097. settings.setValue('splash_screen', 1) if state else settings.setValue('splash_screen', 0)
  5098. # This will write the setting to the platform specific storage.
  5099. del settings
  5100. def on_notebook_tab_rmb_click(self, checked):
  5101. self.ui.notebook.set_detachable(val=checked)
  5102. self.defaults["global_tabs_detachable"] = checked
  5103. self.ui.plot_tab_area.set_detachable(val=checked)
  5104. self.defaults["global_tabs_detachable"] = checked
  5105. def on_deselect_all(self):
  5106. self.collection.set_all_inactive()
  5107. self.delete_selection_shape()
  5108. def on_workspace_modified(self):
  5109. self.save_defaults(silent=True)
  5110. self.plotcanvas.draw_workspace()
  5111. def on_workspace(self):
  5112. self.report_usage("on_workspace()")
  5113. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5114. self.plotcanvas.restore_workspace()
  5115. else:
  5116. self.plotcanvas.delete_workspace()
  5117. self.save_defaults(silent=True)
  5118. def on_workspace_menu(self):
  5119. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5120. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  5121. else:
  5122. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  5123. self.on_workspace()
  5124. def on_layout(self, index=None, lay=None):
  5125. self.report_usage("on_layout()")
  5126. if lay:
  5127. current_layout = lay
  5128. else:
  5129. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  5130. settings = QSettings("Open Source", "FlatCAM")
  5131. settings.setValue('layout', current_layout)
  5132. # This will write the setting to the platform specific storage.
  5133. del settings
  5134. # first remove the toolbars:
  5135. try:
  5136. self.ui.removeToolBar(self.ui.toolbarfile)
  5137. self.ui.removeToolBar(self.ui.toolbargeo)
  5138. self.ui.removeToolBar(self.ui.toolbarview)
  5139. self.ui.removeToolBar(self.ui.toolbarshell)
  5140. self.ui.removeToolBar(self.ui.toolbartools)
  5141. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  5142. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  5143. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  5144. self.ui.removeToolBar(self.ui.snap_toolbar)
  5145. self.ui.removeToolBar(self.ui.toolbarshell)
  5146. except Exception as e:
  5147. pass
  5148. if current_layout == 'standard':
  5149. # ## TOOLBAR INSTALLATION # ##
  5150. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5151. self.ui.toolbarfile.setObjectName('File_TB')
  5152. self.ui.addToolBar(self.ui.toolbarfile)
  5153. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5154. self.ui.toolbargeo.setObjectName('Edit_TB')
  5155. self.ui.addToolBar(self.ui.toolbargeo)
  5156. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5157. self.ui.toolbarview.setObjectName('View_TB')
  5158. self.ui.addToolBar(self.ui.toolbarview)
  5159. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5160. self.ui.toolbarshell.setObjectName('Shell_TB')
  5161. self.ui.addToolBar(self.ui.toolbarshell)
  5162. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5163. self.ui.toolbartools.setObjectName('Tools_TB')
  5164. self.ui.addToolBar(self.ui.toolbartools)
  5165. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5166. # self.ui.exc_edit_toolbar.setVisible(False)
  5167. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5168. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  5169. self.ui.addToolBarBreak()
  5170. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5171. # self.ui.geo_edit_toolbar.setVisible(False)
  5172. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5173. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  5174. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5175. # self.ui.grb_edit_toolbar.setVisible(False)
  5176. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5177. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  5178. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5179. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5180. # self.ui.snap_toolbar.setMaximumHeight(30)
  5181. self.ui.addToolBar(self.ui.snap_toolbar)
  5182. self.ui.corner_snap_btn.setVisible(False)
  5183. self.ui.snap_magnet.setVisible(False)
  5184. elif current_layout == 'compact':
  5185. # ## TOOLBAR INSTALLATION # ##
  5186. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5187. self.ui.toolbarfile.setObjectName('File_TB')
  5188. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  5189. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5190. self.ui.toolbargeo.setObjectName('Edit_TB')
  5191. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  5192. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5193. self.ui.toolbarshell.setObjectName('Shell_TB')
  5194. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  5195. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5196. self.ui.toolbartools.setObjectName('Tools_TB')
  5197. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  5198. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5199. # self.ui.geo_edit_toolbar.setVisible(False)
  5200. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5201. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  5202. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5203. self.ui.toolbarview.setObjectName('View_TB')
  5204. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  5205. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  5206. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5207. # self.ui.grb_edit_toolbar.setVisible(False)
  5208. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5209. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  5210. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5211. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5212. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  5213. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5214. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5215. self.ui.snap_toolbar.setMaximumHeight(30)
  5216. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  5217. self.ui.corner_snap_btn.setVisible(True)
  5218. self.ui.snap_magnet.setVisible(True)
  5219. # add all the actions to the toolbars
  5220. self.ui.populate_toolbars()
  5221. # reconnect all the signals to the toolbar actions
  5222. self.connect_toolbar_signals()
  5223. self.ui.grid_snap_btn.setChecked(True)
  5224. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  5225. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  5226. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  5227. self.ui.grid_gap_link_cb.setChecked(True)
  5228. def on_cnc_custom_parameters(self, signal_text):
  5229. if signal_text == 'Parameters':
  5230. return
  5231. else:
  5232. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  5233. def on_save_button(self):
  5234. log.debug("App.on_save_button() --> Saving preferences to file.")
  5235. self.preferences_changed_flag = False
  5236. self.save_defaults(silent=False)
  5237. # load the defaults so they are updated into the app
  5238. self.load_defaults(filename='current_defaults')
  5239. # Re-fresh project options
  5240. self.on_options_app2project()
  5241. settings = QSettings("Open Source", "FlatCAM")
  5242. # save the notebook font size
  5243. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  5244. settings.setValue('notebook_font_size', fsize)
  5245. # save the axis font size
  5246. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  5247. settings.setValue('axis_font_size', g_fsize)
  5248. # save the textbox font size
  5249. tb_fsize = self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  5250. settings.setValue('textbox_font_size', tb_fsize)
  5251. # This will write the setting to the platform specific storage.
  5252. del settings
  5253. def handlePrint(self):
  5254. self.report_usage("handlePrint()")
  5255. dialog = QtPrintSupport.QPrintDialog()
  5256. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  5257. self.ui.code_editor.document().print_(dialog.printer())
  5258. def handlePreview(self):
  5259. self.report_usage("handlePreview()")
  5260. dialog = QtPrintSupport.QPrintPreviewDialog()
  5261. dialog.paintRequested.connect(self.ui.code_editor.print_)
  5262. dialog.exec_()
  5263. def handleTextChanged(self):
  5264. # enable = not self.ui.code_editor.document().isEmpty()
  5265. # self.ui.buttonPrint.setEnabled(enable)
  5266. # self.ui.buttonPreview.setEnabled(enable)
  5267. pass
  5268. def handleOpen(self, filt=None):
  5269. self.report_usage("handleOpen()")
  5270. if filt:
  5271. _filter_ = filt
  5272. else:
  5273. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  5274. "All Files (*.*)"
  5275. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  5276. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  5277. if path:
  5278. file = QtCore.QFile(path)
  5279. if file.open(QtCore.QIODevice.ReadOnly):
  5280. stream = QtCore.QTextStream(file)
  5281. self.gcode_edited = stream.readAll()
  5282. self.ui.code_editor.setPlainText(self.gcode_edited)
  5283. file.close()
  5284. def handleSaveGCode(self, name=None, filt=None):
  5285. self.report_usage("handleSaveGCode()")
  5286. if filt:
  5287. _filter_ = filt
  5288. else:
  5289. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  5290. "All Files (*.*)"
  5291. if name:
  5292. obj_name = name
  5293. else:
  5294. try:
  5295. obj_name = self.collection.get_active().options['name']
  5296. except AttributeError:
  5297. obj_name = 'file'
  5298. if filt is None:
  5299. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  5300. try:
  5301. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  5302. caption=_("Export G-Code ..."),
  5303. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  5304. filter=_filter_
  5305. )[0])
  5306. except TypeError:
  5307. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  5308. if filename == "":
  5309. self.inform.emit('[WARNING_NOTCL] %s' %
  5310. _("Export Code cancelled."))
  5311. return
  5312. else:
  5313. try:
  5314. my_gcode = self.ui.code_editor.toPlainText()
  5315. with open(filename, 'w') as f:
  5316. for line in my_gcode:
  5317. f.write(line)
  5318. except FileNotFoundError:
  5319. self.inform.emit('[WARNING] %s' %
  5320. _("No such file or directory"))
  5321. return
  5322. except PermissionError:
  5323. self.inform.emit('[WARNING] %s' %
  5324. _("Permission denied, saving not possible.\n"
  5325. "Most likely another app is holding the file open and not accessible."))
  5326. return
  5327. # Just for adding it to the recent files list.
  5328. if self.defaults["global_open_style"] is False:
  5329. self.file_opened.emit("cncjob", filename)
  5330. self.file_saved.emit("cncjob", filename)
  5331. self.inform.emit('%s: %s' % (_("Saved to"), str(filename)))
  5332. def handleFindGCode(self):
  5333. self.report_usage("handleFindGCode()")
  5334. flags = QtGui.QTextDocument.FindCaseSensitively
  5335. text_to_be_found = self.ui.entryFind.get_value()
  5336. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  5337. if r is False:
  5338. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5339. def handleReplaceGCode(self):
  5340. self.report_usage("handleReplaceGCode()")
  5341. old = self.ui.entryFind.get_value()
  5342. new = self.ui.entryReplace.get_value()
  5343. if self.ui.sel_all_cb.isChecked():
  5344. while True:
  5345. cursor = self.ui.code_editor.textCursor()
  5346. cursor.beginEditBlock()
  5347. flags = QtGui.QTextDocument.FindCaseSensitively
  5348. # self.ui.editor is the QPlainTextEdit
  5349. r = self.ui.code_editor.find(str(old), flags)
  5350. if r:
  5351. qc = self.ui.code_editor.textCursor()
  5352. if qc.hasSelection():
  5353. qc.insertText(new)
  5354. else:
  5355. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5356. break
  5357. # Mark end of undo block
  5358. cursor.endEditBlock()
  5359. else:
  5360. cursor = self.ui.code_editor.textCursor()
  5361. cursor.beginEditBlock()
  5362. qc = self.ui.code_editor.textCursor()
  5363. if qc.hasSelection():
  5364. qc.insertText(new)
  5365. # Mark end of undo block
  5366. cursor.endEditBlock()
  5367. def handleRunCode(self):
  5368. # trying to run a Tcl command without having the Shell open will create some warnings because the Tcl Shell
  5369. # tries to print on a hidden widget, therefore show the dock if hidden
  5370. if self.ui.shell_dock.isHidden():
  5371. self.ui.shell_dock.show()
  5372. self.script_code = deepcopy(self.ui.code_editor.toPlainText())
  5373. # self.shell._sysShell.exec_command(script_code)
  5374. old_line = ''
  5375. for tcl_command_line in self.script_code.splitlines():
  5376. # do not process lines starting with '#' = comment and empty lines
  5377. if not tcl_command_line.startswith('#') and tcl_command_line != '':
  5378. # id FlatCAM is run in Windows then replace all the slashes with
  5379. # the UNIX style slash that TCL understands
  5380. if sys.platform == 'win32':
  5381. if "open" in tcl_command_line:
  5382. tcl_command_line = tcl_command_line.replace('\\', '/')
  5383. if old_line != '':
  5384. new_command = old_line + tcl_command_line + '\n'
  5385. else:
  5386. new_command = tcl_command_line
  5387. # execute the actual Tcl command
  5388. try:
  5389. self.shell.open_proccessing() # Disables input box.
  5390. result = self.tcl.eval(str(new_command))
  5391. if result != 'None':
  5392. self.shell.append_output(result + '\n')
  5393. old_line = ''
  5394. except tk.TclError:
  5395. old_line = old_line + tcl_command_line + '\n'
  5396. except Exception as e:
  5397. log.debug("App.handleRunCode() --> %s" % str(e))
  5398. if old_line != '':
  5399. # it means that the script finished with an error
  5400. result = self.tcl.eval("set errorInfo")
  5401. self.log.error("Exec command Exception: %s" % (result + '\n'))
  5402. self.shell.append_error('ERROR: ' + result + '\n')
  5403. self.shell.close_proccessing()
  5404. def on_tool_add_keypress(self):
  5405. # ## Current application units in Upper Case
  5406. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5407. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5408. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5409. if notebook_widget_name == 'selected_tab':
  5410. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5411. # Tool add works for Geometry only if Advanced is True in Preferences
  5412. if self.defaults["global_app_level"] == 'a':
  5413. tool_add_popup = FCInputDialog(title="New Tool ...",
  5414. text='Enter a Tool Diameter:',
  5415. min=0.0000, max=99.9999, decimals=4)
  5416. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5417. val, ok = tool_add_popup.get_value()
  5418. if ok:
  5419. if float(val) == 0:
  5420. self.inform.emit('[WARNING_NOTCL] %s' %
  5421. _("Please enter a tool diameter with non-zero value, in Float format."))
  5422. return
  5423. self.collection.get_active().on_tool_add(dia=float(val))
  5424. else:
  5425. self.inform.emit('[WARNING_NOTCL] %s...' %
  5426. _("Adding Tool cancelled"))
  5427. else:
  5428. msgbox = QtWidgets.QMessageBox()
  5429. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5430. "Go to Preferences -> General - Show Advanced Options."))
  5431. msgbox.setWindowTitle("Tool adding ...")
  5432. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  5433. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5434. msgbox.setDefaultButton(bt_ok)
  5435. msgbox.exec_()
  5436. # work only if the notebook tab on focus is the Tools_Tab
  5437. if notebook_widget_name == 'tool_tab':
  5438. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5439. tool_add_popup = FCInputDialog(title="New Tool ...",
  5440. text='Enter a Tool Diameter:',
  5441. min=0.0000, max=99.9999, decimals=4)
  5442. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5443. val, ok = tool_add_popup.get_value()
  5444. # and only if the tool is NCC Tool
  5445. if tool_widget == self.ncclear_tool.toolName:
  5446. if ok:
  5447. if float(val) == 0:
  5448. self.inform.emit('[WARNING_NOTCL] %s' %
  5449. _("Please enter a tool diameter with non-zero value, in Float format."))
  5450. return
  5451. self.ncclear_tool.on_tool_add(dia=float(val))
  5452. else:
  5453. self.inform.emit('[WARNING_NOTCL] %s...' %
  5454. _("Adding Tool cancelled"))
  5455. # and only if the tool is Paint Area Tool
  5456. elif tool_widget == self.paint_tool.toolName:
  5457. if ok:
  5458. if float(val) == 0:
  5459. self.inform.emit('[WARNING_NOTCL] %s' %
  5460. _("Please enter a tool diameter with non-zero value, in Float format."))
  5461. return
  5462. self.paint_tool.on_tool_add(dia=float(val))
  5463. else:
  5464. self.inform.emit('[WARNING_NOTCL] %s...' %
  5465. _("Adding Tool cancelled"))
  5466. # and only if the tool is Solder Paste Dispensing Tool
  5467. elif tool_widget == self.paste_tool.toolName:
  5468. if ok:
  5469. if float(val) == 0:
  5470. self.inform.emit('[WARNING_NOTCL] %s' %
  5471. _("Please enter a tool diameter with non-zero value, in Float format."))
  5472. return
  5473. self.paste_tool.on_tool_add(dia=float(val))
  5474. else:
  5475. self.inform.emit('[WARNING_NOTCL] %s...' %
  5476. _("Adding Tool cancelled"))
  5477. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5478. # See description bellow.
  5479. def on_delete_keypress(self):
  5480. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5481. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5482. if notebook_widget_name == 'selected_tab':
  5483. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5484. self.collection.get_active().on_tool_delete()
  5485. # work only if the notebook tab on focus is the Tools_Tab
  5486. elif notebook_widget_name == 'tool_tab':
  5487. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5488. # and only if the tool is NCC Tool
  5489. if tool_widget == self.ncclear_tool.toolName:
  5490. self.ncclear_tool.on_tool_delete()
  5491. # and only if the tool is Paint Tool
  5492. elif tool_widget == self.paint_tool.toolName:
  5493. self.paint_tool.on_tool_delete()
  5494. # and only if the tool is Solder Paste Dispensing Tool
  5495. elif tool_widget == self.paste_tool.toolName:
  5496. self.paste_tool.on_tool_delete()
  5497. else:
  5498. self.on_delete()
  5499. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5500. # some screens you have to be careful where you hover with your mouse.
  5501. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5502. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5503. # Complicated, I know :)
  5504. def on_delete(self):
  5505. """
  5506. Delete the currently selected FlatCAMObjs.
  5507. :return: None
  5508. """
  5509. self.report_usage("on_delete()")
  5510. response = None
  5511. bt_ok = None
  5512. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5513. # a geometry object before we update it.
  5514. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5515. and self.grb_editor.editor_active is False:
  5516. if self.defaults["global_delete_confirmation"] is True:
  5517. msgbox = QtWidgets.QMessageBox()
  5518. msgbox.setWindowTitle(_("Delete objects"))
  5519. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  5520. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5521. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5522. "the selected objects?"))
  5523. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5524. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5525. msgbox.setDefaultButton(bt_ok)
  5526. msgbox.exec_()
  5527. response = msgbox.clickedButton()
  5528. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  5529. if self.collection.get_active():
  5530. self.log.debug("App.on_delete()")
  5531. while self.collection.get_active():
  5532. obj_active = self.collection.get_active()
  5533. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  5534. if isinstance(obj_active, FlatCAMGerber):
  5535. for el in obj_active.mark_shapes:
  5536. obj_active.mark_shapes[el].clear(update=True)
  5537. obj_active.mark_shapes[el].enabled = False
  5538. # obj_active.mark_shapes[el] = None
  5539. del el
  5540. elif isinstance(obj_active, FlatCAMCNCjob):
  5541. try:
  5542. obj_active.annotation.clear(update=True)
  5543. obj_active.annotation.enabled = False
  5544. except AttributeError:
  5545. pass
  5546. self.delete_first_selected()
  5547. self.inform.emit('%s...' %
  5548. _("Object(s) deleted"))
  5549. # make sure that the selection shape is deleted, too
  5550. self.delete_selection_shape()
  5551. else:
  5552. self.inform.emit(_("Failed. No object(s) selected..."))
  5553. else:
  5554. self.inform.emit(_("Save the work in Editor and try again ..."))
  5555. def delete_first_selected(self):
  5556. # Keep this for later
  5557. try:
  5558. sel_obj = self.collection.get_active()
  5559. name = sel_obj.options["name"]
  5560. except AttributeError:
  5561. self.log.debug("Nothing selected for deletion")
  5562. return
  5563. # Remove from dictionary
  5564. self.collection.delete_active()
  5565. # Clear form
  5566. self.setup_component_editor()
  5567. self.inform.emit('%s: %s' %
  5568. (_("Object deleted"), name))
  5569. def on_set_origin(self):
  5570. """
  5571. Set the origin to the left mouse click position
  5572. :return: None
  5573. """
  5574. # display the message for the user
  5575. # and ask him to click on the desired position
  5576. self.report_usage("on_set_origin()")
  5577. def origin_replot():
  5578. def worker_task():
  5579. with self.proc_container.new('%s...' % _("Plotting")):
  5580. for obj in self.collection.get_list():
  5581. obj.plot()
  5582. self.plotcanvas.fit_view()
  5583. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  5584. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5585. self.inform.emit(_('Click to set the origin ...'))
  5586. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  5587. # first disconnect it as it may have been used by something else
  5588. try:
  5589. self.replot_signal.disconnect()
  5590. except TypeError:
  5591. pass
  5592. self.replot_signal[list].connect(origin_replot)
  5593. def on_set_zero_click(self, event):
  5594. # this function will be available only for mouse left click
  5595. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5596. if event.button == 1:
  5597. if self.grid_status() == True:
  5598. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5599. else:
  5600. pos = pos_canvas
  5601. x = 0 - pos[0]
  5602. y = 0 - pos[1]
  5603. def worker_task():
  5604. with self.proc_container.new(_("Setting Origin...")):
  5605. for obj in self.collection.get_list():
  5606. obj.offset((x, y))
  5607. self.object_changed.emit(obj)
  5608. # Update the object bounding box options
  5609. a, b, c, d = obj.bounds()
  5610. obj.options['xmin'] = a
  5611. obj.options['ymin'] = b
  5612. obj.options['xmax'] = c
  5613. obj.options['ymax'] = d
  5614. self.inform.emit('[success]%s...' %
  5615. _('Origin set'))
  5616. self.replot_signal.emit([])
  5617. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5618. self.should_we_save = True
  5619. def on_jump_to(self, custom_location=None, fit_center=True):
  5620. """
  5621. Jump to a location by setting the mouse cursor location
  5622. :return:
  5623. """
  5624. self.report_usage("on_jump_to()")
  5625. if not custom_location:
  5626. dia_box = Dialog_box(title=_("Jump to ..."),
  5627. label=_("Enter the coordinates in format X,Y:"),
  5628. icon=QtGui.QIcon('share/jump_to16.png'))
  5629. if dia_box.ok is True:
  5630. try:
  5631. location = eval(dia_box.location)
  5632. if not isinstance(location, tuple):
  5633. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  5634. return
  5635. except:
  5636. return
  5637. else:
  5638. return
  5639. else:
  5640. location = custom_location
  5641. if fit_center:
  5642. self.plotcanvas.fit_center(loc=location)
  5643. cursor = QtGui.QCursor()
  5644. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5645. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  5646. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  5647. self.inform.emit('[success] %s' %
  5648. _("Done."))
  5649. return location
  5650. def on_copy_object(self):
  5651. self.report_usage("on_copy_object()")
  5652. def initialize(obj_init, app):
  5653. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5654. try:
  5655. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5656. except AttributeError:
  5657. pass
  5658. try:
  5659. obj_init.apertures = deepcopy(obj.apertures)
  5660. except AttributeError:
  5661. pass
  5662. try:
  5663. if obj.tools:
  5664. obj_init.tools = deepcopy(obj.tools)
  5665. except Exception as e:
  5666. log.debug("App.on_copy_object() --> %s" % str(e))
  5667. def initialize_excellon(obj_init, app):
  5668. obj_init.tools = deepcopy(obj.tools)
  5669. # drills are offset, so they need to be deep copied
  5670. obj_init.drills = deepcopy(obj.drills)
  5671. # slots are offset, so they need to be deep copied
  5672. obj_init.slots = deepcopy(obj.slots)
  5673. obj_init.create_geometry()
  5674. for obj in self.collection.get_selected():
  5675. obj_name = obj.options["name"]
  5676. try:
  5677. if isinstance(obj, FlatCAMExcellon):
  5678. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  5679. elif isinstance(obj, FlatCAMGerber):
  5680. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  5681. elif isinstance(obj, FlatCAMGeometry):
  5682. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  5683. except Exception as e:
  5684. return "Operation failed: %s" % str(e)
  5685. def on_copy_object2(self, custom_name):
  5686. def initialize_geometry(obj_init, app):
  5687. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5688. try:
  5689. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5690. except AttributeError:
  5691. pass
  5692. try:
  5693. obj_init.apertures = deepcopy(obj.apertures)
  5694. except AttributeError:
  5695. pass
  5696. try:
  5697. if obj.tools:
  5698. obj_init.tools = deepcopy(obj.tools)
  5699. except Exception as e:
  5700. log.debug("on_copy_object2() --> %s" % str(e))
  5701. def initialize_gerber(obj_init, app):
  5702. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5703. obj_init.apertures = deepcopy(obj.apertures)
  5704. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  5705. def initialize_excellon(obj_init, app):
  5706. obj_init.tools = deepcopy(obj.tools)
  5707. # drills are offset, so they need to be deep copied
  5708. obj_init.drills = deepcopy(obj.drills)
  5709. # slots are offset, so they need to be deep copied
  5710. obj_init.slots = deepcopy(obj.slots)
  5711. obj_init.create_geometry()
  5712. for obj in self.collection.get_selected():
  5713. obj_name = obj.options["name"]
  5714. try:
  5715. if isinstance(obj, FlatCAMExcellon):
  5716. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  5717. elif isinstance(obj, FlatCAMGerber):
  5718. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  5719. elif isinstance(obj, FlatCAMGeometry):
  5720. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  5721. except Exception as e:
  5722. return "Operation failed: %s" % str(e)
  5723. def on_rename_object(self, text):
  5724. self.report_usage("on_rename_object()")
  5725. named_obj = self.collection.get_active()
  5726. for obj in named_obj:
  5727. if obj is list:
  5728. self.on_rename_object(text)
  5729. else:
  5730. try:
  5731. obj.options['name'] = text
  5732. except Exception as e:
  5733. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  5734. def convert_any2geo(self):
  5735. self.report_usage("convert_any2geo()")
  5736. def initialize(obj_init, app):
  5737. obj_init.solid_geometry = obj.solid_geometry
  5738. try:
  5739. obj_init.follow_geometry = obj.follow_geometry
  5740. except AttributeError:
  5741. pass
  5742. try:
  5743. obj_init.apertures = obj.apertures
  5744. except AttributeError:
  5745. pass
  5746. try:
  5747. if obj.tools:
  5748. obj_init.tools = obj.tools
  5749. except AttributeError:
  5750. pass
  5751. def initialize_excellon(obj_init, app):
  5752. # objs = self.collection.get_selected()
  5753. # FlatCAMGeometry.merge(objs, obj)
  5754. solid_geo = []
  5755. for tool in obj.tools:
  5756. for geo in obj.tools[tool]['solid_geometry']:
  5757. solid_geo.append(geo)
  5758. obj_init.solid_geometry = deepcopy(solid_geo)
  5759. if not self.collection.get_selected():
  5760. log.warning("App.convert_any2geo --> No object selected")
  5761. self.inform.emit('[WARNING_NOTCL] %s' %
  5762. _("No object is selected. Select an object and try again."))
  5763. return
  5764. for obj in self.collection.get_selected():
  5765. obj_name = obj.options["name"]
  5766. try:
  5767. if isinstance(obj, FlatCAMExcellon):
  5768. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  5769. else:
  5770. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  5771. except Exception as e:
  5772. return "Operation failed: %s" % str(e)
  5773. def convert_any2gerber(self):
  5774. self.report_usage("convert_any2gerber()")
  5775. def initialize_geometry(obj_init, app):
  5776. apertures = {}
  5777. apid = 0
  5778. apertures[str(apid)] = {}
  5779. apertures[str(apid)]['geometry'] = []
  5780. for obj_orig in obj.solid_geometry:
  5781. new_elem = dict()
  5782. new_elem['solid'] = obj_orig
  5783. new_elem['follow'] = obj_orig.exterior
  5784. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  5785. apertures[str(apid)]['size'] = 0.0
  5786. apertures[str(apid)]['type'] = 'C'
  5787. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5788. obj_init.apertures = deepcopy(apertures)
  5789. def initialize_excellon(obj_init, app):
  5790. apertures = {}
  5791. apid = 10
  5792. for tool in obj.tools:
  5793. apertures[str(apid)] = {}
  5794. apertures[str(apid)]['geometry'] = []
  5795. for geo in obj.tools[tool]['solid_geometry']:
  5796. new_el = dict()
  5797. new_el['solid'] = geo
  5798. new_el['follow'] = geo.exterior
  5799. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  5800. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  5801. apertures[str(apid)]['type'] = 'C'
  5802. apid += 1
  5803. # create solid_geometry
  5804. solid_geometry = []
  5805. for apid in apertures:
  5806. for geo_el in apertures[apid]['geometry']:
  5807. solid_geometry.append(geo_el['solid'])
  5808. solid_geometry = MultiPolygon(solid_geometry)
  5809. solid_geometry = solid_geometry.buffer(0.0000001)
  5810. obj_init.solid_geometry = deepcopy(solid_geometry)
  5811. obj_init.apertures = deepcopy(apertures)
  5812. # clear the working objects (perhaps not necessary due of Python GC)
  5813. apertures.clear()
  5814. if not self.collection.get_selected():
  5815. log.warning("App.convert_any2gerber --> No object selected")
  5816. self.inform.emit('[WARNING_NOTCL] %s' %
  5817. _("No object is selected. Select an object and try again."))
  5818. return
  5819. for obj in self.collection.get_selected():
  5820. obj_name = obj.options["name"]
  5821. try:
  5822. if isinstance(obj, FlatCAMExcellon):
  5823. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  5824. elif isinstance(obj, FlatCAMGeometry):
  5825. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  5826. else:
  5827. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  5828. except Exception as e:
  5829. return "Operation failed: %s" % str(e)
  5830. def abort_all_tasks(self):
  5831. if self.abort_flag is False:
  5832. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  5833. self.abort_flag = True
  5834. def app_is_idle(self):
  5835. if self.abort_flag:
  5836. self.inform.emit('[WARNING_NOTCL] %s' %
  5837. _("The current task was gracefully closed on user request..."))
  5838. self.abort_flag = False
  5839. def on_selectall(self):
  5840. self.report_usage("on_selectall()")
  5841. # delete the possible selection box around a possible selected object
  5842. self.delete_selection_shape()
  5843. for name in self.collection.get_names():
  5844. self.collection.set_active(name)
  5845. curr_sel_obj = self.collection.get_by_name(name)
  5846. # create the selection box around the selected object
  5847. if self.defaults['global_selection_shape'] is True:
  5848. self.draw_selection_shape(curr_sel_obj)
  5849. def on_preferences(self):
  5850. # add the tab if it was closed
  5851. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  5852. # delete the absolute and relative position and messages in the infobar
  5853. self.ui.position_label.setText("")
  5854. self.ui.rel_position_label.setText("")
  5855. # Switch plot_area to preferences page
  5856. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  5857. # self.ui.show()
  5858. # this disconnect() is done so the slot will be connected only once
  5859. try:
  5860. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_preferences_closed)
  5861. except (TypeError, AttributeError):
  5862. pass
  5863. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_preferences_closed)
  5864. # detect changes in the preferences
  5865. for idx in range(self.ui.pref_tab_area.count()):
  5866. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5867. try:
  5868. try:
  5869. tb.textEdited.disconnect(self.on_preferences_edited)
  5870. except (TypeError, AttributeError):
  5871. pass
  5872. tb.textEdited.connect(self.on_preferences_edited)
  5873. except AttributeError:
  5874. pass
  5875. try:
  5876. try:
  5877. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5878. except (TypeError, AttributeError):
  5879. pass
  5880. tb.modificationChanged.connect(self.on_preferences_edited)
  5881. except AttributeError:
  5882. pass
  5883. try:
  5884. try:
  5885. tb.toggled.disconnect(self.on_preferences_edited)
  5886. except (TypeError, AttributeError):
  5887. pass
  5888. tb.toggled.connect(self.on_preferences_edited)
  5889. except AttributeError:
  5890. pass
  5891. try:
  5892. try:
  5893. tb.valueChanged.disconnect(self.on_preferences_edited)
  5894. except (TypeError, AttributeError):
  5895. pass
  5896. tb.valueChanged.connect(self.on_preferences_edited)
  5897. except AttributeError:
  5898. pass
  5899. try:
  5900. try:
  5901. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5902. except (TypeError, AttributeError):
  5903. pass
  5904. tb.currentIndexChanged.connect(self.on_preferences_edited)
  5905. except AttributeError:
  5906. pass
  5907. def on_preferences_edited(self):
  5908. self.inform.emit('[WARNING_NOTCL] %s' %
  5909. _("Preferences edited but not saved."))
  5910. self.preferences_changed_flag = True
  5911. def on_preferences_closed(self):
  5912. # disconnect
  5913. for idx in range(self.ui.pref_tab_area.count()):
  5914. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5915. try:
  5916. tb.textEdited.disconnect(self.on_preferences_edited)
  5917. except (TypeError, AttributeError):
  5918. pass
  5919. try:
  5920. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5921. except (TypeError, AttributeError):
  5922. pass
  5923. try:
  5924. tb.toggled.disconnect(self.on_preferences_edited)
  5925. except (TypeError, AttributeError):
  5926. pass
  5927. try:
  5928. tb.valueChanged.disconnect(self.on_preferences_edited)
  5929. except (TypeError, AttributeError):
  5930. pass
  5931. try:
  5932. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5933. except (TypeError, AttributeError):
  5934. pass
  5935. if self.preferences_changed_flag is True:
  5936. msgbox = QtWidgets.QMessageBox()
  5937. msgbox.setText(_("One or more values are changed.\n"
  5938. "Do you want to save the Preferences?"))
  5939. msgbox.setWindowTitle(_("Save Preferences"))
  5940. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  5941. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5942. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5943. msgbox.setDefaultButton(bt_yes)
  5944. msgbox.exec_()
  5945. response = msgbox.clickedButton()
  5946. if response == bt_yes:
  5947. self.on_save_button()
  5948. self.inform.emit('[success] %s' %
  5949. _("Preferences saved."))
  5950. else:
  5951. self.preferences_changed_flag = False
  5952. return
  5953. def on_flipy(self):
  5954. self.report_usage("on_flipy()")
  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 Y 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('X', [px, py])
  5982. obj.plot()
  5983. self.object_changed.emit(obj)
  5984. self.inform.emit('[success] %s' %
  5985. _("Flip on Y 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_flipx(self):
  5991. self.report_usage("on_flipx()")
  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 Flip on X axis."))
  6000. else:
  6001. try:
  6002. # first get a bounding box to fit all
  6003. for obj in obj_list:
  6004. xmin, ymin, xmax, ymax = obj.bounds()
  6005. xminlist.append(xmin)
  6006. yminlist.append(ymin)
  6007. xmaxlist.append(xmax)
  6008. ymaxlist.append(ymax)
  6009. # get the minimum x,y and maximum x,y for all objects selected
  6010. xminimal = min(xminlist)
  6011. yminimal = min(yminlist)
  6012. xmaximal = max(xmaxlist)
  6013. ymaximal = max(ymaxlist)
  6014. px = 0.5 * (xminimal + xmaximal)
  6015. py = 0.5 * (yminimal + ymaximal)
  6016. # execute mirroring
  6017. for obj in obj_list:
  6018. obj.mirror('Y', [px, py])
  6019. obj.plot()
  6020. self.object_changed.emit(obj)
  6021. self.inform.emit('[success] %s' %
  6022. _("Flip on X axis done."))
  6023. except Exception as e:
  6024. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6025. (_("Flip action was not executed."), str(e)))
  6026. return
  6027. def on_rotate(self, silent=False, preset=None):
  6028. self.report_usage("on_rotate()")
  6029. obj_list = self.collection.get_selected()
  6030. xminlist = []
  6031. yminlist = []
  6032. xmaxlist = []
  6033. ymaxlist = []
  6034. if not obj_list:
  6035. self.inform.emit('[WARNING_NOTCL] %s' %
  6036. _("No object selected to Rotate."))
  6037. else:
  6038. if silent is False:
  6039. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6040. min=-360, max=360, decimals=4,
  6041. init_val=float(self.defaults['tools_transform_rotate']))
  6042. num, ok = rotatebox.get_value()
  6043. else:
  6044. num = preset
  6045. ok = True
  6046. if ok:
  6047. try:
  6048. # first get a bounding box to fit all
  6049. for obj in obj_list:
  6050. xmin, ymin, xmax, ymax = obj.bounds()
  6051. xminlist.append(xmin)
  6052. yminlist.append(ymin)
  6053. xmaxlist.append(xmax)
  6054. ymaxlist.append(ymax)
  6055. # get the minimum x,y and maximum x,y for all objects selected
  6056. xminimal = min(xminlist)
  6057. yminimal = min(yminlist)
  6058. xmaximal = max(xmaxlist)
  6059. ymaximal = max(ymaxlist)
  6060. px = 0.5 * (xminimal + xmaximal)
  6061. py = 0.5 * (yminimal + ymaximal)
  6062. for sel_obj in obj_list:
  6063. sel_obj.rotate(-float(num), point=(px, py))
  6064. sel_obj.plot()
  6065. self.object_changed.emit(sel_obj)
  6066. self.inform.emit('[success] %s' %
  6067. _("Rotation done."))
  6068. except Exception as e:
  6069. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6070. (_("Rotation movement was not executed."), str(e)))
  6071. return
  6072. def on_skewx(self):
  6073. self.report_usage("on_skewx()")
  6074. obj_list = self.collection.get_selected()
  6075. xminlist = []
  6076. yminlist = []
  6077. if not obj_list:
  6078. self.inform.emit('[WARNING_NOTCL] %s' %
  6079. _("No object selected to Skew/Shear on X axis."))
  6080. else:
  6081. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6082. min=-360, max=360, decimals=4,
  6083. init_val=float(self.defaults['tools_transform_skew_x']))
  6084. num, ok = skewxbox.get_value()
  6085. if ok:
  6086. # first get a bounding box to fit all
  6087. for obj in obj_list:
  6088. xmin, ymin, xmax, ymax = obj.bounds()
  6089. xminlist.append(xmin)
  6090. yminlist.append(ymin)
  6091. # get the minimum x,y and maximum x,y for all objects selected
  6092. xminimal = min(xminlist)
  6093. yminimal = min(yminlist)
  6094. for obj in obj_list:
  6095. obj.skew(num, 0, point=(xminimal, yminimal))
  6096. obj.plot()
  6097. self.object_changed.emit(obj)
  6098. self.inform.emit('[success] %s' %
  6099. _("Skew on X axis done."))
  6100. def on_skewy(self):
  6101. self.report_usage("on_skewy()")
  6102. obj_list = self.collection.get_selected()
  6103. xminlist = []
  6104. yminlist = []
  6105. if not obj_list:
  6106. self.inform.emit('[WARNING_NOTCL] %s' %
  6107. _("No object selected to Skew/Shear on Y axis."))
  6108. else:
  6109. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6110. min=-360, max=360, decimals=4,
  6111. init_val=float(self.defaults['tools_transform_skew_y']))
  6112. num, ok = skewybox.get_value()
  6113. if ok:
  6114. # first get a bounding box to fit all
  6115. for obj in obj_list:
  6116. xmin, ymin, xmax, ymax = obj.bounds()
  6117. xminlist.append(xmin)
  6118. yminlist.append(ymin)
  6119. # get the minimum x,y and maximum x,y for all objects selected
  6120. xminimal = min(xminlist)
  6121. yminimal = min(yminlist)
  6122. for obj in obj_list:
  6123. obj.skew(0, num, point=(xminimal, yminimal))
  6124. obj.plot()
  6125. self.object_changed.emit(obj)
  6126. self.inform.emit('[success] %s' %
  6127. _("Skew on Y axis done."))
  6128. def on_plots_updated(self):
  6129. """
  6130. Callback used to report when the plots have changed.
  6131. Adjust axes and zooms to fit.
  6132. :return: None
  6133. """
  6134. self.plotcanvas.update() # TODO: Need update canvas?
  6135. self.on_zoom_fit(None)
  6136. self.collection.update_view()
  6137. # self.inform.emit(_("Plots updated ..."))
  6138. # TODO: Rework toolbar 'clear', 'replot' functions
  6139. def on_toolbar_replot(self):
  6140. """
  6141. Callback for toolbar button. Re-plots all objects.
  6142. :return: None
  6143. """
  6144. self.report_usage("on_toolbar_replot")
  6145. self.log.debug("on_toolbar_replot()")
  6146. try:
  6147. self.collection.get_active().read_form()
  6148. except AttributeError:
  6149. self.log.debug("on_toolbar_replot(): AttributeError")
  6150. pass
  6151. self.plot_all()
  6152. def on_row_activated(self, index):
  6153. if index.isValid():
  6154. if index.internalPointer().parent_item != self.collection.root_item:
  6155. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6156. self.collection.on_item_activated(index)
  6157. def grid_status(self):
  6158. if self.ui.grid_snap_btn.isChecked():
  6159. return True
  6160. else:
  6161. return False
  6162. def populate_cmenu_grids(self):
  6163. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6164. self.ui.cmenu_gridmenu.clear()
  6165. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  6166. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  6167. grid_toggle.setCheckable(True)
  6168. if self.grid_status() == True:
  6169. grid_toggle.setChecked(True)
  6170. else:
  6171. grid_toggle.setChecked(False)
  6172. self.ui.cmenu_gridmenu.addSeparator()
  6173. for grid in sorted_list:
  6174. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  6175. action.triggered.connect(self.set_grid)
  6176. self.ui.cmenu_gridmenu.addSeparator()
  6177. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  6178. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  6179. grid_add.triggered.connect(self.on_grid_add)
  6180. grid_delete.triggered.connect(self.on_grid_delete)
  6181. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  6182. def set_grid(self):
  6183. self.ui.grid_gap_x_entry.setText(self.sender().text())
  6184. self.ui.grid_gap_y_entry.setText(self.sender().text())
  6185. def on_grid_add(self):
  6186. # ## Current application units in lower Case
  6187. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6188. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  6189. text=_('Enter a Grid Value:'),
  6190. min=0.0000, max=99.9999, decimals=4)
  6191. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  6192. val, ok = grid_add_popup.get_value()
  6193. if ok:
  6194. if float(val) == 0:
  6195. self.inform.emit('[WARNING_NOTCL] %s' %
  6196. _("Please enter a grid value with non-zero value, in Float format."))
  6197. return
  6198. else:
  6199. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  6200. self.defaults["global_grid_context_menu"][str(units)].append(val)
  6201. self.inform.emit('[success] %s...' %
  6202. _("New Grid added"))
  6203. else:
  6204. self.inform.emit('[WARNING_NOTCL] %s...' %
  6205. _("Grid already exists"))
  6206. else:
  6207. self.inform.emit('[WARNING_NOTCL] %s...' %
  6208. _("Adding New Grid cancelled"))
  6209. def on_grid_delete(self):
  6210. # ## Current application units in lower Case
  6211. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6212. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  6213. text='Enter a Grid Value:',
  6214. min=0.0000, max=99.9999, decimals=4)
  6215. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  6216. val, ok = grid_del_popup.get_value()
  6217. if ok:
  6218. if float(val) == 0:
  6219. self.inform.emit('[WARNING_NOTCL] %s' %
  6220. _("Please enter a grid value with non-zero value, in Float format."))
  6221. return
  6222. else:
  6223. try:
  6224. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  6225. except ValueError:
  6226. self.inform.emit('[ERROR_NOTCL]%s...' %
  6227. _(" Grid Value does not exist"))
  6228. return
  6229. self.inform.emit('[success] %s...' %
  6230. _("Grid Value deleted"))
  6231. else:
  6232. self.inform.emit('[WARNING_NOTCL] %s...' %
  6233. _("Delete Grid value cancelled"))
  6234. def on_shortcut_list(self):
  6235. self.report_usage("on_shortcut_list()")
  6236. # add the tab if it was closed
  6237. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  6238. # delete the absolute and relative position and messages in the infobar
  6239. self.ui.position_label.setText("")
  6240. self.ui.rel_position_label.setText("")
  6241. # Switch plot_area to preferences page
  6242. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  6243. # self.ui.show()
  6244. def on_select_tab(self, name):
  6245. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  6246. if self.ui.splitter.sizes()[0] == 0:
  6247. self.ui.splitter.setSizes([1, 1])
  6248. else:
  6249. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  6250. self.ui.splitter.setSizes([0, 1])
  6251. if name == 'project':
  6252. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6253. elif name == 'selected':
  6254. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6255. elif name == 'tool':
  6256. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  6257. def on_copy_name(self):
  6258. self.report_usage("on_copy_name()")
  6259. obj = self.collection.get_active()
  6260. try:
  6261. name = obj.options["name"]
  6262. except AttributeError:
  6263. log.debug("on_copy_name() --> No object selected to copy it's name")
  6264. self.inform.emit('[WARNING_NOTCL]%s' %
  6265. _(" No object selected to copy it's name"))
  6266. return
  6267. self.clipboard.setText(name)
  6268. self.inform.emit(_("Name copied on clipboard ..."))
  6269. def on_mouse_click_over_plot(self, event):
  6270. """
  6271. Default actions are:
  6272. :param event: Contains information about the event, like which button
  6273. was clicked, the pixel coordinates and the axes coordinates.
  6274. :return: None
  6275. """
  6276. self.pos = []
  6277. # So it can receive key presses
  6278. self.plotcanvas.native.setFocus()
  6279. # Set the mouse button for panning
  6280. self.plotcanvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  6281. self.pos_canvas = self.plotcanvas.translate_coords(event.pos)
  6282. if self.grid_status() == True:
  6283. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  6284. self.app_cursor.enabled = True
  6285. else:
  6286. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  6287. self.app_cursor.enabled = False
  6288. try:
  6289. modifiers = QtWidgets.QApplication.keyboardModifiers()
  6290. if event.button == 1:
  6291. # Reset here the relative coordinates so there is a new reference on the click position
  6292. if self.rel_point1 is None:
  6293. self.rel_point1 = self.pos
  6294. else:
  6295. self.rel_point2 = copy(self.rel_point1)
  6296. self.rel_point1 = self.pos
  6297. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  6298. if modifiers == QtCore.Qt.ShiftModifier:
  6299. # do not auto open the Project Tab
  6300. self.click_noproject = True
  6301. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  6302. self.inform.emit('[success] %s' %
  6303. _("Coordinates copied to clipboard."))
  6304. return
  6305. self.on_mouse_move_over_plot(event, origin_click=True)
  6306. except Exception as e:
  6307. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  6308. def on_double_click_over_plot(self, event):
  6309. self.doubleclick = True
  6310. def on_mouse_move_over_plot(self, event, origin_click=None):
  6311. """
  6312. Callback for the mouse motion event over the plot.
  6313. :param event: Contains information about the event.
  6314. :param origin_click
  6315. :return: None
  6316. """
  6317. # So it can receive key presses
  6318. self.plotcanvas.native.setFocus()
  6319. self.pos_jump = event.pos
  6320. self.ui.popMenu.mouse_is_panning = False
  6321. if not origin_click:
  6322. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  6323. if event.button == 2 and event.is_dragging == 1:
  6324. self.ui.popMenu.mouse_is_panning = True
  6325. return
  6326. if self.rel_point1 is not None:
  6327. try: # May fail in case mouse not within axes
  6328. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  6329. if self.grid_status() == True:
  6330. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6331. self.app_cursor.enabled = True
  6332. # Update cursor
  6333. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  6334. else:
  6335. pos = (pos_canvas[0], pos_canvas[1])
  6336. self.app_cursor.enabled = False
  6337. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6338. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  6339. dx = pos[0] - self.rel_point1[0]
  6340. dy = pos[1] - self.rel_point1[1]
  6341. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6342. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6343. self.mouse = [pos[0], pos[1]]
  6344. # if the mouse is moved and the LMB is clicked then the action is a selection
  6345. if event.is_dragging == 1 and event.button == 1:
  6346. self.delete_selection_shape()
  6347. if dx < 0:
  6348. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  6349. face_color=self.defaults['global_alt_sel_fill'])
  6350. self.selection_type = False
  6351. else:
  6352. self.draw_moving_selection_shape(self.pos, pos)
  6353. self.selection_type = True
  6354. # hover effect - enabled in Preferences -> General -> GUI Settings
  6355. if self.defaults['global_hover']:
  6356. for obj in self.collection.get_list():
  6357. try:
  6358. # select the object(s) only if it is enabled (plotted)
  6359. if obj.options['plot']:
  6360. if obj not in self.collection.get_selected():
  6361. poly_obj = Polygon(
  6362. [(obj.options['xmin'], obj.options['ymin']),
  6363. (obj.options['xmax'], obj.options['ymin']),
  6364. (obj.options['xmax'], obj.options['ymax']),
  6365. (obj.options['xmin'], obj.options['ymax'])]
  6366. )
  6367. if Point(pos).within(poly_obj):
  6368. if obj.isHovering is False:
  6369. obj.isHovering = True
  6370. obj.notHovering = True
  6371. # create the selection box around the selected object
  6372. self.draw_hover_shape(obj, color='#d1e0e0')
  6373. else:
  6374. if obj.notHovering is True:
  6375. obj.notHovering = False
  6376. obj.isHovering = False
  6377. self.delete_hover_shape()
  6378. except:
  6379. # the Exception here will happen if we try to select on screen and we have an
  6380. # newly (and empty) just created Geometry or Excellon object that do not have the
  6381. # xmin, xmax, ymin, ymax options.
  6382. # In this case poly_obj creation (see above) will fail
  6383. pass
  6384. except:
  6385. self.ui.position_label.setText("")
  6386. self.ui.rel_position_label.setText("")
  6387. self.mouse = None
  6388. def on_mouse_click_release_over_plot(self, event):
  6389. """
  6390. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  6391. and has been registered in ''self.__init__()''.
  6392. :param event: contains information about the event.
  6393. :return:
  6394. """
  6395. pos = 0, 0
  6396. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  6397. if self.grid_status() == True:
  6398. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6399. else:
  6400. pos = (pos_canvas[0], pos_canvas[1])
  6401. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  6402. # canvas menu
  6403. if event.button == 2: # right click
  6404. if self.ui.popMenu.mouse_is_panning is False:
  6405. self.cursor = QtGui.QCursor()
  6406. self.populate_cmenu_grids()
  6407. self.ui.popMenu.popup(self.cursor.pos())
  6408. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  6409. # selection and then select a type of selection ("enclosing" or "touching")
  6410. try:
  6411. if event.button == 1: # left click
  6412. if self.doubleclick is True:
  6413. self.doubleclick = False
  6414. if self.collection.get_selected():
  6415. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6416. if self.ui.splitter.sizes()[0] == 0:
  6417. self.ui.splitter.setSizes([1, 1])
  6418. # delete the selection shape(S) as it may be in the way
  6419. self.delete_selection_shape()
  6420. self.delete_hover_shape()
  6421. else:
  6422. if self.selection_type is not None:
  6423. self.selection_area_handler(self.pos, pos, self.selection_type)
  6424. self.selection_type = None
  6425. else:
  6426. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  6427. if key_modifier == QtCore.Qt.ShiftModifier:
  6428. mod_key = 'Shift'
  6429. elif key_modifier == QtCore.Qt.ControlModifier:
  6430. mod_key = 'Control'
  6431. else:
  6432. mod_key = None
  6433. if mod_key == self.defaults["global_mselect_key"]:
  6434. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  6435. # deselect, and if it's not selected then it will be selected
  6436. # If there is no active command (self.command_active is None) then we check if we clicked
  6437. # on a object by checking the bounding limits against mouse click position
  6438. if self.command_active is None:
  6439. self.select_objects(key='CTRL')
  6440. self.delete_hover_shape()
  6441. else:
  6442. # If there is no active command (self.command_active is None) then we check if we clicked
  6443. # on a object by checking the bounding limits against mouse click position
  6444. if self.command_active is None:
  6445. self.select_objects()
  6446. self.delete_hover_shape()
  6447. except Exception as e:
  6448. log.warning("Error: %s" % str(e))
  6449. return
  6450. def selection_area_handler(self, start_pos, end_pos, sel_type):
  6451. """
  6452. :param start_pos: mouse position when the selection LMB click was done
  6453. :param end_pos: mouse position when the left mouse button is released
  6454. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  6455. :return:
  6456. """
  6457. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  6458. self.delete_selection_shape()
  6459. for obj in self.collection.get_list():
  6460. try:
  6461. # select the object(s) only if it is enabled (plotted)
  6462. if obj.options['plot']:
  6463. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  6464. (obj.options['xmax'], obj.options['ymin']),
  6465. (obj.options['xmax'], obj.options['ymax']),
  6466. (obj.options['xmin'], obj.options['ymax'])])
  6467. if sel_type is True:
  6468. if poly_obj.within(poly_selection):
  6469. # create the selection box around the selected object
  6470. if self.defaults['global_selection_shape'] is True:
  6471. self.draw_selection_shape(obj)
  6472. self.collection.set_active(obj.options['name'])
  6473. else:
  6474. if poly_selection.intersects(poly_obj):
  6475. # create the selection box around the selected object
  6476. if self.defaults['global_selection_shape'] is True:
  6477. self.draw_selection_shape(obj)
  6478. self.collection.set_active(obj.options['name'])
  6479. except Exception as e:
  6480. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  6481. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  6482. # In this case poly_obj creation (see above) will fail
  6483. log.debug("App.selection_area_handler() --> %s" % str(e))
  6484. def select_objects(self, key=None):
  6485. # list where we store the overlapped objects under our mouse left click position
  6486. objects_under_the_click_list = []
  6487. # Populate the list with the overlapped objects on the click position
  6488. curr_x, curr_y = self.pos
  6489. for obj in self.all_objects_list:
  6490. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  6491. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  6492. if obj.options['name'] not in objects_under_the_click_list:
  6493. if obj.options['plot']:
  6494. # add objects to the objects_under_the_click list only if the object is plotted
  6495. # (active and not disabled)
  6496. objects_under_the_click_list.append(obj.options['name'])
  6497. try:
  6498. # If there is no element in the overlapped objects list then make everyone inactive
  6499. # because we selected "nothing"
  6500. if not objects_under_the_click_list:
  6501. self.collection.set_all_inactive()
  6502. # delete the possible selection box around a possible selected object
  6503. self.delete_selection_shape()
  6504. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  6505. # only when working on App
  6506. if self.call_source == 'app':
  6507. if self.click_noproject is False:
  6508. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6509. else:
  6510. # restore auto open the Project Tab
  6511. self.click_noproject = False
  6512. # delete any text in the status bar, implicitly the last object name that was selected
  6513. self.inform.emit("")
  6514. else:
  6515. self.call_source = 'app'
  6516. else:
  6517. # case when there is only an object under the click and we toggle it
  6518. if len(objects_under_the_click_list) == 1:
  6519. if self.collection.get_active() is None:
  6520. self.collection.set_active(objects_under_the_click_list[0])
  6521. # create the selection box around the selected object
  6522. curr_sel_obj = self.collection.get_active()
  6523. if self.defaults['global_selection_shape'] is True:
  6524. self.draw_selection_shape(curr_sel_obj)
  6525. # self.inform.emit('[selected] %s: %s selected' %
  6526. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6527. if curr_sel_obj.kind == 'gerber':
  6528. self.inform.emit(
  6529. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6530. color='green', name=str(curr_sel_obj.options['name'])))
  6531. elif curr_sel_obj.kind == 'excellon':
  6532. self.inform.emit(
  6533. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6534. color='brown', name=str(curr_sel_obj.options['name'])))
  6535. elif curr_sel_obj.kind == 'cncjob':
  6536. self.inform.emit(
  6537. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6538. color='blue', name=str(curr_sel_obj.options['name'])))
  6539. elif curr_sel_obj.kind == 'geometry':
  6540. self.inform.emit(
  6541. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6542. color='red', name=str(curr_sel_obj.options['name'])))
  6543. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  6544. self.collection.set_all_inactive()
  6545. self.delete_selection_shape()
  6546. self.collection.set_active(objects_under_the_click_list[0])
  6547. # create the selection box around the selected object
  6548. curr_sel_obj = self.collection.get_active()
  6549. if self.defaults['global_selection_shape'] is True:
  6550. self.draw_selection_shape(curr_sel_obj)
  6551. # self.inform.emit('[selected] %s: %s selected' %
  6552. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6553. if curr_sel_obj.kind == 'gerber':
  6554. self.inform.emit(
  6555. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6556. color='green', name=str(curr_sel_obj.options['name'])))
  6557. elif curr_sel_obj.kind == 'excellon':
  6558. self.inform.emit(
  6559. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6560. color='brown', name=str(curr_sel_obj.options['name'])))
  6561. elif curr_sel_obj.kind == 'cncjob':
  6562. self.inform.emit(
  6563. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6564. color='blue', name=str(curr_sel_obj.options['name'])))
  6565. elif curr_sel_obj.kind == 'geometry':
  6566. self.inform.emit(
  6567. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6568. color='red', name=str(curr_sel_obj.options['name'])))
  6569. else:
  6570. self.collection.set_all_inactive()
  6571. self.delete_selection_shape()
  6572. if self.call_source == 'app':
  6573. # delete any text in the status bar, implicitly the last object name that was selected
  6574. self.inform.emit("")
  6575. else:
  6576. self.call_source = 'app'
  6577. else:
  6578. # If there is no selected object
  6579. # make active the first element of the overlapped objects list
  6580. if self.collection.get_active() is None:
  6581. self.collection.set_active(objects_under_the_click_list[0])
  6582. name_sel_obj = self.collection.get_active().options['name']
  6583. # In case that there is a selected object but it is not in the overlapped object list
  6584. # make that object inactive and activate the first element in the overlapped object list
  6585. if name_sel_obj not in objects_under_the_click_list:
  6586. self.collection.set_inactive(name_sel_obj)
  6587. name_sel_obj = objects_under_the_click_list[0]
  6588. self.collection.set_active(name_sel_obj)
  6589. else:
  6590. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  6591. self.collection.set_all_inactive()
  6592. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  6593. len(objects_under_the_click_list)])
  6594. curr_sel_obj = self.collection.get_active()
  6595. # delete the possible selection box around a possible selected object
  6596. self.delete_selection_shape()
  6597. # create the selection box around the selected object
  6598. if self.defaults['global_selection_shape'] is True:
  6599. self.draw_selection_shape(curr_sel_obj)
  6600. # self.inform.emit('[selected] %s: %s selected' %
  6601. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6602. if curr_sel_obj.kind == 'gerber':
  6603. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6604. color='green', name=str(curr_sel_obj.options['name'])))
  6605. elif curr_sel_obj.kind == 'excellon':
  6606. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6607. color='brown', name=str(curr_sel_obj.options['name'])))
  6608. elif curr_sel_obj.kind == 'cncjob':
  6609. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6610. color='blue', name=str(curr_sel_obj.options['name'])))
  6611. elif curr_sel_obj.kind == 'geometry':
  6612. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6613. color='red', name=str(curr_sel_obj.options['name'])))
  6614. # for obj in self.collection.get_list():
  6615. # obj.plot()
  6616. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  6617. # TODO: on selected objects change the object colors and do not draw the selection box
  6618. # self.plotcanvas.update() # this updates the canvas
  6619. except Exception as e:
  6620. log.error("[ERROR] Something went bad. %s" % str(e))
  6621. return
  6622. def delete_hover_shape(self):
  6623. self.hover_shapes.clear()
  6624. self.hover_shapes.redraw()
  6625. def draw_hover_shape(self, sel_obj, color=None):
  6626. """
  6627. :param sel_obj: the object for which the hover shape must be drawn
  6628. :return:
  6629. """
  6630. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6631. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6632. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6633. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6634. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  6635. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6636. hover_rect = hover_rect.buffer(-0.1)
  6637. hover_rect = hover_rect.buffer(0.2)
  6638. else:
  6639. hover_rect = hover_rect.buffer(-0.00393)
  6640. hover_rect = hover_rect.buffer(0.00787)
  6641. if color:
  6642. face = Color(color)
  6643. face.alpha = 0.2
  6644. outline = Color(color, alpha=0.8)
  6645. else:
  6646. face = Color(self.defaults['global_sel_fill'])
  6647. face.alpha = 0.2
  6648. outline = self.defaults['global_sel_line']
  6649. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  6650. def delete_selection_shape(self):
  6651. self.move_tool.sel_shapes.clear()
  6652. self.move_tool.sel_shapes.redraw()
  6653. def draw_selection_shape(self, sel_obj, color=None):
  6654. """
  6655. :param sel_obj: the object for which the selection shape must be drawn
  6656. :return:
  6657. """
  6658. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6659. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6660. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6661. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6662. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6663. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6664. sel_rect = sel_rect.buffer(-0.1)
  6665. sel_rect = sel_rect.buffer(0.2)
  6666. else:
  6667. sel_rect = sel_rect.buffer(-0.00393)
  6668. sel_rect = sel_rect.buffer(0.00787)
  6669. if color:
  6670. face = Color(color, alpha=0.2)
  6671. outline = Color(color, alpha=0.8)
  6672. else:
  6673. face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  6674. outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  6675. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  6676. color=outline,
  6677. face_color=face,
  6678. update=True,
  6679. layer=0,
  6680. tolerance=None))
  6681. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  6682. """
  6683. :param old_coords: old coordinates
  6684. :param coords: new coordinates
  6685. :return:
  6686. """
  6687. if 'color' in kwargs:
  6688. color = kwargs['color']
  6689. else:
  6690. color = self.defaults['global_sel_line']
  6691. if 'face_color' in kwargs:
  6692. face_color = kwargs['face_color']
  6693. else:
  6694. face_color = self.defaults['global_sel_fill']
  6695. if 'face_alpha' in kwargs:
  6696. face_alpha = kwargs['face_alpha']
  6697. else:
  6698. face_alpha = 0.3
  6699. x0, y0 = old_coords
  6700. x1, y1 = coords
  6701. pt1 = (x0, y0)
  6702. pt2 = (x1, y0)
  6703. pt3 = (x1, y1)
  6704. pt4 = (x0, y1)
  6705. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6706. color_t = Color(face_color)
  6707. color_t.alpha = face_alpha
  6708. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  6709. layer=0, tolerance=None)
  6710. def on_file_new_click(self):
  6711. if self.collection.get_list() and self.should_we_save:
  6712. msgbox = QtWidgets.QMessageBox()
  6713. # msgbox.setText("<B>Save changes ...</B>")
  6714. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  6715. "Creating a New project will delete them.\n"
  6716. "Do you want to Save the project?"))
  6717. msgbox.setWindowTitle(_("Save changes"))
  6718. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6719. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6720. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6721. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6722. msgbox.setDefaultButton(bt_yes)
  6723. msgbox.exec_()
  6724. response = msgbox.clickedButton()
  6725. if response == bt_yes:
  6726. self.on_file_saveprojectas()
  6727. elif response == bt_cancel:
  6728. return
  6729. elif response == bt_no:
  6730. self.on_file_new()
  6731. else:
  6732. self.on_file_new()
  6733. self.inform.emit('[success] %s...' %
  6734. _("New Project created"))
  6735. def on_file_new(self, cli=None):
  6736. """
  6737. Callback for menu item File->New. Returns the application to its
  6738. startup state. This method is thread-safe.
  6739. :return: None
  6740. """
  6741. self.report_usage("on_file_new")
  6742. # Remove everything from memory
  6743. App.log.debug("on_file_new()")
  6744. if self.call_source != 'app':
  6745. self.editor2object(cleanup=True)
  6746. # ## EDITOR section
  6747. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  6748. self.exc_editor = FlatCAMExcEditor(self)
  6749. self.grb_editor = FlatCAMGrbEditor(self)
  6750. # Clear pool
  6751. self.clear_pool()
  6752. for obj in self.collection.get_list():
  6753. # delete shapes left drawn from mark shape_collections, if any
  6754. if isinstance(obj, FlatCAMGerber):
  6755. try:
  6756. obj.mark_shapes.enabled = False
  6757. obj.mark_shapes.clear(update=True)
  6758. except AttributeError:
  6759. pass
  6760. # also delete annotation shapes, if any
  6761. elif isinstance(obj, FlatCAMCNCjob):
  6762. try:
  6763. obj.annotation.enabled = False
  6764. obj.annotation.clear(update=True)
  6765. except AttributeError:
  6766. pass
  6767. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6768. self.init_tcl()
  6769. self.delete_selection_shape()
  6770. self.collection.delete_all()
  6771. self.setup_component_editor()
  6772. # Clear project filename
  6773. self.project_filename = None
  6774. # Load the application defaults
  6775. self.load_defaults(filename='current_defaults')
  6776. # Re-fresh project options
  6777. self.on_options_app2project()
  6778. # Init Tools
  6779. self.init_tools()
  6780. if cli is None:
  6781. # Close any Tabs opened in the Plot Tab Area section
  6782. for index in range(self.ui.plot_tab_area.count()):
  6783. self.ui.plot_tab_area.closeTab(index)
  6784. # for whatever reason previous command does not close the last tab so I do it manually
  6785. self.ui.plot_tab_area.closeTab(0)
  6786. # # And then add again the Plot Area
  6787. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  6788. self.ui.plot_tab_area.protectTab(0)
  6789. # take the focus of the Notebook on Project Tab.
  6790. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6791. self.set_ui_title(name=_("New Project - Not saved"))
  6792. def obj_properties(self):
  6793. self.report_usage("obj_properties()")
  6794. self.properties_tool.run(toggle=False)
  6795. def on_project_context_save(self):
  6796. obj = self.collection.get_active()
  6797. if type(obj) == FlatCAMGeometry:
  6798. self.on_file_exportdxf()
  6799. elif type(obj) == FlatCAMExcellon:
  6800. self.on_file_saveexcellon()
  6801. elif type(obj) == FlatCAMCNCjob:
  6802. obj.on_exportgcode_button_click()
  6803. elif type(obj) == FlatCAMGerber:
  6804. self.on_file_savegerber()
  6805. def obj_move(self):
  6806. self.report_usage("obj_move()")
  6807. self.move_tool.run(toggle=False)
  6808. def on_fileopengerber(self, checked=None, name=None):
  6809. """
  6810. File menu callback for opening a Gerber.
  6811. :return: None
  6812. """
  6813. self.report_usage("on_fileopengerber")
  6814. App.log.debug("on_fileopengerber()")
  6815. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6816. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6817. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  6818. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6819. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6820. "*.mil);;" \
  6821. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6822. "Allegro Files (*.art);;" \
  6823. "Mentor Files (*.pho *.gdo);;" \
  6824. "All Files (*.*)"
  6825. if name is None:
  6826. try:
  6827. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6828. directory=self.get_last_folder(),
  6829. filter=_filter_)
  6830. except TypeError:
  6831. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6832. filenames = [str(filename) for filename in filenames]
  6833. else:
  6834. filenames = [name]
  6835. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6836. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6837. _("Opening Gerber file.")),
  6838. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6839. color=QtGui.QColor("gray"))
  6840. if len(filenames) == 0:
  6841. self.inform.emit('[WARNING_NOTCL] %s' %
  6842. _("Open Gerber cancelled."))
  6843. else:
  6844. for filename in filenames:
  6845. if filename != '':
  6846. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6847. def on_fileopenexcellon(self, checked=None, name=None):
  6848. """
  6849. File menu callback for opening an Excellon file.
  6850. :return: None
  6851. """
  6852. self.report_usage("on_fileopenexcellon")
  6853. App.log.debug("on_fileopenexcellon()")
  6854. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6855. "All Files (*.*)"
  6856. if name is None:
  6857. try:
  6858. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6859. directory=self.get_last_folder(),
  6860. filter=_filter_)
  6861. except TypeError:
  6862. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6863. filenames = [str(filename) for filename in filenames]
  6864. else:
  6865. filenames = [str(name)]
  6866. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6867. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6868. _("Opening Excellon file.")),
  6869. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6870. color=QtGui.QColor("gray"))
  6871. if len(filenames) == 0:
  6872. self.inform.emit('[WARNING_NOTCL]%s' %
  6873. _(" Open Excellon cancelled."))
  6874. else:
  6875. for filename in filenames:
  6876. if filename != '':
  6877. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6878. def on_fileopengcode(self, checked=None, name=None):
  6879. """
  6880. File menu call back for opening gcode.
  6881. :return: None
  6882. """
  6883. self.report_usage("on_fileopengcode")
  6884. App.log.debug("on_fileopengcode()")
  6885. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6886. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6887. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  6888. "All Files (*.*)"
  6889. if name is None:
  6890. try:
  6891. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6892. directory=self.get_last_folder(),
  6893. filter=_filter_)
  6894. except TypeError:
  6895. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6896. filenames = [str(filename) for filename in filenames]
  6897. else:
  6898. filenames = [name]
  6899. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6900. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6901. _("Opening G-Code file.")),
  6902. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6903. color=QtGui.QColor("gray"))
  6904. if len(filenames) == 0:
  6905. self.inform.emit('[WARNING_NOTCL] %s' %
  6906. _("Open G-Code cancelled."))
  6907. else:
  6908. for filename in filenames:
  6909. if filename != '':
  6910. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename]})
  6911. def on_file_openproject(self, checked=None):
  6912. """
  6913. File menu callback for opening a project.
  6914. :return: None
  6915. """
  6916. self.report_usage("on_file_openproject")
  6917. App.log.debug("on_file_openproject()")
  6918. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6919. try:
  6920. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6921. directory=self.get_last_folder(), filter=_filter_)
  6922. except TypeError:
  6923. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6924. # The Qt methods above will return a QString which can cause problems later.
  6925. # So far json.dump() will fail to serialize it.
  6926. # TODO: Improve the serialization methods and remove this fix.
  6927. filename = str(filename)
  6928. if filename == "":
  6929. self.inform.emit('[WARNING_NOTCL] %s' %
  6930. _("Open Project cancelled."))
  6931. else:
  6932. # self.worker_task.emit({'fcn': self.open_project,
  6933. # 'params': [filename]})
  6934. # The above was failing because open_project() is not
  6935. # thread safe. The new_project()
  6936. self.open_project(filename)
  6937. def on_file_openconfig(self, checked=None):
  6938. """
  6939. File menu callback for opening a config file.
  6940. :return: None
  6941. """
  6942. self.report_usage("on_file_openconfig")
  6943. App.log.debug("on_file_openconfig()")
  6944. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6945. try:
  6946. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6947. directory=self.data_path, filter=_filter_)
  6948. except TypeError:
  6949. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6950. filter=_filter_)
  6951. if filename == "":
  6952. self.inform.emit('[WARNING_NOTCL] %s' %
  6953. _("Open Config cancelled."))
  6954. else:
  6955. self.open_config_file(filename)
  6956. def on_file_exportsvg(self):
  6957. """
  6958. Callback for menu item File->Export SVG.
  6959. :return: None
  6960. """
  6961. self.report_usage("on_file_exportsvg")
  6962. App.log.debug("on_file_exportsvg()")
  6963. obj = self.collection.get_active()
  6964. if obj is None:
  6965. self.inform.emit('[WARNING_NOTCL] %s' %
  6966. _("No object selected."))
  6967. msg = _("Please Select a Geometry object to export")
  6968. msgbox = QtWidgets.QMessageBox()
  6969. msgbox.setInformativeText(msg)
  6970. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6971. msgbox.setDefaultButton(bt_ok)
  6972. msgbox.exec_()
  6973. return
  6974. # Check for more compatible types and add as required
  6975. if (not isinstance(obj, FlatCAMGeometry)
  6976. and not isinstance(obj, FlatCAMGerber)
  6977. and not isinstance(obj, FlatCAMCNCjob)
  6978. and not isinstance(obj, FlatCAMExcellon)):
  6979. msg = '[ERROR_NOTCL] %s' % \
  6980. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6981. msgbox = QtWidgets.QMessageBox()
  6982. msgbox.setInformativeText(msg)
  6983. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6984. msgbox.setDefaultButton(bt_ok)
  6985. msgbox.exec_()
  6986. return
  6987. name = obj.options["name"]
  6988. _filter = "SVG File (*.svg);;All Files (*.*)"
  6989. try:
  6990. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6991. caption=_("Export SVG"),
  6992. directory=self.get_last_save_folder() + '/' + str(name),
  6993. filter=_filter)
  6994. except TypeError:
  6995. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  6996. filename = str(filename)
  6997. if filename == "":
  6998. self.inform.emit('[WARNING_NOTCL]%s' %
  6999. _(" Export SVG cancelled."))
  7000. return
  7001. else:
  7002. self.export_svg(name, filename)
  7003. if self.defaults["global_open_style"] is False:
  7004. self.file_opened.emit("SVG", filename)
  7005. self.file_saved.emit("SVG", filename)
  7006. def on_file_exportpng(self):
  7007. self.report_usage("on_file_exportpng")
  7008. App.log.debug("on_file_exportpng()")
  7009. self.date = str(datetime.today()).rpartition('.')[0]
  7010. self.date = ''.join(c for c in self.date if c not in ':-')
  7011. self.date = self.date.replace(' ', '_')
  7012. image = _screenshot()
  7013. data = np.asarray(image)
  7014. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  7015. self.inform.emit('[[WARNING_NOTCL]] %s' %
  7016. _('Data must be a 3D array with last dimension 3 or 4'))
  7017. return
  7018. filter_ = "PNG File (*.png);;All Files (*.*)"
  7019. try:
  7020. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7021. caption=_("Export PNG Image"),
  7022. directory=self.get_last_save_folder() + '/png_' + self.date,
  7023. filter=filter_)
  7024. except TypeError:
  7025. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  7026. filename = str(filename)
  7027. if filename == "":
  7028. self.inform.emit(_("Export PNG cancelled."))
  7029. return
  7030. else:
  7031. write_png(filename, data)
  7032. if self.defaults["global_open_style"] is False:
  7033. self.file_opened.emit("png", filename)
  7034. self.file_saved.emit("png", filename)
  7035. def on_file_savegerber(self):
  7036. """
  7037. Callback for menu item in Project context menu.
  7038. :return: None
  7039. """
  7040. self.report_usage("on_file_savegerber")
  7041. App.log.debug("on_file_savegerber()")
  7042. obj = self.collection.get_active()
  7043. if obj is None:
  7044. self.inform.emit('[WARNING_NOTCL] %s' %
  7045. _("No object selected. Please select an Gerber object to export."))
  7046. return
  7047. # Check for more compatible types and add as required
  7048. if not isinstance(obj, FlatCAMGerber):
  7049. self.inform.emit('[ERROR_NOTCL] %s' %
  7050. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7051. return
  7052. name = self.collection.get_active().options["name"]
  7053. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  7054. try:
  7055. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7056. caption="Save Gerber source file",
  7057. directory=self.get_last_save_folder() + '/' + name,
  7058. filter=_filter)
  7059. except TypeError:
  7060. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  7061. filename = str(filename)
  7062. if filename == "":
  7063. self.inform.emit('[WARNING_NOTCL] %s' %
  7064. _("Save Gerber source file cancelled."))
  7065. return
  7066. else:
  7067. self.save_source_file(name, filename)
  7068. if self.defaults["global_open_style"] is False:
  7069. self.file_opened.emit("Gerber", filename)
  7070. self.file_saved.emit("Gerber", filename)
  7071. def on_file_saveexcellon(self):
  7072. """
  7073. Callback for menu item in project context menu.
  7074. :return: None
  7075. """
  7076. self.report_usage("on_file_saveexcellon")
  7077. App.log.debug("on_file_saveexcellon()")
  7078. obj = self.collection.get_active()
  7079. if obj is None:
  7080. self.inform.emit('[WARNING_NOTCL] %s' %
  7081. _("No object selected. Please select an Excellon object to export."))
  7082. return
  7083. # Check for more compatible types and add as required
  7084. if not isinstance(obj, FlatCAMExcellon):
  7085. self.inform.emit('[ERROR_NOTCL] %s' %
  7086. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7087. return
  7088. name = self.collection.get_active().options["name"]
  7089. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7090. try:
  7091. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7092. caption=_("Save Excellon source file"),
  7093. directory=self.get_last_save_folder() + '/' + name,
  7094. filter=_filter)
  7095. except TypeError:
  7096. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  7097. filename = str(filename)
  7098. if filename == "":
  7099. self.inform.emit('[WARNING_NOTCL] %s' %
  7100. _("Saving Excellon source file cancelled."))
  7101. return
  7102. else:
  7103. self.save_source_file(name, filename)
  7104. if self.defaults["global_open_style"] is False:
  7105. self.file_opened.emit("Excellon", filename)
  7106. self.file_saved.emit("Excellon", filename)
  7107. def on_file_exportexcellon(self):
  7108. """
  7109. Callback for menu item File->Export->Excellon.
  7110. :return: None
  7111. """
  7112. self.report_usage("on_file_exportexcellon")
  7113. App.log.debug("on_file_exportexcellon()")
  7114. obj = self.collection.get_active()
  7115. if obj is None:
  7116. self.inform.emit('[WARNING_NOTCL] %s' %
  7117. _("No object selected. Please Select an Excellon object to export."))
  7118. return
  7119. # Check for more compatible types and add as required
  7120. if not isinstance(obj, FlatCAMExcellon):
  7121. self.inform.emit('[ERROR_NOTCL] %s' %
  7122. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7123. return
  7124. name = self.collection.get_active().options["name"]
  7125. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7126. try:
  7127. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7128. caption=_("Export Excellon"),
  7129. directory=self.get_last_save_folder() + '/' + name,
  7130. filter=_filter)
  7131. except TypeError:
  7132. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  7133. filename = str(filename)
  7134. if filename == "":
  7135. self.inform.emit('[WARNING_NOTCL] %s' %
  7136. _("Export Excellon cancelled."))
  7137. return
  7138. else:
  7139. self.export_excellon(name, filename)
  7140. if self.defaults["global_open_style"] is False:
  7141. self.file_opened.emit("Excellon", filename)
  7142. self.file_saved.emit("Excellon", filename)
  7143. def on_file_exportgerber(self):
  7144. """
  7145. Callback for menu item File->Export->Gerber.
  7146. :return: None
  7147. """
  7148. self.report_usage("on_file_exportgerber")
  7149. App.log.debug("on_file_exportgerber()")
  7150. obj = self.collection.get_active()
  7151. if obj is None:
  7152. self.inform.emit('[WARNING_NOTCL] %s' %
  7153. _("No object selected. Please Select an Gerber object to export."))
  7154. return
  7155. # Check for more compatible types and add as required
  7156. if not isinstance(obj, FlatCAMGerber):
  7157. self.inform.emit('[ERROR_NOTCL] %s' %
  7158. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7159. return
  7160. name = self.collection.get_active().options["name"]
  7161. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  7162. try:
  7163. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7164. caption=_("Export Gerber"),
  7165. directory=self.get_last_save_folder() + '/' + name,
  7166. filter=_filter_)
  7167. except TypeError:
  7168. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  7169. filename = str(filename)
  7170. if filename == "":
  7171. self.inform.emit('[WARNING_NOTCL] %s' %
  7172. _("Export Gerber cancelled."))
  7173. return
  7174. else:
  7175. self.export_gerber(name, filename)
  7176. if self.defaults["global_open_style"] is False:
  7177. self.file_opened.emit("Gerber", filename)
  7178. self.file_saved.emit("Gerber", filename)
  7179. def on_file_exportdxf(self):
  7180. """
  7181. Callback for menu item File->Export DXF.
  7182. :return: None
  7183. """
  7184. self.report_usage("on_file_exportdxf")
  7185. App.log.debug("on_file_exportdxf()")
  7186. obj = self.collection.get_active()
  7187. if obj is None:
  7188. self.inform.emit('[WARNING_NOTCL] %s' %
  7189. _("No object selected."))
  7190. msg = _("Please Select a Geometry object to export")
  7191. msgbox = QtWidgets.QMessageBox()
  7192. msgbox.setInformativeText(msg)
  7193. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7194. msgbox.setDefaultButton(bt_ok)
  7195. msgbox.exec_()
  7196. return
  7197. # Check for more compatible types and add as required
  7198. if not isinstance(obj, FlatCAMGeometry):
  7199. msg = '[ERROR_NOTCL] %s' % \
  7200. _("Only Geometry objects can be used.")
  7201. msgbox = QtWidgets.QMessageBox()
  7202. msgbox.setInformativeText(msg)
  7203. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7204. msgbox.setDefaultButton(bt_ok)
  7205. msgbox.exec_()
  7206. return
  7207. name = self.collection.get_active().options["name"]
  7208. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7209. try:
  7210. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7211. caption=_("Export DXF"),
  7212. directory=self.get_last_save_folder() + '/' + name,
  7213. filter=_filter_)
  7214. except TypeError:
  7215. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  7216. filter=_filter_)
  7217. filename = str(filename)
  7218. if filename == "":
  7219. self.inform.emit('[WARNING_NOTCL] %s' %
  7220. _("Export DXF cancelled."))
  7221. return
  7222. else:
  7223. self.export_dxf(name, filename)
  7224. if self.defaults["global_open_style"] is False:
  7225. self.file_opened.emit("DXF", filename)
  7226. self.file_saved.emit("DXF", filename)
  7227. def on_file_importsvg(self, type_of_obj):
  7228. """
  7229. Callback for menu item File->Import SVG.
  7230. :param type_of_obj: to import the SVG as Geometry or as Gerber
  7231. :type type_of_obj: str
  7232. :return: None
  7233. """
  7234. self.report_usage("on_file_importsvg")
  7235. App.log.debug("on_file_importsvg()")
  7236. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  7237. try:
  7238. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7239. directory=self.get_last_folder(), filter=_filter_)
  7240. except TypeError:
  7241. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7242. filter=_filter_)
  7243. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7244. type_of_obj = "geometry"
  7245. filenames = [str(filename) for filename in filenames]
  7246. if len(filenames) == 0:
  7247. self.inform.emit('[WARNING_NOTCL] %s' %
  7248. _("Open SVG cancelled."))
  7249. else:
  7250. for filename in filenames:
  7251. if filename != '':
  7252. self.worker_task.emit({'fcn': self.import_svg,
  7253. 'params': [filename, type_of_obj]})
  7254. def on_file_importdxf(self, type_of_obj):
  7255. """
  7256. Callback for menu item File->Import DXF.
  7257. :param type_of_obj: to import the DXF as Geometry or as Gerber
  7258. :type type_of_obj: str
  7259. :return: None
  7260. """
  7261. self.report_usage("on_file_importdxf")
  7262. App.log.debug("on_file_importdxf()")
  7263. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7264. try:
  7265. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7266. directory=self.get_last_folder(),
  7267. filter=_filter_)
  7268. except TypeError:
  7269. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7270. filter=_filter_)
  7271. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7272. type_of_obj = "geometry"
  7273. filenames = [str(filename) for filename in filenames]
  7274. if len(filenames) == 0:
  7275. self.inform.emit('[WARNING_NOTCL] %s' %
  7276. _("Open DXF cancelled."))
  7277. else:
  7278. for filename in filenames:
  7279. if filename != '':
  7280. self.worker_task.emit({'fcn': self.import_dxf,
  7281. 'params': [filename, type_of_obj]})
  7282. # ###############################################################################################################
  7283. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  7284. # ###############################################################################################################
  7285. def init_code_editor(self, name):
  7286. # Signals section
  7287. # Disconnect the old signals
  7288. try:
  7289. self.ui.buttonOpen.clicked.disconnect()
  7290. except TypeError:
  7291. pass
  7292. try:
  7293. self.ui.buttonSave.clicked.disconnect()
  7294. except TypeError:
  7295. pass
  7296. # add the tab if it was closed
  7297. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, '%s' % name)
  7298. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  7299. # delete the absolute and relative position and messages in the infobar
  7300. self.ui.position_label.setText("")
  7301. self.ui.rel_position_label.setText("")
  7302. # first clear previous text in text editor (if any)
  7303. self.ui.code_editor.clear()
  7304. self.ui.code_editor.setReadOnly(False)
  7305. self.toggle_codeeditor = True
  7306. self.ui.code_editor.completer_enable = False
  7307. self.ui.buttonRun.hide()
  7308. # make sure to keep a reference to the code editor
  7309. self.reference_code_editor = self.ui.code_editor
  7310. # Switch plot_area to CNCJob tab
  7311. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  7312. def on_view_source(self):
  7313. self.inform.emit('%s' %
  7314. _("Viewing the source code of the selected object."))
  7315. self.proc_container.view.set_busy(_("Loading..."))
  7316. try:
  7317. obj = self.collection.get_active()
  7318. except Exception as e:
  7319. log.debug("App.on_view_source() --> %s" % str(e))
  7320. self.inform.emit('[WARNING_NOTCL] %s' %
  7321. _("Select an Gerber or Excellon file to view it's source file."))
  7322. return 'fail'
  7323. if obj.kind == 'gerber':
  7324. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  7325. elif obj.kind == 'excellon':
  7326. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  7327. elif obj.kind == 'cncjob':
  7328. "GCode Files (*.NC);;All Files (*.*)"
  7329. else:
  7330. flt = "All Files (*.*)"
  7331. self.init_code_editor(name=_("Source Editor"))
  7332. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  7333. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  7334. # then append the text from GCode to the text editor
  7335. if obj.kind == 'cncjob':
  7336. try:
  7337. file = obj.export_gcode(
  7338. preamble=self.defaults["cncjob_prepend"],
  7339. postamble=self.defaults["cncjob_append"],
  7340. to_file=True)
  7341. if file == 'fail':
  7342. return 'fail'
  7343. except AttributeError:
  7344. self.inform.emit('[WARNING_NOTCL] %s' %
  7345. _("There is no selected object for which to see it's source file code."))
  7346. return 'fail'
  7347. else:
  7348. try:
  7349. file = StringIO(obj.source_file)
  7350. except AttributeError:
  7351. self.inform.emit('[WARNING_NOTCL] %s' %
  7352. _("There is no selected object for which to see it's source file code."))
  7353. return 'fail'
  7354. self.ui.cncjob_frame.hide()
  7355. try:
  7356. for line in file:
  7357. QtWidgets.QApplication.processEvents()
  7358. proc_line = str(line).strip('\n')
  7359. self.ui.code_editor.append(proc_line)
  7360. except Exception as e:
  7361. log.debug('App.on_view_source() -->%s' % str(e))
  7362. self.inform.emit('[ERROR] %s: %s' %
  7363. (_('Failed to load the source code for the selected object'), str(e)))
  7364. return
  7365. self.handleTextChanged()
  7366. self.ui.cncjob_frame.show()
  7367. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7368. self.proc_container.view.set_idle()
  7369. # self.ui.show()
  7370. def on_toggle_code_editor(self):
  7371. self.report_usage("on_toggle_code_editor()")
  7372. if self.toggle_codeeditor is False:
  7373. self.init_code_editor(name=_("Code Editor"))
  7374. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  7375. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  7376. else:
  7377. for idx in range(self.ui.plot_tab_area.count()):
  7378. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  7379. self.ui.plot_tab_area.closeTab(idx)
  7380. break
  7381. self.toggle_codeeditor = False
  7382. def on_filenewscript(self, silent=False):
  7383. """
  7384. Will create a new script file and open it in the Code Editor
  7385. :param silent: if True will not display status messages
  7386. :return: None
  7387. """
  7388. if silent is False:
  7389. self.inform.emit('[success] %s' %
  7390. _("New TCL script file created in Code Editor."))
  7391. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  7392. self.init_code_editor(name=_("Script Editor"))
  7393. self.ui.code_editor.completer_enable = True
  7394. self.ui.code_editor.append(_(
  7395. "#\n"
  7396. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  7397. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  7398. "#\n\n"
  7399. "# FlatCAM commands list:\n"
  7400. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, ClearCopper,\n"
  7401. "# Cncjob, Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, GetNames,\n"
  7402. "# GetSys, ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillDrills,\n"
  7403. "# MillSlots, Mirror, New, NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"
  7404. "# Options, Paint, Panelize, Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, SubtractPoly,\n"
  7405. "# SubtractRectangle, Version, WriteGCode\n"
  7406. "#\n\n"
  7407. ))
  7408. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  7409. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  7410. self.ui.buttonRun.show()
  7411. try:
  7412. self.ui.buttonRun.clicked.disconnect(self.handleRunCode)
  7413. except TypeError:
  7414. pass
  7415. self.ui.buttonRun.clicked.connect(self.handleRunCode)
  7416. self.handleTextChanged()
  7417. self.ui.code_editor.show()
  7418. def on_fileopenscript(self, name=None, silent=False):
  7419. """
  7420. Will open a Tcl script file into the Code Editor
  7421. :param silent: if True will not display status messages
  7422. :param name: name of a Tcl script file to open
  7423. :return:
  7424. """
  7425. if name:
  7426. filename = name
  7427. else:
  7428. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7429. try:
  7430. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  7431. directory=self.get_last_folder(), filter=_filter_)
  7432. except TypeError:
  7433. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  7434. # The Qt methods above will return a QString which can cause problems later.
  7435. # So far json.dump() will fail to serialize it.
  7436. # TODO: Improve the serialization methods and remove this fix.
  7437. filename = str(filename)
  7438. if filename == "":
  7439. if silent is False:
  7440. self.inform.emit('[WARNING_NOTCL] %s' %
  7441. _("Open TCL script cancelled."))
  7442. else:
  7443. self.on_filenewscript()
  7444. try:
  7445. with open(filename, "r") as opened_script:
  7446. try:
  7447. for line in opened_script:
  7448. proc_line = str(line).strip('\n')
  7449. self.ui.code_editor.append(proc_line)
  7450. except Exception as e:
  7451. log.debug('App.on_fileopenscript() -->%s' % str(e))
  7452. if silent is False:
  7453. self.inform.emit('[ERROR] %s %s' %
  7454. (_('App.on_fileopenscript() -->'), str(e)))
  7455. return
  7456. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7457. self.handleTextChanged()
  7458. if silent is False:
  7459. self.inform.emit('[success] %s' %
  7460. _("TCL script file opened in Code Editor."))
  7461. # self.ui.show()
  7462. except Exception as e:
  7463. log.debug("App.on_fileopenscript() -> %s" % str(e))
  7464. def on_filerunscript(self, name=None, silent=False):
  7465. """
  7466. File menu callback for loading and running a TCL script.
  7467. :param silent: if True will not display status messages
  7468. :param name: name of a Tcl script file to be run by FlatCAM
  7469. :return: None
  7470. """
  7471. self.report_usage("on_filerunscript")
  7472. App.log.debug("on_file_runscript()")
  7473. if name:
  7474. filename = name
  7475. if self.cmd_line_headless != 1:
  7476. self.splash.showMessage('%s: %ssec\n%s' %
  7477. (_("Canvas initialization started.\n"
  7478. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7479. _("Executing FlatCAMScript file.")
  7480. ),
  7481. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7482. color=QtGui.QColor("gray"))
  7483. else:
  7484. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7485. try:
  7486. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  7487. directory=self.get_last_folder(), filter=_filter_)
  7488. except TypeError:
  7489. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  7490. # The Qt methods above will return a QString which can cause problems later.
  7491. # So far json.dump() will fail to serialize it.
  7492. # TODO: Improve the serialization methods and remove this fix.
  7493. filename = str(filename)
  7494. if filename == "":
  7495. if silent is False:
  7496. self.inform.emit('[WARNING_NOTCL] %s' %
  7497. _("Run TCL script cancelled."))
  7498. else:
  7499. if self.cmd_line_headless != 1:
  7500. if self.ui.shell_dock.isHidden():
  7501. self.ui.shell_dock.show()
  7502. try:
  7503. with open(filename, "r") as tcl_script:
  7504. cmd_line_shellfile_content = tcl_script.read()
  7505. if self.cmd_line_headless != 1:
  7506. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  7507. else:
  7508. self.shell._sysShell.exec_command(cmd_line_shellfile_content, no_echo=True)
  7509. if silent is False:
  7510. self.inform.emit('[success] %s' %
  7511. _("TCL script file opened in Code Editor and executed."))
  7512. except Exception as e:
  7513. log.debug("App.on_filerunscript() -> %s" % str(e))
  7514. sys.exit(2)
  7515. def on_file_saveproject(self, silent=False):
  7516. """
  7517. Callback for menu item File->Save Project. Saves the project to
  7518. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7519. if set to None. The project is saved by calling ``self.save_project()``.
  7520. :param silent: if True will not display status messages
  7521. :return: None
  7522. """
  7523. self.report_usage("on_file_saveproject")
  7524. if self.project_filename is None:
  7525. self.on_file_saveprojectas()
  7526. else:
  7527. self.worker_task.emit({'fcn': self.save_project,
  7528. 'params': [self.project_filename, silent]})
  7529. if self.defaults["global_open_style"] is False:
  7530. self.file_opened.emit("project", self.project_filename)
  7531. self.file_saved.emit("project", self.project_filename)
  7532. self.set_ui_title(name=self.project_filename)
  7533. self.should_we_save = False
  7534. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7535. """
  7536. Callback for menu item File->Save Project As... Opens a file
  7537. chooser and saves the project to the given file via
  7538. ``self.save_project()``.
  7539. :param make_copy if to be create a copy of the project; boolean
  7540. :param use_thread: if to be run in a separate thread; boolean
  7541. :param quit_action: if to be followed by quiting the application; boolean
  7542. :return: None
  7543. """
  7544. self.report_usage("on_file_saveprojectas")
  7545. self.date = str(datetime.today()).rpartition('.')[0]
  7546. self.date = ''.join(c for c in self.date if c not in ':-')
  7547. self.date = self.date.replace(' ', '_')
  7548. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  7549. try:
  7550. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7551. caption=_("Save Project As ..."),
  7552. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  7553. filter=filter_)
  7554. except TypeError:
  7555. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  7556. filename = str(filename)
  7557. if filename == '':
  7558. self.inform.emit('[WARNING_NOTCL] %s' %
  7559. _("Save Project cancelled."))
  7560. return
  7561. try:
  7562. f = open(filename, 'r')
  7563. f.close()
  7564. except IOError:
  7565. pass
  7566. if use_thread is True:
  7567. self.worker_task.emit({'fcn': self.save_project,
  7568. 'params': [filename, quit_action]})
  7569. else:
  7570. self.save_project(filename, quit_action)
  7571. # self.save_project(filename)
  7572. if self.defaults["global_open_style"] is False:
  7573. self.file_opened.emit("project", filename)
  7574. self.file_saved.emit("project", filename)
  7575. if not make_copy:
  7576. self.project_filename = filename
  7577. self.set_ui_title(name=self.project_filename)
  7578. self.should_we_save = False
  7579. def export_svg(self, obj_name, filename, scale_factor=0.00):
  7580. """
  7581. Exports a Geometry Object to an SVG file.
  7582. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7583. :param filename: Path to the SVG file to save to.
  7584. :param scale_factor: factor by which to change/scale the thickness of the features
  7585. :return:
  7586. """
  7587. self.report_usage("export_svg()")
  7588. if filename is None:
  7589. filename = self.defaults["global_last_save_folder"]
  7590. self.log.debug("export_svg()")
  7591. try:
  7592. obj = self.collection.get_by_name(str(obj_name))
  7593. except:
  7594. # TODO: The return behavior has not been established... should raise exception?
  7595. return "Could not retrieve object: %s" % obj_name
  7596. with self.proc_container.new(_("Exporting SVG")) as proc:
  7597. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7598. # Determine bounding area for svg export
  7599. bounds = obj.bounds()
  7600. size = obj.size()
  7601. # Convert everything to strings for use in the xml doc
  7602. svgwidth = str(size[0])
  7603. svgheight = str(size[1])
  7604. minx = str(bounds[0])
  7605. miny = str(bounds[1] - size[1])
  7606. uom = obj.units.lower()
  7607. # Add a SVG Header and footer to the svg output from shapely
  7608. # The transform flips the Y Axis so that everything renders
  7609. # properly within svg apps such as inkscape
  7610. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7611. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7612. svg_header += 'width="' + svgwidth + uom + '" '
  7613. svg_header += 'height="' + svgheight + uom + '" '
  7614. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7615. svg_header += '<g transform="scale(1,-1)">'
  7616. svg_footer = '</g> </svg>'
  7617. svg_elem = svg_header + exported_svg + svg_footer
  7618. # Parse the xml through a xml parser just to add line feeds
  7619. # and to make it look more pretty for the output
  7620. svgcode = parse_xml_string(svg_elem)
  7621. try:
  7622. with open(filename, 'w') as fp:
  7623. fp.write(svgcode.toprettyxml())
  7624. except PermissionError:
  7625. self.inform.emit('[WARNING] %s' %
  7626. _("Permission denied, saving not possible.\n"
  7627. "Most likely another app is holding the file open and not accessible."))
  7628. return 'fail'
  7629. if self.defaults["global_open_style"] is False:
  7630. self.file_opened.emit("SVG", filename)
  7631. self.file_saved.emit("SVG", filename)
  7632. self.inform.emit('[success] %s: %s' %
  7633. (_("SVG file exported to"), filename))
  7634. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  7635. """
  7636. Exports a Geometry Object to an SVG file in negative.
  7637. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7638. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  7639. :param filename: Path to the SVG file to save to.
  7640. :param boundary: thickness of a black border to surround all the features
  7641. :param scale_factor: factor by which to change/scale the thickness of the features
  7642. :param use_thread: if to be run in a separate thread; boolean
  7643. :return:
  7644. """
  7645. self.report_usage("export_negative()")
  7646. if filename is None:
  7647. filename = self.defaults["global_last_save_folder"]
  7648. self.log.debug("export_svg() negative")
  7649. try:
  7650. obj = self.collection.get_by_name(str(obj_name))
  7651. except:
  7652. # TODO: The return behavior has not been established... should raise exception?
  7653. return "Could not retrieve object: %s" % obj_name
  7654. try:
  7655. box = self.collection.get_by_name(str(box_name))
  7656. except:
  7657. # TODO: The return behavior has not been established... should raise exception?
  7658. return "Could not retrieve object: %s" % box_name
  7659. if box is None:
  7660. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  7661. (_("No object Box. Using instead"), obj))
  7662. box = obj
  7663. def make_negative_film():
  7664. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7665. # Determine bounding area for svg export
  7666. bounds = box.bounds()
  7667. size = box.size()
  7668. uom = obj.units.lower()
  7669. # Convert everything to strings for use in the xml doc
  7670. svgwidth = str(size[0] + (2 * boundary))
  7671. svgheight = str(size[1] + (2 * boundary))
  7672. minx = str(bounds[0] - boundary)
  7673. miny = str(bounds[1] + boundary + size[1])
  7674. miny_rect = str(bounds[1] - boundary)
  7675. # Add a SVG Header and footer to the svg output from shapely
  7676. # The transform flips the Y Axis so that everything renders
  7677. # properly within svg apps such as inkscape
  7678. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7679. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7680. svg_header += 'width="' + svgwidth + uom + '" '
  7681. svg_header += 'height="' + svgheight + uom + '" '
  7682. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7683. svg_header += '>'
  7684. svg_header += '<g transform="scale(1,-1)">'
  7685. svg_footer = '</g> </svg>'
  7686. # Change the attributes of the exported SVG
  7687. # We don't need stroke-width - wrong, we do when we have lines with certain width
  7688. # We set opacity to maximum
  7689. # We set the color to WHITE
  7690. root = ET.fromstring(exported_svg)
  7691. for child in root:
  7692. child.set('fill', '#FFFFFF')
  7693. child.set('opacity', '1.0')
  7694. child.set('stroke', '#FFFFFF')
  7695. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  7696. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  7697. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  7698. first_svg_elem_tag = 'rect'
  7699. first_svg_elem_attribs = {
  7700. 'x': minx,
  7701. 'y': miny_rect,
  7702. 'width': svgwidth,
  7703. 'height': svgheight,
  7704. 'id': 'neg_rect',
  7705. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  7706. }
  7707. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  7708. exported_svg = ET.tostring(root)
  7709. svg_elem = svg_header + str(exported_svg) + svg_footer
  7710. # Parse the xml through a xml parser just to add line feeds
  7711. # and to make it look more pretty for the output
  7712. doc = parse_xml_string(svg_elem)
  7713. try:
  7714. with open(filename, 'w') as fp:
  7715. fp.write(doc.toprettyxml())
  7716. except PermissionError:
  7717. self.inform.emit('[WARNING] %s' %
  7718. _("Permission denied, saving not possible.\n"
  7719. "Most likely another app is holding the file open and not accessible."))
  7720. return 'fail'
  7721. if self.defaults["global_open_style"] is False:
  7722. self.file_opened.emit("SVG", filename)
  7723. self.file_saved.emit("SVG", filename)
  7724. self.inform.emit('[success] %s: %s' %
  7725. (_("SVG file exported to"), filename))
  7726. if use_thread is True:
  7727. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  7728. def job_thread_film(app_obj):
  7729. try:
  7730. make_negative_film()
  7731. except Exception as e:
  7732. proc.done()
  7733. return
  7734. proc.done()
  7735. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  7736. else:
  7737. make_negative_film()
  7738. def export_svg_positive(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  7739. """
  7740. Exports a Geometry Object to an SVG file in positive black.
  7741. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7742. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  7743. :param filename: Path to the SVG file to save to.
  7744. :param scale_factor: factor by which to change/scale the thickness of the features
  7745. :param use_thread: if to be run in a separate thread; boolean
  7746. :return:
  7747. """
  7748. self.report_usage("export_svg_positive()")
  7749. if filename is None:
  7750. filename = self.defaults["global_last_save_folder"]
  7751. self.log.debug("export_svg() black")
  7752. try:
  7753. obj = self.collection.get_by_name(str(obj_name))
  7754. except:
  7755. # TODO: The return behavior has not been established... should raise exception?
  7756. return "Could not retrieve object: %s" % obj_name
  7757. try:
  7758. box = self.collection.get_by_name(str(box_name))
  7759. except:
  7760. # TODO: The return behavior has not been established... should raise exception?
  7761. return "Could not retrieve object: %s" % box_name
  7762. if box is None:
  7763. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  7764. (_("No object Box. Using instead"), obj))
  7765. box = obj
  7766. def make_positive_film():
  7767. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7768. self.progress.emit(40)
  7769. # Change the attributes of the exported SVG
  7770. # We don't need stroke-width
  7771. # We set opacity to maximum
  7772. # We set the colour to WHITE
  7773. root = ET.fromstring(exported_svg)
  7774. for child in root:
  7775. child.set('fill', str(self.defaults['tools_film_color']))
  7776. child.set('opacity', '1.0')
  7777. child.set('stroke', str(self.defaults['tools_film_color']))
  7778. exported_svg = ET.tostring(root)
  7779. # Determine bounding area for svg export
  7780. bounds = box.bounds()
  7781. size = box.size()
  7782. # This contain the measure units
  7783. uom = obj.units.lower()
  7784. # Define a boundary around SVG of about 1.0mm (~39mils)
  7785. if uom in "mm":
  7786. boundary = 1.0
  7787. else:
  7788. boundary = 0.0393701
  7789. self.progress.emit(80)
  7790. # Convert everything to strings for use in the xml doc
  7791. svgwidth = str(size[0] + (2 * boundary))
  7792. svgheight = str(size[1] + (2 * boundary))
  7793. minx = str(bounds[0] - boundary)
  7794. miny = str(bounds[1] + boundary + size[1])
  7795. self.log.debug(minx)
  7796. self.log.debug(miny)
  7797. # Add a SVG Header and footer to the svg output from shapely
  7798. # The transform flips the Y Axis so that everything renders
  7799. # properly within svg apps such as inkscape
  7800. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7801. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7802. svg_header += 'width="' + svgwidth + uom + '" '
  7803. svg_header += 'height="' + svgheight + uom + '" '
  7804. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7805. svg_header += '>'
  7806. svg_header += '<g transform="scale(1,-1)">'
  7807. svg_footer = '</g> </svg>'
  7808. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  7809. self.progress.emit(90)
  7810. # Parse the xml through a xml parser just to add line feeds
  7811. # and to make it look more pretty for the output
  7812. doc = parse_xml_string(svg_elem)
  7813. try:
  7814. with open(filename, 'w') as fp:
  7815. fp.write(doc.toprettyxml())
  7816. except PermissionError:
  7817. self.inform.emit('[WARNING] %s' %
  7818. _("Permission denied, saving not possible.\n"
  7819. "Most likely another app is holding the file open and not accessible."))
  7820. return 'fail'
  7821. self.progress.emit(100)
  7822. if self.defaults["global_open_style"] is False:
  7823. self.file_opened.emit("SVG", filename)
  7824. self.file_saved.emit("SVG", filename)
  7825. self.inform.emit('[success] %s: %s' %
  7826. (_("SVG file exported to"), filename))
  7827. if use_thread is True:
  7828. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  7829. def job_thread_film(app_obj):
  7830. try:
  7831. make_positive_film()
  7832. except Exception as e:
  7833. proc.done()
  7834. return
  7835. proc.done()
  7836. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  7837. else:
  7838. make_positive_film()
  7839. def save_source_file(self, obj_name, filename, use_thread=True):
  7840. """
  7841. Exports a FlatCAM Object to an Gerber/Excellon file.
  7842. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7843. :param filename: Path to the Gerber file to save to.
  7844. :param use_thread: if to be run in a separate thread
  7845. :return:
  7846. """
  7847. self.report_usage("save source file()")
  7848. if filename is None:
  7849. filename = self.defaults["global_last_save_folder"]
  7850. self.log.debug("save source file()")
  7851. obj = self.collection.get_by_name(obj_name)
  7852. file_string = StringIO(obj.source_file)
  7853. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7854. try:
  7855. with open(filename, 'w') as file:
  7856. file.writelines('G04*\n')
  7857. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7858. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7859. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7860. file.writelines('G04 Created on : %s*\n' % time_string)
  7861. for line in file_string:
  7862. file.writelines(line)
  7863. except PermissionError:
  7864. self.inform.emit('[WARNING] %s' %
  7865. _("Permission denied, saving not possible.\n"
  7866. "Most likely another app is holding the file open and not accessible."))
  7867. return 'fail'
  7868. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7869. """
  7870. Exports a Excellon Object to an Excellon file.
  7871. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7872. :param filename: Path to the Excellon file to save to.
  7873. :param use_thread: if to be run in a separate thread
  7874. :return:
  7875. """
  7876. self.report_usage("export_excellon()")
  7877. if filename is None:
  7878. filename = self.defaults["global_last_save_folder"]
  7879. self.log.debug("export_excellon()")
  7880. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7881. self.defaults["excellon_exp_decimals"]
  7882. )
  7883. units = ''
  7884. if local_use is None:
  7885. try:
  7886. obj = self.collection.get_by_name(str(obj_name))
  7887. except:
  7888. # TODO: The return behavior has not been established... should raise exception?
  7889. return "Could not retrieve object: %s" % obj_name
  7890. else:
  7891. obj = local_use
  7892. # updated units
  7893. eunits = self.defaults["excellon_exp_units"]
  7894. ewhole = self.defaults["excellon_exp_integer"]
  7895. efract = self.defaults["excellon_exp_decimals"]
  7896. ezeros = self.defaults["excellon_exp_zeros"]
  7897. eformat = self.defaults["excellon_exp_format"]
  7898. slot_type = self.defaults["excellon_exp_slot_type"]
  7899. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7900. if fc_units == 'MM':
  7901. factor = 1 if eunits == 'METRIC' else 0.03937
  7902. else:
  7903. factor = 25.4 if eunits == 'METRIC' else 1
  7904. def make_excellon():
  7905. try:
  7906. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7907. header = 'M48\n'
  7908. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7909. (str(self.version), str(self.version_date))
  7910. header += ';Filename: %s' % str(obj_name) + '\n'
  7911. header += ';Created on : %s' % time_str + '\n'
  7912. if eformat == 'dec':
  7913. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7914. header += eunits + '\n'
  7915. for tool in obj.tools:
  7916. if eunits == 'METRIC':
  7917. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7918. tool=str(tool),
  7919. dec=2)
  7920. else:
  7921. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7922. tool=str(tool),
  7923. dec=4)
  7924. else:
  7925. if ezeros == 'LZ':
  7926. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7927. form='ndec', e_zeros='LZ', factor=factor,
  7928. slot_type=slot_type)
  7929. header += '%s,%s\n' % (eunits, 'LZ')
  7930. header += format_exc
  7931. for tool in obj.tools:
  7932. if eunits == 'METRIC':
  7933. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7934. tool=str(tool),
  7935. dec=2)
  7936. else:
  7937. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7938. tool=str(tool),
  7939. dec=4)
  7940. else:
  7941. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7942. form='ndec', e_zeros='TZ', factor=factor,
  7943. slot_type=slot_type)
  7944. header += '%s,%s\n' % (eunits, 'TZ')
  7945. header += format_exc
  7946. for tool in obj.tools:
  7947. if eunits == 'METRIC':
  7948. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7949. tool=str(tool),
  7950. dec=2)
  7951. else:
  7952. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7953. tool=str(tool),
  7954. dec=4)
  7955. header += '%\n'
  7956. footer = 'M30\n'
  7957. exported_excellon = header
  7958. exported_excellon += excellon_code
  7959. exported_excellon += footer
  7960. if local_use is None:
  7961. try:
  7962. with open(filename, 'w') as fp:
  7963. fp.write(exported_excellon)
  7964. except PermissionError:
  7965. self.inform.emit('[WARNING] %s' %
  7966. _("Permission denied, saving not possible.\n"
  7967. "Most likely another app is holding the file open and not accessible."))
  7968. return 'fail'
  7969. if self.defaults["global_open_style"] is False:
  7970. self.file_opened.emit("Excellon", filename)
  7971. self.file_saved.emit("Excellon", filename)
  7972. self.inform.emit('[success] %s: %s' %
  7973. (_("Excellon file exported to"), filename))
  7974. else:
  7975. return exported_excellon
  7976. except Exception as e:
  7977. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7978. return 'fail'
  7979. if use_thread is True:
  7980. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7981. def job_thread_exc(app_obj):
  7982. ret = make_excellon()
  7983. if ret == 'fail':
  7984. self.inform.emit('[ERROR_NOTCL] %s' %
  7985. _('Could not export Excellon file.'))
  7986. return
  7987. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7988. else:
  7989. ret = make_excellon()
  7990. if ret == 'fail':
  7991. self.inform.emit('[ERROR_NOTCL] %s' %
  7992. _('Could not export Excellon file.'))
  7993. return 'fail'
  7994. if local_use is not None:
  7995. return ret
  7996. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7997. """
  7998. Exports a Gerber Object to an Gerber file.
  7999. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  8000. :param filename: Path to the Gerber file to save to.
  8001. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8002. When not None, the value will be the actual Gerber object for which to create the Gerber code
  8003. :param use_thread: if to be run in a separate thread
  8004. :return:
  8005. """
  8006. self.report_usage("export_gerber()")
  8007. if filename is None:
  8008. filename = self.defaults["global_last_save_folder"]
  8009. self.log.debug("export_gerber()")
  8010. if local_use is None:
  8011. try:
  8012. obj = self.collection.get_by_name(str(obj_name))
  8013. except:
  8014. # TODO: The return behavior has not been established... should raise exception?
  8015. return "Could not retrieve object: %s" % obj_name
  8016. else:
  8017. obj = local_use
  8018. # updated units
  8019. gunits = self.defaults["gerber_exp_units"]
  8020. gwhole = self.defaults["gerber_exp_integer"]
  8021. gfract = self.defaults["gerber_exp_decimals"]
  8022. gzeros = self.defaults["gerber_exp_zeros"]
  8023. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8024. if fc_units == 'MM':
  8025. factor = 1 if gunits == 'MM' else 0.03937
  8026. else:
  8027. factor = 25.4 if gunits == 'MM' else 1
  8028. def make_gerber():
  8029. try:
  8030. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8031. header = 'G04*\n'
  8032. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  8033. (str(self.version), str(self.version_date))
  8034. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  8035. header += 'G04 Created on : %s*' % time_str + '\n'
  8036. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  8037. header += "%MO{units}*%\n".format(units=gunits)
  8038. for apid in obj.apertures:
  8039. if obj.apertures[apid]['type'] == 'C':
  8040. header += "%ADD{apid}{type},{size}*%\n".format(
  8041. apid=str(apid),
  8042. type='C',
  8043. size=(factor * obj.apertures[apid]['size'])
  8044. )
  8045. elif obj.apertures[apid]['type'] == 'R':
  8046. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8047. apid=str(apid),
  8048. type='R',
  8049. width=(factor * obj.apertures[apid]['width']),
  8050. height=(factor * obj.apertures[apid]['height'])
  8051. )
  8052. elif obj.apertures[apid]['type'] == 'O':
  8053. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8054. apid=str(apid),
  8055. type='O',
  8056. width=(factor * obj.apertures[apid]['width']),
  8057. height=(factor * obj.apertures[apid]['height'])
  8058. )
  8059. header += '\n'
  8060. # obsolete units but some software may need it
  8061. if gunits == 'IN':
  8062. header += 'G70*\n'
  8063. else:
  8064. header += 'G71*\n'
  8065. # Absolute Mode
  8066. header += 'G90*\n'
  8067. header += 'G01*\n'
  8068. # positive polarity
  8069. header += '%LPD*%\n'
  8070. footer = 'M02*\n'
  8071. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8072. exported_gerber = header
  8073. exported_gerber += gerber_code
  8074. exported_gerber += footer
  8075. if local_use is None:
  8076. try:
  8077. with open(filename, 'w') as fp:
  8078. fp.write(exported_gerber)
  8079. except PermissionError:
  8080. self.inform.emit('[WARNING] %s' %
  8081. _("Permission denied, saving not possible.\n"
  8082. "Most likely another app is holding the file open and not accessible."))
  8083. return 'fail'
  8084. if self.defaults["global_open_style"] is False:
  8085. self.file_opened.emit("Gerber", filename)
  8086. self.file_saved.emit("Gerber", filename)
  8087. self.inform.emit('[success] %s: %s' %
  8088. (_("Gerber file exported to"), filename))
  8089. else:
  8090. return exported_gerber
  8091. except Exception as e:
  8092. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8093. return 'fail'
  8094. if use_thread is True:
  8095. with self.proc_container.new(_("Exporting Gerber")) as proc:
  8096. def job_thread_grb(app_obj):
  8097. ret = make_gerber()
  8098. if ret == 'fail':
  8099. self.inform.emit('[ERROR_NOTCL] %s' %
  8100. _('Could not export Gerber file.'))
  8101. return
  8102. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8103. else:
  8104. ret = make_gerber()
  8105. if ret == 'fail':
  8106. self.inform.emit('[ERROR_NOTCL] %s' %
  8107. _('Could not export Gerber file.'))
  8108. return 'fail'
  8109. if local_use is not None:
  8110. return ret
  8111. def export_dxf(self, obj_name, filename, use_thread=True):
  8112. """
  8113. Exports a Geometry Object to an DXF file.
  8114. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8115. :param filename: Path to the DXF file to save to.
  8116. :param use_thread: if to be run in a separate thread
  8117. :return:
  8118. """
  8119. self.report_usage("export_dxf()")
  8120. if filename is None:
  8121. filename = self.defaults["global_last_save_folder"]
  8122. self.log.debug("export_dxf()")
  8123. format_exc = ''
  8124. units = ''
  8125. try:
  8126. obj = self.collection.get_by_name(str(obj_name))
  8127. except:
  8128. # TODO: The return behavior has not been established... should raise exception?
  8129. return "Could not retrieve object: %s" % obj_name
  8130. # updated units
  8131. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8132. if units == 'IN' or units == 'INCH':
  8133. units = 'INCH'
  8134. elif units == 'MM' or units == 'METIRC':
  8135. units ='METRIC'
  8136. def make_dxf():
  8137. try:
  8138. dxf_code = obj.export_dxf()
  8139. dxf_code.saveas(filename)
  8140. if self.defaults["global_open_style"] is False:
  8141. self.file_opened.emit("DXF", filename)
  8142. self.file_saved.emit("DXF", filename)
  8143. self.inform.emit('[success] %s: %s' %
  8144. (_("DXF file exported to"), filename))
  8145. except:
  8146. return 'fail'
  8147. if use_thread is True:
  8148. with self.proc_container.new(_("Exporting DXF")) as proc:
  8149. def job_thread_exc(app_obj):
  8150. ret = make_dxf()
  8151. if ret == 'fail':
  8152. app_obj.inform.emit('[WARNING_NOTCL] %s' %
  8153. _('Could not export DXF file.'))
  8154. return
  8155. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8156. else:
  8157. ret = make_dxf()
  8158. if ret == 'fail':
  8159. self.inform.emit('[WARNING_NOTCL] %s' %
  8160. _('Could not export DXF file.'))
  8161. return
  8162. def import_svg(self, filename, geo_type='geometry', outname=None):
  8163. """
  8164. Adds a new Geometry Object to the projects and populates
  8165. it with shapes extracted from the SVG file.
  8166. :param filename: Path to the SVG file.
  8167. :param outname:
  8168. :return:
  8169. """
  8170. self.report_usage("import_svg()")
  8171. obj_type = ""
  8172. if geo_type is None or geo_type == "geometry":
  8173. obj_type = "geometry"
  8174. elif geo_type == "gerber":
  8175. obj_type = geo_type
  8176. else:
  8177. self.inform.emit('[ERROR_NOTCL] %s' %
  8178. _("Not supported type is picked as parameter. "
  8179. "Only Geometry and Gerber are supported"))
  8180. return
  8181. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8182. def obj_init(geo_obj, app_obj):
  8183. geo_obj.import_svg(filename, obj_type, units=units)
  8184. geo_obj.multigeo = False
  8185. with self.proc_container.new(_("Importing SVG")) as proc:
  8186. # Object name
  8187. name = outname or filename.split('/')[-1].split('\\')[-1]
  8188. self.new_object(obj_type, name, obj_init, autoselected=False)
  8189. self.progress.emit(20)
  8190. # Register recent file
  8191. self.file_opened.emit("svg", filename)
  8192. # GUI feedback
  8193. self.inform.emit('[success] %s: %s' %
  8194. (_("Opened"), filename))
  8195. self.progress.emit(100)
  8196. def import_dxf(self, filename, geo_type='geometry', outname=None):
  8197. """
  8198. Adds a new Geometry Object to the projects and populates
  8199. it with shapes extracted from the DXF file.
  8200. :param filename: Path to the DXF file.
  8201. :param outname:
  8202. :type putname: str
  8203. :return:
  8204. """
  8205. self.report_usage("import_dxf()")
  8206. obj_type = ""
  8207. if geo_type is None or geo_type == "geometry":
  8208. obj_type = "geometry"
  8209. elif geo_type == "gerber":
  8210. obj_type = geo_type
  8211. else:
  8212. self.inform.emit('[ERROR_NOTCL] %s' %
  8213. _("Not supported type is picked as parameter. "
  8214. "Only Geometry and Gerber are supported"))
  8215. return
  8216. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8217. def obj_init(geo_obj, app_obj):
  8218. geo_obj.import_dxf(filename, obj_type, units=units)
  8219. geo_obj.multigeo = False
  8220. with self.proc_container.new(_("Importing DXF")) as proc:
  8221. # Object name
  8222. name = outname or filename.split('/')[-1].split('\\')[-1]
  8223. self.new_object(obj_type, name, obj_init, autoselected=False)
  8224. self.progress.emit(20)
  8225. # Register recent file
  8226. self.file_opened.emit("dxf", filename)
  8227. # GUI feedback
  8228. self.inform.emit('[success] %s: %s' %
  8229. (_("Opened"), filename))
  8230. self.progress.emit(100)
  8231. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  8232. """
  8233. Adds a new Geometry Object to the projects and populates
  8234. it with shapes extracted from the SVG file.
  8235. :param filename: Path to the SVG file.
  8236. :param o_type: type of FlatCAM objeect
  8237. :param dpi: dot per inch
  8238. :param mode: black or color
  8239. :param mask: dictate the level of detail
  8240. :param outname: name for the resulting file
  8241. :return:
  8242. """
  8243. self.report_usage("import_image()")
  8244. if o_type is None or o_type == "geometry":
  8245. obj_type = "geometry"
  8246. elif o_type == "gerber":
  8247. obj_type = o_type
  8248. else:
  8249. self.inform.emit('[ERROR_NOTCL] %s' %
  8250. _("Not supported type is picked as parameter. "
  8251. "Only Geometry and Gerber are supported"))
  8252. return
  8253. def obj_init(geo_obj, app_obj):
  8254. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  8255. geo_obj.multigeo = False
  8256. with self.proc_container.new(_("Importing Image")) as proc:
  8257. # Object name
  8258. name = outname or filename.split('/')[-1].split('\\')[-1]
  8259. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  8260. self.new_object(obj_type, name, obj_init)
  8261. self.progress.emit(20)
  8262. # Register recent file
  8263. self.file_opened.emit("image", filename)
  8264. # GUI feedback
  8265. self.inform.emit('[success] %s: %s' %
  8266. (_("Opened"), filename))
  8267. self.progress.emit(100)
  8268. def open_gerber(self, filename, outname=None):
  8269. """
  8270. Opens a Gerber file, parses it and creates a new object for
  8271. it in the program. Thread-safe.
  8272. :param outname: Name of the resulting object. None causes the
  8273. name to be that of the file.
  8274. :param filename: Gerber file filename
  8275. :type filename: str
  8276. :param follow: If true, the parser will not create polygons, just lines
  8277. following the gerber path.
  8278. :type follow: bool
  8279. :return: None
  8280. """
  8281. # How the object should be initialized
  8282. def obj_init(gerber_obj, app_obj):
  8283. assert isinstance(gerber_obj, FlatCAMGerber), \
  8284. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  8285. # Opening the file happens here
  8286. self.progress.emit(30)
  8287. try:
  8288. gerber_obj.parse_file(filename)
  8289. except IOError:
  8290. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8291. (_("Failed to open file"), filename))
  8292. app_obj.progress.emit(0)
  8293. return "fail"
  8294. except ParseError as err:
  8295. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' %
  8296. (_("Failed to parse file"), filename, str(err)))
  8297. app_obj.progress.emit(0)
  8298. self.log.error(str(err))
  8299. return "fail"
  8300. except Exception as e:
  8301. log.debug("App.open_gerber() --> %s" % str(e))
  8302. msg = '[ERROR] %s' % \
  8303. _("An internal error has occurred. See shell.\n")
  8304. msg += traceback.format_exc()
  8305. app_obj.inform.emit(msg)
  8306. return "fail"
  8307. if gerber_obj.is_empty():
  8308. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  8309. # self.collection.set_active(gerber_obj.options["name"])
  8310. # self.collection.delete_active()
  8311. self.inform.emit('[ERROR_NOTCL] %s' %
  8312. _("Object is not Gerber file or empty. Aborting object creation."))
  8313. return "fail"
  8314. # Further parsing
  8315. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  8316. App.log.debug("open_gerber()")
  8317. with self.proc_container.new(_("Opening Gerber")) as proc:
  8318. self.progress.emit(10)
  8319. # Object name
  8320. name = outname or filename.split('/')[-1].split('\\')[-1]
  8321. # # ## Object creation # ##
  8322. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  8323. if ret == 'fail':
  8324. self.inform.emit('[ERROR_NOTCL]%s' %
  8325. _(' Open Gerber failed. Probable not a Gerber file.'))
  8326. return
  8327. # Register recent file
  8328. self.file_opened.emit("gerber", filename)
  8329. self.progress.emit(100)
  8330. # GUI feedback
  8331. self.inform.emit('[success] %s: %s' %
  8332. (_("Opened"), filename))
  8333. def open_excellon(self, filename, outname=None, plot=True):
  8334. """
  8335. Opens an Excellon file, parses it and creates a new object for
  8336. it in the program. Thread-safe.
  8337. :param outname: Name of the resulting object. None causes the
  8338. name to be that of the file.
  8339. :param filename: Excellon file filename
  8340. :type filename: str
  8341. :return: None
  8342. """
  8343. App.log.debug("open_excellon()")
  8344. # How the object should be initialized
  8345. def obj_init(excellon_obj, app_obj):
  8346. # self.progress.emit(20)
  8347. try:
  8348. ret = excellon_obj.parse_file(filename=filename)
  8349. if ret == "fail":
  8350. log.debug("Excellon parsing failed.")
  8351. self.inform.emit('[ERROR_NOTCL] %s' %
  8352. _("This is not Excellon file."))
  8353. return "fail"
  8354. except IOError:
  8355. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8356. (_("Cannot open file"), filename))
  8357. log.debug("Could not open Excellon object.")
  8358. self.progress.emit(0) # TODO: self and app_bjj mixed
  8359. return "fail"
  8360. except:
  8361. msg = '[ERROR_NOTCL] %s' % \
  8362. _("An internal error has occurred. See shell.\n")
  8363. msg += traceback.format_exc()
  8364. app_obj.inform.emit(msg)
  8365. return "fail"
  8366. ret = excellon_obj.create_geometry()
  8367. if ret == 'fail':
  8368. log.debug("Could not create geometry for Excellon object.")
  8369. return "fail"
  8370. for tool in excellon_obj.tools:
  8371. if excellon_obj.tools[tool]['solid_geometry']:
  8372. return
  8373. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8374. (_("No geometry found in file"), filename))
  8375. return "fail"
  8376. with self.proc_container.new(_("Opening Excellon.")):
  8377. # Object name
  8378. name = outname or filename.split('/')[-1].split('\\')[-1]
  8379. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8380. if ret_val == 'fail':
  8381. self.inform.emit('[ERROR_NOTCL] %s' %
  8382. _('Open Excellon file failed. Probable not an Excellon file.'))
  8383. return
  8384. # Register recent file
  8385. self.file_opened.emit("excellon", filename)
  8386. # GUI feedback
  8387. self.inform.emit('[success] %s: %s' %
  8388. (_("Opened"), filename))
  8389. def open_gcode(self, filename, outname=None, plot=True):
  8390. """
  8391. Opens a G-gcode file, parses it and creates a new object for
  8392. it in the program. Thread-safe.
  8393. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8394. :param filename: G-code file filename
  8395. :type filename: str
  8396. :return: None
  8397. """
  8398. App.log.debug("open_gcode()")
  8399. # How the object should be initialized
  8400. def obj_init(job_obj, app_obj_):
  8401. """
  8402. :param job_obj: the resulting object
  8403. :type app_obj_: App
  8404. """
  8405. assert isinstance(app_obj_, App), \
  8406. "Initializer expected App, got %s" % type(app_obj_)
  8407. self.progress.emit(10)
  8408. try:
  8409. f = open(filename)
  8410. gcode = f.read()
  8411. f.close()
  8412. except IOError:
  8413. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  8414. (_("Failed to open"), filename))
  8415. self.progress.emit(0)
  8416. return "fail"
  8417. job_obj.gcode = gcode
  8418. self.progress.emit(20)
  8419. ret = job_obj.gcode_parse()
  8420. if ret == "fail":
  8421. self.inform.emit('[ERROR_NOTCL] %s' %
  8422. _("This is not GCODE"))
  8423. return "fail"
  8424. self.progress.emit(60)
  8425. job_obj.create_geometry()
  8426. with self.proc_container.new(_("Opening G-Code.")):
  8427. # Object name
  8428. name = outname or filename.split('/')[-1].split('\\')[-1]
  8429. # New object creation and file processing
  8430. ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8431. if ret == 'fail':
  8432. self.inform.emit('[ERROR_NOTCL] %s' %
  8433. _("Failed to create CNCJob Object. Probable not a GCode file.\n "
  8434. "Attempting to create a FlatCAM CNCJob Object from "
  8435. "G-Code file failed during processing"))
  8436. return "fail"
  8437. # Register recent file
  8438. self.file_opened.emit("cncjob", filename)
  8439. # GUI feedback
  8440. self.inform.emit('[success] %s: %s' %
  8441. (_("Opened"), filename))
  8442. self.progress.emit(100)
  8443. def open_config_file(self, filename, run_from_arg=None):
  8444. """
  8445. Loads a config file from the specified file.
  8446. :param filename: Name of the file from which to load.
  8447. :type filename: str
  8448. :return: None
  8449. """
  8450. App.log.debug("Opening config file: " + filename)
  8451. if run_from_arg:
  8452. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8453. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8454. _("Opening FlatCAM Config file.")),
  8455. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8456. color=QtGui.QColor("gray"))
  8457. # add the tab if it was closed
  8458. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  8459. # first clear previous text in text editor (if any)
  8460. self.ui.code_editor.clear()
  8461. # Switch plot_area to CNCJob tab
  8462. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  8463. try:
  8464. if filename:
  8465. f = QtCore.QFile(filename)
  8466. if f.open(QtCore.QIODevice.ReadOnly):
  8467. stream = QtCore.QTextStream(f)
  8468. gcode_edited = stream.readAll()
  8469. self.ui.code_editor.setPlainText(gcode_edited)
  8470. f.close()
  8471. except IOError:
  8472. App.log.error("Failed to open config file: %s" % filename)
  8473. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8474. (_("Failed to open config file"), filename))
  8475. return
  8476. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  8477. """
  8478. Loads a project from the specified file.
  8479. 1) Loads and parses file
  8480. 2) Registers the file as recently opened.
  8481. 3) Calls on_file_new()
  8482. 4) Updates options
  8483. 5) Calls new_object() with the object's from_dict() as init method.
  8484. 6) Calls plot_all() if plot=True
  8485. :param filename: Name of the file from which to load.
  8486. :type filename: str
  8487. :param run_from_arg: True if run for arguments
  8488. :param plot: If True plot all objects in the project
  8489. :param cli: run from command line
  8490. :return: None
  8491. """
  8492. App.log.debug("Opening project: " + filename)
  8493. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8494. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8495. if cli is None:
  8496. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8497. if run_from_arg:
  8498. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8499. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8500. _("Opening FlatCAM Project file.")),
  8501. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8502. color=QtGui.QColor("gray"))
  8503. # Open and parse an uncompressed Project file
  8504. try:
  8505. f = open(filename, 'r')
  8506. except IOError:
  8507. App.log.error("Failed to open project file: %s" % filename)
  8508. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8509. (_("Failed to open project file"), filename))
  8510. return
  8511. try:
  8512. d = json.load(f, object_hook=dict2obj)
  8513. except Exception as e:
  8514. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8515. (filename, str(e)))
  8516. f.close()
  8517. # Open and parse a compressed Project file
  8518. try:
  8519. with lzma.open(filename) as f:
  8520. file_content = f.read().decode('utf-8')
  8521. d = json.loads(file_content, object_hook=dict2obj)
  8522. except Exception as e:
  8523. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8524. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8525. (_("Failed to open project file"), filename))
  8526. return
  8527. # Clear the current project
  8528. # # NOT THREAD SAFE # ##
  8529. if run_from_arg is True:
  8530. pass
  8531. elif cli is True:
  8532. self.delete_selection_shape()
  8533. else:
  8534. self.on_file_new()
  8535. # Project options
  8536. self.options.update(d['options'])
  8537. self.project_filename = filename
  8538. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8539. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8540. if cli is None:
  8541. self.set_screen_units(self.options["units"])
  8542. # Re create objects
  8543. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8544. for obj in d['objs']:
  8545. def obj_init(obj_inst, app_inst):
  8546. obj_inst.from_dict(obj)
  8547. App.log.debug("Recreating from opened project an %s object: %s" %
  8548. (obj['kind'].capitalize(), obj['options']['name']))
  8549. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8550. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8551. if cli is None:
  8552. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8553. obj['kind'].upper(),
  8554. obj['options']['name']
  8555. )
  8556. )
  8557. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  8558. self.inform.emit('[success] %s: %s' %
  8559. (_("Project loaded from"), filename))
  8560. self.should_we_save = False
  8561. self.file_opened.emit("project", filename)
  8562. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8563. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8564. if cli is None:
  8565. self.set_ui_title(name=self.project_filename)
  8566. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8567. def propagate_defaults(self, silent=False):
  8568. """
  8569. This method is used to set default values in classes. It's
  8570. an alternative to project options but allows the use
  8571. of values invisible to the user.
  8572. :return: None
  8573. """
  8574. if silent is False:
  8575. self.log.debug("propagate_defaults()")
  8576. # Which objects to update the given parameters.
  8577. routes = {
  8578. "global_zdownrate": CNCjob,
  8579. "excellon_zeros": Excellon,
  8580. "excellon_format_upper_in": Excellon,
  8581. "excellon_format_lower_in": Excellon,
  8582. "excellon_format_upper_mm": Excellon,
  8583. "excellon_format_lower_mm": Excellon,
  8584. "excellon_units": Excellon,
  8585. "gerber_use_buffer_for_union": Gerber,
  8586. "geometry_multidepth": Geometry
  8587. }
  8588. for param in routes:
  8589. if param in routes[param].defaults:
  8590. try:
  8591. routes[param].defaults[param] = self.defaults[param]
  8592. if silent is False:
  8593. self.log.debug(" " + param + " OK")
  8594. except KeyError:
  8595. if silent is False:
  8596. self.log.debug(" ERROR: " + param + " not in defaults.")
  8597. else:
  8598. # Try extracting the name:
  8599. # classname_param here is param in the object
  8600. if param.find(routes[param].__name__.lower() + "_") == 0:
  8601. p = param[len(routes[param].__name__) + 1:]
  8602. if p in routes[param].defaults:
  8603. routes[param].defaults[p] = self.defaults[param]
  8604. if silent is False:
  8605. self.log.debug(" " + param + " OK!")
  8606. def restore_main_win_geom(self):
  8607. try:
  8608. self.ui.setGeometry(self.defaults["global_def_win_x"],
  8609. self.defaults["global_def_win_y"],
  8610. self.defaults["global_def_win_w"],
  8611. self.defaults["global_def_win_h"])
  8612. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  8613. except KeyError as e:
  8614. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  8615. def plot_all(self, zoom=True):
  8616. """
  8617. Re-generates all plots from all objects.
  8618. :return: None
  8619. """
  8620. self.log.debug("Plot_all()")
  8621. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  8622. for obj in self.collection.get_list():
  8623. def worker_task(obj):
  8624. with self.proc_container.new("Plotting"):
  8625. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8626. if zoom:
  8627. self.object_plotted.emit(obj)
  8628. # Send to worker
  8629. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  8630. def register_folder(self, filename):
  8631. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8632. def register_save_folder(self, filename):
  8633. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8634. def set_progress_bar(self, percentage, text=""):
  8635. self.ui.progress_bar.setValue(int(percentage))
  8636. def setup_shell(self):
  8637. """
  8638. Creates shell functions. Runs once at startup.
  8639. :return: None
  8640. """
  8641. self.log.debug("setup_shell()")
  8642. def shelp(p=None):
  8643. if not p:
  8644. return _("Available commands:\n") + \
  8645. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  8646. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  8647. if p not in commands:
  8648. return "Unknown command: %s" % p
  8649. return commands[p]["help"]
  8650. # --- Migrated to new architecture ---
  8651. # def options(name):
  8652. # ops = self.collection.get_by_name(str(name)).options
  8653. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  8654. def h(*args):
  8655. """
  8656. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  8657. and standalone parameters into list.
  8658. """
  8659. kwa = {}
  8660. a = []
  8661. n = len(args)
  8662. name = None
  8663. for i in range(n):
  8664. match = re.search(r'^-([a-zA-Z].*)', args[i])
  8665. if match:
  8666. assert name is None
  8667. name = match.group(1)
  8668. continue
  8669. if name is None:
  8670. a.append(args[i])
  8671. else:
  8672. kwa[name] = args[i]
  8673. name = None
  8674. return a, kwa
  8675. @contextmanager
  8676. def wait_signal(signal, timeout=10000):
  8677. """
  8678. Block loop until signal emitted, timeout (ms) elapses
  8679. or unhandled exception happens in a thread.
  8680. :param timeout: time after which the loop is exited
  8681. :param signal: Signal to wait for.
  8682. """
  8683. loop = QtCore.QEventLoop()
  8684. # Normal termination
  8685. signal.connect(loop.quit)
  8686. # Termination by exception in thread
  8687. self.thread_exception.connect(loop.quit)
  8688. status = {'timed_out': False}
  8689. def report_quit():
  8690. status['timed_out'] = True
  8691. loop.quit()
  8692. yield
  8693. # Temporarily change how exceptions are managed.
  8694. oeh = sys.excepthook
  8695. ex = []
  8696. def except_hook(type_, value, traceback_):
  8697. ex.append(value)
  8698. oeh(type_, value, traceback_)
  8699. sys.excepthook = except_hook
  8700. # Terminate on timeout
  8701. if timeout is not None:
  8702. QtCore.QTimer.singleShot(timeout, report_quit)
  8703. # # ## Block ## ##
  8704. loop.exec_()
  8705. # Restore exception management
  8706. sys.excepthook = oeh
  8707. if ex:
  8708. self.raiseTclError(str(ex[0]))
  8709. if status['timed_out']:
  8710. raise Exception('Timed out!')
  8711. def make_docs():
  8712. output = ''
  8713. import collections
  8714. od = collections.OrderedDict(sorted(commands.items()))
  8715. for cmd_, val in od.items():
  8716. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  8717. t = val['help']
  8718. usage_i = t.find('>')
  8719. if usage_i < 0:
  8720. expl = t
  8721. output += expl + '\n\n'
  8722. continue
  8723. expl = t[:usage_i - 1]
  8724. output += expl + '\n\n'
  8725. end_usage_i = t[usage_i:].find('\n')
  8726. if end_usage_i < 0:
  8727. end_usage_i = len(t[usage_i:])
  8728. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  8729. else:
  8730. extras = t[usage_i+end_usage_i+1:]
  8731. parts = [s.strip() for s in extras.split('\n')]
  8732. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  8733. for p in parts:
  8734. output += ' ' + p + '\n\n'
  8735. return output
  8736. '''
  8737. Howto implement TCL shell commands:
  8738. All parameters passed to command should be possible to set as None and test it afterwards.
  8739. This is because we need to see error caused in tcl,
  8740. if None value as default parameter is not allowed TCL will return empty error.
  8741. Use:
  8742. def mycommand(name=None,...):
  8743. Test it like this:
  8744. if name is None:
  8745. self.raise_tcl_error('Argument name is missing.')
  8746. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  8747. otherwise we will miss it and processing will silently continue.
  8748. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  8749. which is catched in exec_command and displayed in TCL shell console with red background.
  8750. Error in console is displayed with TCL trace.
  8751. This behavior works only within main thread,
  8752. errors with promissed tasks can be catched and detected only with log.
  8753. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  8754. TCL shell.
  8755. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  8756. '''
  8757. commands = {
  8758. 'help': {
  8759. 'fcn': shelp,
  8760. 'help': _("Shows list of commands.")
  8761. },
  8762. }
  8763. # Import/overwrite tcl commands as objects of TclCommand descendants
  8764. # This modifies the variable 'commands'.
  8765. tclCommands.register_all_commands(self, commands)
  8766. # Add commands to the tcl interpreter
  8767. for cmd in commands:
  8768. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  8769. # Make the tcl puts function return instead of print to stdout
  8770. self.tcl.eval('''
  8771. rename puts original_puts
  8772. proc puts {args} {
  8773. if {[llength $args] == 1} {
  8774. return "[lindex $args 0]"
  8775. } else {
  8776. eval original_puts $args
  8777. }
  8778. }
  8779. ''')
  8780. def setup_recent_items(self):
  8781. # TODO: Move this to constructor
  8782. icons = {
  8783. "gerber": "share/flatcam_icon16.png",
  8784. "excellon": "share/drill16.png",
  8785. 'geometry': "share/geometry16.png",
  8786. "cncjob": "share/cnc16.png",
  8787. "project": "share/project16.png",
  8788. "svg": "share/geometry16.png",
  8789. "dxf": "share/dxf16.png",
  8790. "pdf": "share/pdf32.png",
  8791. "image": "share/image16.png"
  8792. }
  8793. openers = {
  8794. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8795. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8796. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8797. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8798. 'project': self.open_project,
  8799. 'svg': self.import_svg,
  8800. 'dxf': self.import_dxf,
  8801. 'image': self.import_image,
  8802. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8803. }
  8804. # Open recent file for files
  8805. try:
  8806. f = open(self.data_path + '/recent.json')
  8807. except IOError:
  8808. App.log.error("Failed to load recent item list.")
  8809. self.inform.emit('[ERROR_NOTCL] %s' %
  8810. _("Failed to load recent item list."))
  8811. return
  8812. try:
  8813. self.recent = json.load(f)
  8814. except json.scanner.JSONDecodeError:
  8815. App.log.error("Failed to parse recent item list.")
  8816. self.inform.emit('[ERROR_NOTCL] %s' %
  8817. _("Failed to parse recent item list."))
  8818. f.close()
  8819. return
  8820. f.close()
  8821. # Open recent file for projects
  8822. try:
  8823. fp = open(self.data_path + '/recent_projects.json')
  8824. except IOError:
  8825. App.log.error("Failed to load recent project item list.")
  8826. self.inform.emit('[ERROR_NOTCL] %s' %
  8827. _("Failed to load recent projects item list."))
  8828. return
  8829. try:
  8830. self.recent_projects = json.load(fp)
  8831. except json.scanner.JSONDecodeError:
  8832. App.log.error("Failed to parse recent project item list.")
  8833. self.inform.emit('[ERROR_NOTCL] %s' %
  8834. _("Failed to parse recent project item list."))
  8835. fp.close()
  8836. return
  8837. fp.close()
  8838. # Closure needed to create callbacks in a loop.
  8839. # Otherwise late binding occurs.
  8840. def make_callback(func, fname):
  8841. def opener():
  8842. func(fname)
  8843. return opener
  8844. def reset_recent_files():
  8845. # Reset menu
  8846. self.ui.recent.clear()
  8847. self.recent = []
  8848. try:
  8849. f = open(self.data_path + '/recent.json', 'w')
  8850. except IOError:
  8851. App.log.error("Failed to open recent items file for writing.")
  8852. return
  8853. json.dump(self.recent, f)
  8854. def reset_recent_projects():
  8855. # Reset menu
  8856. self.ui.recent_projects.clear()
  8857. self.recent_projects = []
  8858. try:
  8859. fp = open(self.data_path + '/recent_projects.json', 'w')
  8860. except IOError:
  8861. App.log.error("Failed to open recent projects items file for writing.")
  8862. return
  8863. json.dump(self.recent, fp)
  8864. # Reset menu
  8865. self.ui.recent.clear()
  8866. self.ui.recent_projects.clear()
  8867. # Create menu items for projects
  8868. for recent in self.recent_projects:
  8869. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8870. if recent['kind'] == 'project':
  8871. try:
  8872. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8873. # Attach callback
  8874. o = make_callback(openers[recent["kind"]], recent['filename'])
  8875. action.triggered.connect(o)
  8876. self.ui.recent_projects.addAction(action)
  8877. except KeyError:
  8878. App.log.error("Unsupported file type: %s" % recent["kind"])
  8879. # Last action in Recent Files menu is one that Clear the content
  8880. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  8881. clear_action_proj.triggered.connect(reset_recent_projects)
  8882. self.ui.recent_projects.addSeparator()
  8883. self.ui.recent_projects.addAction(clear_action_proj)
  8884. # Create menu items for files
  8885. for recent in self.recent:
  8886. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8887. if recent['kind'] != 'project':
  8888. try:
  8889. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8890. # Attach callback
  8891. o = make_callback(openers[recent["kind"]], recent['filename'])
  8892. action.triggered.connect(o)
  8893. self.ui.recent.addAction(action)
  8894. except KeyError:
  8895. App.log.error("Unsupported file type: %s" % recent["kind"])
  8896. # Last action in Recent Files menu is one that Clear the content
  8897. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  8898. clear_action.triggered.connect(reset_recent_files)
  8899. self.ui.recent.addSeparator()
  8900. self.ui.recent.addAction(clear_action)
  8901. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8902. # self.ui.menufilerecent.set_submenu(recent_menu)
  8903. # recent_menu.show_all()
  8904. # self.ui.recent.show()
  8905. self.log.debug("Recent items list has been populated.")
  8906. def setup_component_editor(self):
  8907. # label = QtWidgets.QLabel("Choose an item from Project")
  8908. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8909. sel_title = QtWidgets.QTextEdit(
  8910. _('<b>Shortcut Key List</b>'))
  8911. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8912. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8913. settings = QSettings("Open Source", "FlatCAM")
  8914. if settings.contains("notebook_font_size"):
  8915. fsize = settings.value('notebook_font_size', type=int)
  8916. else:
  8917. fsize = 12
  8918. tsize = fsize + int(fsize / 2)
  8919. # selected_text = (_('''
  8920. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  8921. #
  8922. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8923. # The normal flow when working in FlatCAM is the following:</span></p>
  8924. #
  8925. # <ol>
  8926. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  8927. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  8928. # even dragging and dropping the files on the GUI.<br />
  8929. # <br />
  8930. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  8931. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  8932. # &nbsp;</li>
  8933. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  8934. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  8935. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  8936. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  8937. # <br />
  8938. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  8939. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  8940. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  8941. # it even if it was out of focus.<br />
  8942. # <br />
  8943. # You can change the parameters in this screen and the flow direction is like this:<br />
  8944. # <br />
  8945. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  8946. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  8947. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  8948. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  8949. # </ol>
  8950. #
  8951. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  8952. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  8953. # <strong>F3</strong>.</span></p>
  8954. #
  8955. # ''').format(fsize=fsize, tsize=tsize))
  8956. selected_text = '''
  8957. <p><span style="font-size:{tsize}px"><strong>%s</strong></span></p>
  8958. <p><span style="font-size:{fsize}px"><strong>%s</strong>:<br />
  8959. %s:</span></p>
  8960. <ol>
  8961. <li><span style="font-size:{fsize}px">%s menu&#39;s, %s.<br />
  8962. <br />
  8963. %s &amp; %s.</span><br />
  8964. &nbsp;</li>
  8965. <li><span style="font-size:{fsize}px">%s <strong>%s</strong> (%s), <strong>%s</strong> %s it-s %s.<br />
  8966. <br />
  8967. %s <strong>%s</strong> %s <strong>%s</strong> %s.<br />
  8968. <br />
  8969. %s:<br />
  8970. <br />
  8971. <strong>%s</strong> -&gt; %s -&gt; %s -&gt;<strong> %s </strong> -&gt; %s -&gt; %s -&gt;<strong> %s
  8972. </strong>-&gt; %s <strong>%s)&nbsp;</strong>-&gt; %s</span></li>
  8973. </ol>
  8974. <p><span style="font-size:{fsize}px">%s <strong>%s -&gt; %s</strong>&nbsp;%s it&#39;s %s:
  8975. <strong>F3</strong>.</span></p>
  8976. ''' % (
  8977. _("Selected Tab - Choose an Item from Project Tab"), _("Details"),
  8978. _("The normal flow when working in FlatCAM is the following"),
  8979. _("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the"),
  8980. _("toolbars, key shortcuts or even dragging and dropping the files on the GUI"),
  8981. _("You can also load a FlatCAM project by double clicking on the project file, drag"),
  8982. _("drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app"),
  8983. _("Once an object is available in the Project Tab, by selecting it and then focusing on"),
  8984. _("SELECTED TAB"), _("more simpler is to double click the object name in the Project Tab"),
  8985. _("SELECTED TAB"), _("will be updated with the object properties according to"),
  8986. _("kind: Gerber, Excellon, Geometry or CNCJob object"),
  8987. _("If the selection of the object is done on the canvas by single click instead, and the"),
  8988. _("SELECTED TAB"),
  8989. _("is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, "
  8990. "double clicking on the object on the canvas will bring the"),
  8991. _("SELECTED TAB"), _("and populate it even if it was out of focus"),
  8992. _("You can change the parameters in this screen and the flow direction is like this"),
  8993. _("Gerber/Excellon Object"), _("Change Parameter"), _("Generate Geometry"), _("Geometry Object"),
  8994. _("Add tools (change param in Selected Tab)"), _("Generate CNCJob"), _("CNCJob Object"),
  8995. _("Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in"), _("SELECTED TAB"),
  8996. _("Save GCode"), _("A list of key shortcuts is available through an menu entry in"), _("Help"),
  8997. _("Shortcuts List"), _("or through"), _("own key shortcut"),
  8998. )
  8999. sel_title.setText(selected_text)
  9000. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  9001. self.ui.selected_scroll_area.setWidget(sel_title)
  9002. def setup_obj_classes(self):
  9003. """
  9004. Sets up application specifics on the FlatCAMObj class.
  9005. :return: None
  9006. """
  9007. FlatCAMObj.app = self
  9008. ObjectCollection.app = self
  9009. Gerber.app = self
  9010. Excellon.app = self
  9011. Geometry.app = self
  9012. CNCjob.app = self
  9013. FCProcess.app = self
  9014. FCProcessContainer.app = self
  9015. def version_check(self):
  9016. """
  9017. Checks for the latest version of the program. Alerts the
  9018. user if theirs is outdated. This method is meant to be run
  9019. in a separate thread.
  9020. :return: None
  9021. """
  9022. self.log.debug("version_check()")
  9023. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  9024. full_url = App.version_url + \
  9025. "?s=" + str(self.defaults['global_serial']) + \
  9026. "&v=" + str(self.version) + \
  9027. "&os=" + str(self.os) + \
  9028. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  9029. else:
  9030. # no_stats dict; just so it won't break things on website
  9031. no_ststs_dict = {}
  9032. no_ststs_dict["global_ststs"] = {}
  9033. full_url = App.version_url + \
  9034. "?s=" + str(self.defaults['global_serial']) + \
  9035. "&v=" + str(self.version) + \
  9036. "&os=" + str(self.os) + \
  9037. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  9038. App.log.debug("Checking for updates @ %s" % full_url)
  9039. # ## Get the data
  9040. try:
  9041. f = urllib.request.urlopen(full_url)
  9042. except:
  9043. # App.log.warning("Failed checking for latest version. Could not connect.")
  9044. self.log.warning("Failed checking for latest version. Could not connect.")
  9045. self.inform.emit('[WARNING_NOTCL] %s' %
  9046. _("Failed checking for latest version. Could not connect."))
  9047. return
  9048. try:
  9049. data = json.load(f)
  9050. except Exception as e:
  9051. App.log.error("Could not parse information about latest version.")
  9052. self.inform.emit('[ERROR_NOTCL] %s' %
  9053. _("Could not parse information about latest version."))
  9054. App.log.debug("json.load(): %s" % str(e))
  9055. f.close()
  9056. return
  9057. f.close()
  9058. # ## Latest version?
  9059. if self.version >= data["version"]:
  9060. App.log.debug("FlatCAM is up to date!")
  9061. self.inform.emit('[success] %s' %
  9062. _("FlatCAM is up to date!"))
  9063. return
  9064. App.log.debug("Newer version available.")
  9065. self.message.emit(
  9066. _("Newer Version Available"),
  9067. _("There is a newer version of FlatCAM available for download:\n\n") +
  9068. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  9069. _("info")
  9070. )
  9071. def on_plotcanvas_setup(self, container=None):
  9072. """
  9073. This is doing the setup for the plot area (VisPy canvas)
  9074. :param container: widget where to install the canvas
  9075. :return: None
  9076. """
  9077. if container:
  9078. plot_container = container
  9079. else:
  9080. plot_container = self.ui.right_layout
  9081. self.plotcanvas = PlotCanvas(plot_container, self)
  9082. # So it can receive key presses
  9083. self.plotcanvas.native.setFocus()
  9084. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  9085. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  9086. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  9087. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  9088. # Keys over plot enabled
  9089. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  9090. self.app_cursor = self.plotcanvas.new_cursor()
  9091. self.app_cursor.enabled = False
  9092. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  9093. def on_zoom_fit(self, event):
  9094. """
  9095. Callback for zoom-out request. This can be either from the corresponding
  9096. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  9097. with axes limits from the geometry bounds of all objects.
  9098. :param event: Ignored.
  9099. :return: None
  9100. """
  9101. self.plotcanvas.fit_view()
  9102. def on_zoom_in(self):
  9103. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  9104. def on_zoom_out(self):
  9105. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  9106. def disable_all_plots(self):
  9107. self.report_usage("disable_all_plots()")
  9108. self.disable_plots(self.collection.get_list())
  9109. self.inform.emit('[success] %s' %
  9110. _("All plots disabled."))
  9111. def disable_other_plots(self):
  9112. self.report_usage("disable_other_plots()")
  9113. self.disable_plots(self.collection.get_non_selected())
  9114. self.inform.emit('[success] %s' %
  9115. _("All non selected plots disabled."))
  9116. def enable_all_plots(self):
  9117. self.report_usage("enable_all_plots()")
  9118. self.enable_plots(self.collection.get_list())
  9119. self.inform.emit('[success] %s' %
  9120. _("All plots enabled."))
  9121. def on_enable_sel_plots(self):
  9122. log.debug("App.on_enable_sel_plot()")
  9123. object_list = self.collection.get_selected()
  9124. self.enable_plots(objects=object_list)
  9125. self.inform.emit('[success] %s' %
  9126. _("Selected plots enabled..."))
  9127. def on_disable_sel_plots(self):
  9128. log.debug("App.on_disable_sel_plot()")
  9129. # self.inform.emit(_("Disabling plots ..."))
  9130. object_list = self.collection.get_selected()
  9131. self.disable_plots(objects=object_list)
  9132. self.inform.emit('[success] %s' %
  9133. _("Selected plots disabled..."))
  9134. def enable_plots(self, objects):
  9135. """
  9136. Disables plots
  9137. :param objects: list of Objects to be enabled
  9138. :return:
  9139. """
  9140. log.debug("Enabling plots ...")
  9141. # self.inform.emit(_("Working ..."))
  9142. for obj in objects:
  9143. if obj.options['plot'] is False:
  9144. obj.options.set_change_callback(lambda x: None)
  9145. obj.options['plot'] = True
  9146. obj.options.set_change_callback(obj.on_options_change)
  9147. def worker_task(objects):
  9148. with self.proc_container.new(_("Enabling plots ...")):
  9149. for obj in objects:
  9150. # obj.options['plot'] = True
  9151. if isinstance(obj, FlatCAMCNCjob):
  9152. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  9153. else:
  9154. obj.plot(visible=True)
  9155. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9156. # self.plots_updated.emit()
  9157. def disable_plots(self, objects):
  9158. """
  9159. Disables plots
  9160. :param objects: list of Objects to be disabled
  9161. :return:
  9162. """
  9163. # if no objects selected then do nothing
  9164. if not self.collection.get_selected():
  9165. return
  9166. log.debug("Disabling plots ...")
  9167. # self.inform.emit(_("Working ..."))
  9168. for obj in objects:
  9169. if obj.options['plot'] is True:
  9170. obj.options.set_change_callback(lambda x: None)
  9171. obj.options['plot'] = False
  9172. obj.options.set_change_callback(obj.on_options_change)
  9173. try:
  9174. self.delete_selection_shape()
  9175. except Exception as e:
  9176. log.debug("App.disable_plots() --> %s" % str(e))
  9177. # self.plots_updated.emit()
  9178. def worker_task(objects):
  9179. with self.proc_container.new(_("Disabling plots ...")):
  9180. for obj in objects:
  9181. # obj.options['plot'] = True
  9182. if isinstance(obj, FlatCAMCNCjob):
  9183. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  9184. else:
  9185. obj.plot(visible=False)
  9186. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9187. def toggle_plots(self, objects):
  9188. """
  9189. Toggle plots visibility
  9190. :param objects: list of Objects for which to be toggled the visibility
  9191. :return:
  9192. """
  9193. # if no objects selected then do nothing
  9194. if not self.collection.get_selected():
  9195. return
  9196. log.debug("Toggling plots ...")
  9197. self.inform.emit(_("Working ..."))
  9198. for obj in objects:
  9199. if obj.options['plot'] is False:
  9200. obj.options['plot'] = True
  9201. else:
  9202. obj.options['plot'] = False
  9203. self.plots_updated.emit()
  9204. def clear_plots(self):
  9205. objects = self.collection.get_list()
  9206. for obj in objects:
  9207. obj.clear(obj == objects[-1])
  9208. # Clear pool to free memory
  9209. self.clear_pool()
  9210. def generate_cnc_job(self, objects):
  9211. self.report_usage("generate_cnc_job()")
  9212. # for obj in objects:
  9213. # obj.generatecncjob()
  9214. for obj in objects:
  9215. obj.on_generatecnc_button_click()
  9216. def save_project(self, filename, quit_action=False, silent=False):
  9217. """
  9218. Saves the current project to the specified file.
  9219. :param filename: Name of the file in which to save.
  9220. :type filename: str
  9221. :param quit_action: if the project saving will be followed by an app quit; boolean
  9222. :param silent: if True will not display status messages
  9223. :return: None
  9224. """
  9225. self.log.debug("save_project()")
  9226. self.save_in_progress = True
  9227. with self.proc_container.new(_("Saving FlatCAM Project")):
  9228. # Capture the latest changes
  9229. # Current object
  9230. try:
  9231. self.collection.get_active().read_form()
  9232. except:
  9233. self.log.debug("There was no active object")
  9234. pass
  9235. # Project options
  9236. self.options_read_form()
  9237. # Serialize the whole project
  9238. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  9239. "options": self.options,
  9240. "version": self.version}
  9241. if self.defaults["global_save_compressed"] is True:
  9242. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  9243. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  9244. # # Write
  9245. f.write(g)
  9246. self.inform.emit('[success] %s: %s' %
  9247. (_("Project saved to"), filename))
  9248. else:
  9249. # Open file
  9250. try:
  9251. f = open(filename, 'w')
  9252. except IOError:
  9253. App.log.error("Failed to open file for saving: %s", filename)
  9254. return
  9255. # Write
  9256. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  9257. f.close()
  9258. # verification of the saved project
  9259. # Open and parse
  9260. try:
  9261. saved_f = open(filename, 'r')
  9262. except IOError:
  9263. if silent is False:
  9264. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9265. (_("Failed to verify project file"), filename, _("Retry to save it."))
  9266. )
  9267. return
  9268. try:
  9269. saved_d = json.load(saved_f, object_hook=dict2obj)
  9270. except:
  9271. if silent is False:
  9272. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9273. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9274. )
  9275. f.close()
  9276. return
  9277. saved_f.close()
  9278. if silent is False:
  9279. if 'version' in saved_d:
  9280. self.inform.emit('[success] %s: %s' %
  9281. (_("Project saved to"), filename))
  9282. else:
  9283. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9284. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9285. )
  9286. settings = QSettings("Open Source", "FlatCAM")
  9287. lock_state = self.ui.lock_action.isChecked()
  9288. settings.setValue('toolbar_lock', lock_state)
  9289. # This will write the setting to the platform specific storage.
  9290. del settings
  9291. # if quit:
  9292. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  9293. # t.start()
  9294. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  9295. def start_delayed_quit(self, delay, filename, should_quit=None):
  9296. """
  9297. :param delay: period of checking if project file size is more than zero; in seconds
  9298. :param filename: the name of the project file to be checked periodically for size more than zero
  9299. :param should_quit: if the task finished will be followed by an app quit; boolean
  9300. :return:
  9301. """
  9302. to_quit = should_quit
  9303. self.save_timer = QtCore.QTimer()
  9304. self.save_timer.setInterval(delay)
  9305. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  9306. self.save_timer.start()
  9307. def check_project_file_size(self, filename, should_quit=None):
  9308. """
  9309. :param filename: the name of the project file to be checked periodically for size more than zero
  9310. :param should_quit: will quit the app if True; boolean
  9311. :return:
  9312. """
  9313. try:
  9314. if os.stat(filename).st_size > 0:
  9315. self.save_in_progress = False
  9316. self.save_timer.stop()
  9317. if should_quit:
  9318. self.app_quit.emit()
  9319. except Exception as e:
  9320. traceback.print_exc()
  9321. def on_options_app2project(self):
  9322. """
  9323. Callback for Options->Transfer Options->App=>Project. Copies options
  9324. from application defaults to project defaults.
  9325. :return: None
  9326. """
  9327. self.report_usage("on_options_app2project")
  9328. self.defaults_read_form()
  9329. self.options.update(self.defaults)
  9330. self.options_write_form()
  9331. def on_options_project2app(self):
  9332. """
  9333. Callback for Options->Transfer Options->Project=>App. Copies options
  9334. from project defaults to application defaults.
  9335. :return: None
  9336. """
  9337. self.report_usage("on_options_project2app")
  9338. self.options_read_form()
  9339. self.defaults.update(self.options)
  9340. self.defaults_write_form()
  9341. def on_options_project2object(self):
  9342. """
  9343. Callback for Options->Transfer Options->Project=>Object. Copies options
  9344. from project defaults to the currently selected object.
  9345. :return: None
  9346. """
  9347. self.report_usage("on_options_project2object")
  9348. self.options_read_form()
  9349. obj = self.collection.get_active()
  9350. if obj is None:
  9351. self.inform.emit('[WARNING_NOTCL] %s' %
  9352. _("No object selected."))
  9353. return
  9354. for option in self.options:
  9355. if option.find(obj.kind + "_") == 0:
  9356. oname = option[len(obj.kind) + 1:]
  9357. obj.options[oname] = self.options[option]
  9358. obj.to_form() # Update UI
  9359. def on_options_object2project(self):
  9360. """
  9361. Callback for Options->Transfer Options->Object=>Project. Copies options
  9362. from the currently selected object to project defaults.
  9363. :return: None
  9364. """
  9365. self.report_usage("on_options_object2project")
  9366. obj = self.collection.get_active()
  9367. if obj is None:
  9368. self.inform.emit('[WARNING_NOTCL] %s' %
  9369. _("No object selected."))
  9370. return
  9371. obj.read_form()
  9372. for option in obj.options:
  9373. if option in ['name']: # TODO: Handle this better...
  9374. continue
  9375. self.options[obj.kind + "_" + option] = obj.options[option]
  9376. self.options_write_form()
  9377. def on_options_object2app(self):
  9378. """
  9379. Callback for Options->Transfer Options->Object=>App. Copies options
  9380. from the currently selected object to application defaults.
  9381. :return: None
  9382. """
  9383. self.report_usage("on_options_object2app")
  9384. obj = self.collection.get_active()
  9385. if obj is None:
  9386. self.inform.emit('[WARNING_NOTCL] %s' %
  9387. _("No object selected."))
  9388. return
  9389. obj.read_form()
  9390. for option in obj.options:
  9391. if option in ['name']: # TODO: Handle this better...
  9392. continue
  9393. self.defaults[obj.kind + "_" + option] = obj.options[option]
  9394. self.defaults_write_form()
  9395. def on_options_app2object(self):
  9396. """
  9397. Callback for Options->Transfer Options->App=>Object. Copies options
  9398. from application defaults to the currently selected object.
  9399. :return: None
  9400. """
  9401. self.report_usage("on_options_app2object")
  9402. self.defaults_read_form()
  9403. obj = self.collection.get_active()
  9404. if obj is None:
  9405. self.inform.emit('[WARNING_NOTCL] %s' %
  9406. _("No object selected."))
  9407. return
  9408. for option in self.defaults:
  9409. if option.find(obj.kind + "_") == 0:
  9410. oname = option[len(obj.kind) + 1:]
  9411. obj.options[oname] = self.defaults[option]
  9412. obj.to_form() # Update UI
  9413. class ArgsThread(QtCore.QObject):
  9414. open_signal = pyqtSignal(list)
  9415. start = pyqtSignal()
  9416. if sys.platform == 'win32':
  9417. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  9418. else:
  9419. address = ('/tmp/testipc', 'AF_UNIX')
  9420. def __init__(self):
  9421. super(ArgsThread, self).__init__()
  9422. self.start.connect(self.run)
  9423. def my_loop(self, address):
  9424. try:
  9425. listener = Listener(*address)
  9426. while True:
  9427. conn = listener.accept()
  9428. self.serve(conn)
  9429. except socket.error as e:
  9430. conn = Client(*address)
  9431. conn.send(sys.argv)
  9432. conn.send('close')
  9433. # close the current instance only if there are args
  9434. if len(sys.argv) > 1:
  9435. sys.exit()
  9436. def serve(self, conn):
  9437. while True:
  9438. msg = conn.recv()
  9439. if msg == 'close':
  9440. break
  9441. self.open_signal.emit(msg)
  9442. conn.close()
  9443. # the decorator is a must; without it this technique will not work unless the start signal is connected
  9444. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  9445. @pyqtSlot()
  9446. def run(self):
  9447. self.my_loop(self.address)
  9448. class GracefulException(Exception):
  9449. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  9450. def __init__(self):
  9451. super().__init__()
  9452. def __str__(self):
  9453. return ('\n\n%s' % _("The user requested a graceful exit of the current task."))
  9454. # end of file