FlatCAMApp.py 534 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898
  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, cpu_count
  27. import socket
  28. from array import array
  29. # #######################################
  30. # # Imports part of FlatCAM ##
  31. # #######################################
  32. from ObjectCollection import *
  33. from FlatCAMObj import *
  34. from flatcamGUI.PlotCanvas import *
  35. from flatcamGUI.PlotCanvasLegacy import *
  36. from flatcamGUI.FlatCAMGUI import *
  37. from FlatCAMCommon import LoudDict
  38. from FlatCAMPostProc import load_postprocessors
  39. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  40. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  41. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  42. from flatcamEditors.FlatCAMTextEditor import TextEditor
  43. from FlatCAMProcess import *
  44. from FlatCAMWorkerStack import WorkerStack
  45. # from flatcamGUI.VisPyVisuals import Color
  46. from vispy.gloo.util import _screenshot
  47. from vispy.io import write_png
  48. from flatcamTools import *
  49. import tclCommands
  50. import gettext
  51. import FlatCAMTranslation as fcTranslate
  52. import builtins
  53. if sys.platform == 'win32':
  54. import winreg
  55. fcTranslate.apply_language('strings')
  56. if '_' not in builtins.__dict__:
  57. _ = gettext.gettext
  58. class App(QtCore.QObject):
  59. # ########################################
  60. # # App ###
  61. # ########################################
  62. """
  63. The main application class. The constructor starts the GUI.
  64. """
  65. # Get Cmd Line Options
  66. cmd_line_shellfile = ''
  67. cmd_line_shellvar = ''
  68. cmd_line_headless = None
  69. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  70. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  71. "FlatCam.py --headless=1"
  72. try:
  73. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  74. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  75. "shellvar=",
  76. "headless=",
  77. "multiprocessing-fork="])
  78. except getopt.GetoptError:
  79. print(cmd_line_help)
  80. sys.exit(2)
  81. for opt, arg in cmd_line_options:
  82. if opt == '-h':
  83. print(cmd_line_help)
  84. sys.exit()
  85. elif opt == '--shellfile':
  86. cmd_line_shellfile = arg
  87. elif opt == '--shellvar':
  88. cmd_line_shellvar = arg
  89. elif opt == '--headless':
  90. try:
  91. cmd_line_headless = eval(arg)
  92. except NameError:
  93. pass
  94. # ## Logging ###
  95. log = logging.getLogger('base')
  96. log.setLevel(logging.DEBUG)
  97. # log.setLevel(logging.WARNING)
  98. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  99. handler = logging.StreamHandler()
  100. handler.setFormatter(formatter)
  101. log.addHandler(handler)
  102. # ##########################################################################
  103. # ################## Version and VERSION DATE ##############################
  104. # ##########################################################################
  105. version = 8.98
  106. version_date = "2019/10/7"
  107. beta = True
  108. engine = '3D'
  109. # current date now
  110. date = str(datetime.today()).rpartition('.')[0]
  111. date = ''.join(c for c in date if c not in ':-')
  112. date = date.replace(' ', '_')
  113. # URL for update checks and statistics
  114. version_url = "http://flatcam.org/version"
  115. # App URL
  116. app_url = "http://flatcam.org"
  117. # Manual URL
  118. manual_url = "http://flatcam.org/manual/index.html"
  119. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  120. gerber_spec_url ="https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  121. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  122. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  123. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  124. # this variable will hold the project status
  125. # if True it will mean that the project was modified and not saved
  126. should_we_save = False
  127. # flag is True if saving action has been triggered
  128. save_in_progress = False
  129. # ###########################################################################
  130. # ############################# Signals ################################
  131. # ###########################################################################
  132. # Inform the user
  133. # Handled by:
  134. # * App.info() --> Print on the status bar
  135. inform = QtCore.pyqtSignal(str)
  136. app_quit = QtCore.pyqtSignal()
  137. # General purpose background task
  138. worker_task = QtCore.pyqtSignal(dict)
  139. # File opened
  140. # Handled by:
  141. # * register_folder()
  142. # * register_recent()
  143. # Note: Setting the parameters to unicode does not seem
  144. # to have an effect. Then are received as Qstring
  145. # anyway.
  146. # File type and filename
  147. file_opened = QtCore.pyqtSignal(str, str)
  148. # File type and filename
  149. file_saved = QtCore.pyqtSignal(str, str)
  150. # Percentage of progress
  151. progress = QtCore.pyqtSignal(int)
  152. plots_updated = QtCore.pyqtSignal()
  153. # Emitted by new_object() and passes the new object as argument, plot flag.
  154. # on_object_created() adds the object to the collection, plots on appropriate flag
  155. # and emits new_object_available.
  156. object_created = QtCore.pyqtSignal(object, bool, bool)
  157. # Emitted when a object has been changed (like scaled, mirrored)
  158. object_changed = QtCore.pyqtSignal(object)
  159. # Emitted after object has been plotted.
  160. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  161. object_plotted = QtCore.pyqtSignal(object)
  162. # Emitted when a new object has been added or deleted from/to the collection
  163. object_status_changed = QtCore.pyqtSignal(object, str, str)
  164. message = QtCore.pyqtSignal(str, str, str)
  165. # Emmited when shell command is finished(one command only)
  166. shell_command_finished = QtCore.pyqtSignal(object)
  167. # Emitted when multiprocess pool has been recreated
  168. pool_recreated = QtCore.pyqtSignal(object)
  169. # Emitted when an unhandled exception happens
  170. # in the worker task.
  171. thread_exception = QtCore.pyqtSignal(object)
  172. # used to signal that there are arguments for the app
  173. args_at_startup = QtCore.pyqtSignal(list)
  174. # a reusable signal to replot a list of objects
  175. # should be disconnected after use so it can be reused
  176. replot_signal = pyqtSignal(list)
  177. def __init__(self, user_defaults=True, post_gui=None):
  178. """
  179. Starts the application.
  180. :return: app
  181. :rtype: App
  182. """
  183. App.log.info("FlatCAM Starting...")
  184. self.main_thread = QtWidgets.QApplication.instance().thread()
  185. # ############################################################################
  186. # # ################# OS-specific ############################################
  187. # ############################################################################
  188. portable = False
  189. # Folder for user settings.
  190. if sys.platform == 'win32':
  191. # #########################################################################
  192. # Setup the listening thread for another instance launching with args #####
  193. # #########################################################################
  194. # make sure the thread is stored by using a self. otherwise it's garbage collected
  195. self.th = QtCore.QThread()
  196. self.th.start(priority=QtCore.QThread.LowestPriority)
  197. self.new_launch = ArgsThread()
  198. self.new_launch.open_signal[list].connect(self.on_startup_args)
  199. self.new_launch.moveToThread(self.th)
  200. self.new_launch.start.emit()
  201. from win32com.shell import shell, shellcon
  202. if platform.architecture()[0] == '32bit':
  203. App.log.debug("Win32!")
  204. else:
  205. App.log.debug("Win64!")
  206. # #########################################################################
  207. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  208. # #########################################################################
  209. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  210. try:
  211. with open(config_file, 'r'):
  212. pass
  213. except FileNotFoundError:
  214. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  215. try:
  216. with open(config_file, 'r') as f:
  217. try:
  218. for line in f:
  219. param = str(line).replace('\n', '').rpartition('=')
  220. if param[0] == 'portable':
  221. try:
  222. portable = eval(param[2])
  223. except NameError:
  224. portable = False
  225. if param[0] == 'headless':
  226. if param[2].lower() == 'true':
  227. self.cmd_line_headless = 1
  228. else:
  229. self.cmd_line_headless = None
  230. except Exception as e:
  231. log.debug('App.__init__() -->%s' % str(e))
  232. return
  233. except FileNotFoundError as e:
  234. log.debug(str(e))
  235. pass
  236. if portable is False:
  237. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  238. else:
  239. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  240. self.os = 'windows'
  241. else: # Linux/Unix/MacOS
  242. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  243. self.os = 'unix'
  244. # ##########################################################################
  245. # ################## Setup folders and files ###############################
  246. # ##########################################################################
  247. if not os.path.exists(self.data_path):
  248. os.makedirs(self.data_path)
  249. App.log.debug('Created data folder: ' + self.data_path)
  250. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  251. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  252. self.postprocessorpaths = os.path.join(self.data_path, 'postprocessors')
  253. if not os.path.exists(self.postprocessorpaths):
  254. os.makedirs(self.postprocessorpaths)
  255. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  256. # create current_defaults.FlatConfig file if there is none
  257. try:
  258. f = open(self.data_path + '/current_defaults.FlatConfig')
  259. f.close()
  260. except IOError:
  261. App.log.debug('Creating empty current_defaults.FlatConfig')
  262. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  263. json.dump({}, f)
  264. f.close()
  265. # create factory_defaults.FlatConfig file if there is none
  266. try:
  267. f = open(self.data_path + '/factory_defaults.FlatConfig')
  268. f.close()
  269. except IOError:
  270. App.log.debug('Creating empty factory_defaults.FlatConfig')
  271. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  272. json.dump({}, f)
  273. f.close()
  274. # create a recent files json file if there is none
  275. try:
  276. f = open(self.data_path + '/recent.json')
  277. f.close()
  278. except IOError:
  279. App.log.debug('Creating empty recent.json')
  280. f = open(self.data_path + '/recent.json', 'w')
  281. json.dump([], f)
  282. f.close()
  283. # create a recent projects json file if there is none
  284. try:
  285. fp = open(self.data_path + '/recent_projects.json')
  286. fp.close()
  287. except IOError:
  288. App.log.debug('Creating empty recent_projects.json')
  289. fp = open(self.data_path + '/recent_projects.json', 'w')
  290. json.dump([], fp)
  291. fp.close()
  292. # Application directory. CHDIR to it. Otherwise, trying to load
  293. # GUI icons will fail as their path is relative.
  294. # This will fail under cx_freeze ...
  295. self.app_home = os.path.dirname(os.path.realpath(__file__))
  296. App.log.debug("Application path is " + self.app_home)
  297. App.log.debug("Started in " + os.getcwd())
  298. # cx_freeze workaround
  299. if os.path.isfile(self.app_home):
  300. self.app_home = os.path.dirname(self.app_home)
  301. os.chdir(self.app_home)
  302. # #############################################################################
  303. # ##################### CREATE MULTIPROCESSING POOL ###########################
  304. # #############################################################################
  305. self.pool = Pool(processes=cpu_count())
  306. # ##########################################################################
  307. # ################## Setting the Splash Screen #############################
  308. # ##########################################################################
  309. settings = QSettings("Open Source", "FlatCAM")
  310. if settings.contains("splash_screen"):
  311. show_splash = settings.value("splash_screen")
  312. else:
  313. settings.setValue('splash_screen', 1)
  314. # This will write the setting to the platform specific storage.
  315. del settings
  316. show_splash = 1
  317. if show_splash and self.cmd_line_headless != 1:
  318. splash_pix = QtGui.QPixmap('share/splash.png')
  319. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  320. # self.splash.setMask(splash_pix.mask())
  321. # move splashscreen to the current monitor
  322. desktop = QtWidgets.QApplication.desktop()
  323. screen = desktop.screenNumber(QtGui.QCursor.pos())
  324. current_screen_center = desktop.availableGeometry(screen).center()
  325. self.splash.move(current_screen_center - self.splash.rect().center())
  326. self.splash.show()
  327. self.splash.showMessage(_("FlatCAM is initializing ..."),
  328. alignment=Qt.AlignBottom | Qt.AlignLeft,
  329. color=QtGui.QColor("gray"))
  330. else:
  331. show_splash = 0
  332. # #############################################################################
  333. # ##################### Initialize GUI ########################################
  334. # #############################################################################
  335. # FlatCAM colors used in plotting
  336. self.FC_light_green = '#BBF268BF'
  337. self.FC_dark_green = '#006E20BF'
  338. self.FC_light_blue = '#a5a5ffbf'
  339. self.FC_dark_blue = '#0000ffbf'
  340. QtCore.QObject.__init__(self)
  341. self.ui = FlatCAMGUI(self.version, self.beta, self)
  342. settings = QtCore.QSettings("Open Source", "FlatCAM")
  343. if settings.contains("theme"):
  344. theme = settings.value('theme', type=str)
  345. else:
  346. theme = 'white'
  347. if theme == 'white':
  348. self.cursor_color_3D = 'black'
  349. else:
  350. self.cursor_color_3D = 'gray'
  351. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  352. self.ui.final_save.connect(self.final_save)
  353. # #############################################################################
  354. # ############################## Data #########################################
  355. # #############################################################################
  356. self.recent = []
  357. self.recent_projects = []
  358. self.clipboard = QtWidgets.QApplication.clipboard()
  359. self.project_filename = None
  360. self.toggle_units_ignore = False
  361. # self.defaults_form = PreferencesUI()
  362. # when adding entries here read the comments in the method found bellow named:
  363. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  364. self.defaults_form_fields = {
  365. # General App
  366. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  367. "global_graphic_engine": self.ui.general_defaults_form.general_app_group.ge_radio,
  368. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  369. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  370. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  371. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  372. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  373. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  374. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  375. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  376. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  377. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  378. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  379. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  380. # General GUI Preferences
  381. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  382. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  383. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  384. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  385. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  386. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  387. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  388. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  389. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  390. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  391. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  392. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  393. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  394. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  395. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  396. "global_activity_icon": self.ui.general_defaults_form.general_gui_group.activity_combo,
  397. # General GUI Settings
  398. "global_theme": self.ui.general_defaults_form.general_gui_set_group.theme_radio,
  399. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  400. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  401. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  402. "global_systray_icon": self.ui.general_defaults_form.general_gui_set_group.systray_cb,
  403. "global_shell_at_startup": self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb,
  404. "global_project_at_startup": self.ui.general_defaults_form.general_gui_set_group.project_startup_cb,
  405. "global_project_autohide": self.ui.general_defaults_form.general_gui_set_group.project_autohide_cb,
  406. "global_toggle_tooltips": self.ui.general_defaults_form.general_gui_set_group.toggle_tooltips_cb,
  407. "global_delete_confirmation": self.ui.general_defaults_form.general_gui_set_group.delete_conf_cb,
  408. "global_cursor_type": self.ui.general_defaults_form.general_gui_set_group.cursor_radio,
  409. "global_cursor_size": self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry,
  410. # Gerber General
  411. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  412. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  413. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  414. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  415. "gerber_def_units": self.ui.gerber_defaults_form.gerber_gen_group.gerber_units_radio,
  416. "gerber_def_zeros": self.ui.gerber_defaults_form.gerber_gen_group.gerber_zeros_radio,
  417. # Gerber Options
  418. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  419. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  420. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  421. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  422. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  423. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  424. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  425. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  426. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  427. # Gerber Advanced Options
  428. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  429. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  430. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  431. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  432. "gerber_tool_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.tool_type_radio,
  433. "gerber_vtipdia": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipdia_spinner,
  434. "gerber_vtipangle": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipangle_spinner,
  435. "gerber_vcutz": self.ui.gerber_defaults_form.gerber_adv_opt_group.cutz_spinner,
  436. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  437. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  438. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  439. # Gerber Export
  440. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  441. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  442. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  443. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  444. # Gerber Editor
  445. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  446. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  447. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  448. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  449. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  450. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  451. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  452. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  453. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  454. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  455. "gerber_editor_circ_angle":
  456. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  457. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  458. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  459. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  460. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  461. # Excellon General
  462. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  463. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  464. "excellon_format_upper_in":
  465. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  466. "excellon_format_lower_in":
  467. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  468. "excellon_format_upper_mm":
  469. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  470. "excellon_format_lower_mm":
  471. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  472. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  473. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  474. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  475. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  476. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  477. # Excellon Options
  478. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  479. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  480. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.eendz_entry,
  481. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  482. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  483. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  484. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  485. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  486. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  487. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  488. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  489. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  490. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  491. # Excellon Advanced Options
  492. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  493. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  494. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  495. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  496. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  497. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  498. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  499. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  500. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  501. # Excellon Export
  502. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  503. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  504. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  505. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  506. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  507. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  508. # Excellon Editor
  509. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  510. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  511. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  512. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  513. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  514. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  515. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  516. "excellon_editor_circ_angle":
  517. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  518. # Excellon Slots
  519. "excellon_editor_slot_direction":
  520. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  521. "excellon_editor_slot_angle":
  522. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  523. "excellon_editor_slot_length":
  524. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  525. # Excellon Slots
  526. "excellon_editor_slot_array_size":
  527. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  528. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  529. "excellon_editor_slot_lin_pitch":
  530. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  531. "excellon_editor_slot_lin_angle":
  532. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  533. "excellon_editor_slot_circ_dir":
  534. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  535. "excellon_editor_slot_circ_angle":
  536. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  537. # Geometry General
  538. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  539. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  540. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  541. # Geometry Options
  542. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  543. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  544. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  545. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  546. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  547. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  548. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  549. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  550. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  551. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  552. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.gendz_entry,
  553. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  554. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  555. # Geometry Advanced Options
  556. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  557. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  558. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  559. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  560. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  561. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  562. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  563. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  564. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  565. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  566. # Geometry Editor
  567. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  568. "geometry_editor_milling_type": self.ui.geometry_defaults_form.geometry_editor_group.milling_type_radio,
  569. # CNCJob General
  570. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  571. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  572. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  573. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  574. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  575. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  576. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  577. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  578. # CNC Job Options
  579. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  580. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  581. # CNC Job Advanced Options
  582. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  583. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  584. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  585. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  586. # NCC Tool
  587. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  588. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  589. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  590. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  591. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  592. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  593. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  594. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  595. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  596. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  597. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  598. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  599. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  600. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  601. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  602. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  603. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  604. # CutOut Tool
  605. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  606. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  607. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  608. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  609. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  610. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  611. # Paint Area Tool
  612. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  613. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  614. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  615. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  616. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  617. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  618. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  619. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  620. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  621. # 2-sided Tool
  622. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  623. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  624. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  625. # Film Tool
  626. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  627. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  628. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  629. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  630. # Panelize Tool
  631. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  632. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  633. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  634. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  635. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  636. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  637. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  638. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  639. # Calculators Tool
  640. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  641. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  642. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  643. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  644. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  645. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  646. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  647. # Transformations Tool
  648. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  649. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  650. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  651. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  652. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  653. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  654. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  655. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  656. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  657. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  658. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  659. # SolderPaste Dispensing Tool
  660. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  661. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  662. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  663. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  664. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  665. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  666. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  667. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  668. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  669. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  670. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  671. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  672. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  673. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  674. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  675. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  676. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  677. # Utilities
  678. # File associations
  679. "fa_excellon": self.ui.util_defaults_form.fa_excellon_group.exc_list_text,
  680. "fa_gcode": self.ui.util_defaults_form.fa_gcode_group.gco_list_text,
  681. # "fa_geometry": self.ui.util_defaults_form.fa_geometry_group.close_paths_cb,
  682. "fa_gerber": self.ui.util_defaults_form.fa_gerber_group.grb_list_text,
  683. "util_autocomplete_keywords": self.ui.util_defaults_form.kw_group.kw_list_text,
  684. }
  685. # ############################
  686. # ### LOAD POSTPROCESSORS ####
  687. # ############################
  688. self.postprocessors = load_postprocessors(self)
  689. for name in list(self.postprocessors.keys()):
  690. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  691. if name.partition('_')[0] == 'Paste':
  692. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  693. continue
  694. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  695. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  696. if name == 'hpgl':
  697. continue
  698. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  699. # ############################
  700. # ### LOAD LANGUAGES ####
  701. # ############################
  702. self.languages = fcTranslate.load_languages()
  703. for name in sorted(self.languages.values()):
  704. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  705. # #################################################################################
  706. # #################### DEFAULTS - PREFERENCES STORAGE #############################
  707. # #################################################################################
  708. self.defaults = LoudDict()
  709. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  710. self.defaults.update({
  711. # Global APP Preferences
  712. "first_run": True,
  713. "units": "IN",
  714. "global_serial": 0,
  715. "global_stats": {},
  716. "global_tabs_detachable": True,
  717. "global_graphic_engine": '3D',
  718. "global_app_level": 'b',
  719. "global_portable": False,
  720. "global_language": 'English',
  721. "global_version_check": True,
  722. "global_send_stats": True,
  723. "global_pan_button": '2',
  724. "global_mselect_key": 'Control',
  725. "global_project_at_startup": False,
  726. "global_systray_icon": True,
  727. "global_project_autohide": True,
  728. "global_toggle_tooltips": True,
  729. "global_worker_number": 2,
  730. "global_tolerance": 0.005,
  731. "global_open_style": True,
  732. "global_delete_confirmation": True,
  733. "global_compression_level": 3,
  734. "global_save_compressed": True,
  735. # Global GUI Preferences
  736. "global_gridx": 0.0393701,
  737. "global_gridy": 0.0393701,
  738. "global_snap_max": 0.001968504,
  739. "global_workspace": False,
  740. "global_workspaceT": "A4P",
  741. "global_grid_context_menu": {
  742. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  743. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  744. },
  745. "global_plot_fill": '#BBF268BF',
  746. "global_plot_line": '#006E20BF',
  747. "global_sel_fill": '#a5a5ffbf',
  748. "global_sel_line": '#0000ffbf',
  749. "global_alt_sel_fill": '#BBF268BF',
  750. "global_alt_sel_line": '#006E20BF',
  751. "global_draw_color": '#FF0000',
  752. "global_sel_draw_color": '#0000FF',
  753. "global_proj_item_color": '#000000',
  754. "global_proj_item_dis_color": '#b7b7cb',
  755. "global_activity_icon": 'Ball green',
  756. "global_toolbar_view": 511,
  757. "global_background_timeout": 300000, # Default value is 5 minutes
  758. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  759. # (python trace only for unknown errors),
  760. # 1 = show trace(show trace always),
  761. # 2 = (For the future).
  762. # Persistence
  763. "global_last_folder": None,
  764. "global_last_save_folder": None,
  765. # Default window geometry
  766. "global_def_win_x": 100,
  767. "global_def_win_y": 100,
  768. "global_def_win_w": 1024,
  769. "global_def_win_h": 650,
  770. "global_def_notebook_width": 1,
  771. # Constants...
  772. "global_defaults_save_period_ms": 20000, # Time between default saves.
  773. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  774. "global_shell_at_startup": False, # Show the shell at startup.
  775. "global_recent_limit": 10, # Max. items in recent list.
  776. "fit_key": 'V',
  777. "zoom_out_key": '-',
  778. "zoom_in_key": '=',
  779. "grid_toggle_key": 'G',
  780. "global_zoom_ratio": 1.5,
  781. "global_point_clipboard_format": "(%.4f, %.4f)",
  782. "global_zdownrate": None,
  783. # General GUI Settings
  784. "global_theme": 'white',
  785. "global_hover": False,
  786. "global_selection_shape": True,
  787. "global_layout": "compact",
  788. "global_cursor_type": "small",
  789. "global_cursor_size": 20,
  790. # Gerber General
  791. "gerber_plot": True,
  792. "gerber_solid": True,
  793. "gerber_multicolored": False,
  794. "gerber_circle_steps": 128,
  795. "gerber_use_buffer_for_union": True,
  796. "gerber_def_units": 'IN',
  797. "gerber_def_zeros": 'L',
  798. # Gerber Options
  799. "gerber_isotooldia": 0.00787402,
  800. "gerber_isopasses": 1,
  801. "gerber_isooverlap": 0.00393701,
  802. "gerber_milling_type": "cl",
  803. "gerber_combine_passes": False,
  804. "gerber_noncoppermargin": 0.00393701,
  805. "gerber_noncopperrounded": False,
  806. "gerber_bboxmargin": 0.00393701,
  807. "gerber_bboxrounded": False,
  808. # Gerber Advanced Options
  809. "gerber_aperture_display": False,
  810. "gerber_aperture_scale_factor": 1.0,
  811. "gerber_aperture_buffer_factor": 0.0,
  812. "gerber_follow": False,
  813. "gerber_tool_type": 'circular',
  814. "gerber_vtipdia": 0.1,
  815. "gerber_vtipangle": 30,
  816. "gerber_vcutz": -0.05,
  817. "gerber_buffering": "full",
  818. "gerber_simplification": False,
  819. "gerber_simp_tolerance": 0.0005,
  820. # Gerber Export
  821. "gerber_exp_units": 'IN',
  822. "gerber_exp_integer": 2,
  823. "gerber_exp_decimals": 4,
  824. "gerber_exp_zeros": 'L',
  825. # Gerber Editor
  826. "gerber_editor_sel_limit": 30,
  827. "gerber_editor_newcode": 10,
  828. "gerber_editor_newsize": 0.8,
  829. "gerber_editor_newtype": 'C',
  830. "gerber_editor_newdim": "0.5, 0.5",
  831. "gerber_editor_array_size": 5,
  832. "gerber_editor_lin_axis": 'X',
  833. "gerber_editor_lin_pitch": 1,
  834. "gerber_editor_lin_angle": 0.0,
  835. "gerber_editor_circ_dir": 'CW',
  836. "gerber_editor_circ_angle": 0.0,
  837. "gerber_editor_scale_f": 1.0,
  838. "gerber_editor_buff_f": 0.1,
  839. "gerber_editor_ma_low": 0.0,
  840. "gerber_editor_ma_high": 1.0,
  841. # Excellon General
  842. "excellon_plot": True,
  843. "excellon_solid": True,
  844. "excellon_format_upper_in": 2,
  845. "excellon_format_lower_in": 4,
  846. "excellon_format_upper_mm": 3,
  847. "excellon_format_lower_mm": 3,
  848. "excellon_zeros": "L",
  849. "excellon_units": "INCH",
  850. "excellon_update": True,
  851. "excellon_optimization_type": 'B',
  852. "excellon_search_time": 3,
  853. # Excellon Options
  854. "excellon_drillz": -0.0590551,
  855. "excellon_travelz": 0.0787402,
  856. "excellon_endz": 0.5,
  857. "excellon_feedrate": 3.14961,
  858. "excellon_spindlespeed": None,
  859. "excellon_dwell": False,
  860. "excellon_dwelltime": 1,
  861. "excellon_toolchange": False,
  862. "excellon_toolchangez": 0.5,
  863. "excellon_ppname_e": 'default',
  864. "excellon_tooldia": 0.0314961,
  865. "excellon_slot_tooldia": 0.0708661,
  866. "excellon_gcode_type": "drills",
  867. # Excellon Advanced Options
  868. "excellon_offset": 0.0,
  869. "excellon_toolchangexy": "0.0, 0.0",
  870. "excellon_startz": None,
  871. "excellon_feedrate_rapid": 31.4961,
  872. "excellon_z_pdepth": -0.02,
  873. "excellon_feedrate_probe": 3.14961,
  874. "excellon_spindledir": 'CW',
  875. "excellon_f_plunge": False,
  876. "excellon_f_retract": False,
  877. # Excellon Export
  878. "excellon_exp_units": 'INCH',
  879. "excellon_exp_format": 'ndec',
  880. "excellon_exp_integer": 2,
  881. "excellon_exp_decimals": 4,
  882. "excellon_exp_zeros": 'LZ',
  883. "excellon_exp_slot_type": 'routing',
  884. # Excellon Editor
  885. "excellon_editor_sel_limit": 30,
  886. "excellon_editor_newdia": 0.039,
  887. "excellon_editor_array_size": 5,
  888. "excellon_editor_lin_dir": 'X',
  889. "excellon_editor_lin_pitch": 0.1,
  890. "excellon_editor_lin_angle": 0.0,
  891. "excellon_editor_circ_dir": 'CW',
  892. "excellon_editor_circ_angle": 12,
  893. # Excellon Slots
  894. "excellon_editor_slot_direction": 'X',
  895. "excellon_editor_slot_angle": 0.0,
  896. "excellon_editor_slot_length": 5.0,
  897. # Excellon Slot Array
  898. "excellon_editor_slot_array_size": 5,
  899. "excellon_editor_slot_lin_dir": 'X',
  900. "excellon_editor_slot_lin_pitch": 0.1,
  901. "excellon_editor_slot_lin_angle": 0.0,
  902. "excellon_editor_slot_circ_dir": 'CW',
  903. "excellon_editor_slot_circ_angle": 0.0,
  904. # Geometry General
  905. "geometry_plot": True,
  906. "geometry_circle_steps": 128,
  907. "geometry_cnctooldia": "0.0944882",
  908. # Geometry Options
  909. "geometry_cutz": -0.0944882,
  910. "geometry_vtipdia": 0.1,
  911. "geometry_vtipangle": 30,
  912. "geometry_multidepth": False,
  913. "geometry_depthperpass": 0.0314961,
  914. "geometry_travelz": 0.0787402,
  915. "geometry_toolchange": False,
  916. "geometry_toolchangez": 0.5,
  917. "geometry_endz": 0.5,
  918. "geometry_feedrate": 3.14961,
  919. "geometry_feedrate_z": 3.14961,
  920. "geometry_spindlespeed": None,
  921. "geometry_dwell": False,
  922. "geometry_dwelltime": 1,
  923. "geometry_ppname_g": 'default',
  924. # Geometry Advanced Options
  925. "geometry_toolchangexy": "0.0, 0.0",
  926. "geometry_startz": None,
  927. "geometry_feedrate_rapid": 3.14961,
  928. "geometry_extracut": False,
  929. "geometry_z_pdepth": -0.02,
  930. "geometry_f_plunge": False,
  931. "geometry_spindledir": 'CW',
  932. "geometry_feedrate_probe": 3.14961,
  933. "geometry_segx": 0.0,
  934. "geometry_segy": 0.0,
  935. # Geometry Editor
  936. "geometry_editor_sel_limit": 30,
  937. "geometry_editor_milling_type": "cl",
  938. # CNC Job General
  939. "cncjob_plot": True,
  940. "cncjob_plot_kind": 'all',
  941. "cncjob_annotation": True,
  942. "cncjob_tooldia": 0.0393701,
  943. "cncjob_coords_type": "G90",
  944. "cncjob_coords_decimals": 4,
  945. "cncjob_fr_decimals": 2,
  946. "cncjob_steps_per_circle": 128,
  947. # CNC Job Options
  948. "cncjob_prepend": "",
  949. "cncjob_append": "",
  950. # CNC Job Advanced Options
  951. "cncjob_toolchange_macro": "",
  952. "cncjob_toolchange_macro_enable": False,
  953. "cncjob_annotation_fontsize": 9,
  954. "cncjob_annotation_fontcolor": '#990000',
  955. # NCC Tool
  956. "tools_ncctools": "0.0393701, 0.019685",
  957. "tools_nccorder": 'rev',
  958. "tools_nccoverlap": 0.015748,
  959. "tools_nccmargin": 0.0393701,
  960. "tools_nccmethod": "seed",
  961. "tools_nccconnect": True,
  962. "tools_ncccontour": True,
  963. "tools_nccrest": False,
  964. "tools_ncc_offset_choice": False,
  965. "tools_ncc_offset_value": 0.0000,
  966. "tools_nccref": 'itself',
  967. "tools_ncc_plotting": 'normal',
  968. "tools_nccmilling_type": 'cl',
  969. "tools_ncctool_type": 'V',
  970. "tools_ncccutz": -0.001968504,
  971. "tools_ncctipdia": 0.00393701,
  972. "tools_ncctipangle": 30,
  973. # Cutout Tool
  974. "tools_cutouttooldia": 0.0944882,
  975. "tools_cutoutkind": "single",
  976. "tools_cutoutmargin": 0.00393701,
  977. "tools_cutoutgapsize": 0.15748,
  978. "tools_gaps_ff": "4",
  979. "tools_cutout_convexshape": False,
  980. # Paint Tool
  981. "tools_painttooldia": 0.023622,
  982. "tools_paintorder": 'rev',
  983. "tools_paintoverlap": 0.015748,
  984. "tools_paintmargin": 0.0,
  985. "tools_paintmethod": "seed",
  986. "tools_selectmethod": "all",
  987. "tools_pathconnect": True,
  988. "tools_paintcontour": True,
  989. "tools_paint_plotting": 'normal',
  990. # 2-Sided Tool
  991. "tools_2sided_mirror_axis": "X",
  992. "tools_2sided_axis_loc": "point",
  993. "tools_2sided_drilldia": 0.11811,
  994. # Film Tool
  995. "tools_film_type": 'neg',
  996. "tools_film_boundary": 0.0393701,
  997. "tools_film_scale": 0,
  998. "tools_film_color": '#000000',
  999. # Panel Tool
  1000. "tools_panelize_spacing_columns": 0,
  1001. "tools_panelize_spacing_rows": 0,
  1002. "tools_panelize_columns": 1,
  1003. "tools_panelize_rows": 1,
  1004. "tools_panelize_constrain": False,
  1005. "tools_panelize_constrainx": 0.0,
  1006. "tools_panelize_constrainy": 0.0,
  1007. "tools_panelize_panel_type": 'gerber',
  1008. # Calculators Tool
  1009. "tools_calc_vshape_tip_dia": 0.007874,
  1010. "tools_calc_vshape_tip_angle": 30,
  1011. "tools_calc_vshape_cut_z": 0.000787,
  1012. "tools_calc_electro_length": 10.0,
  1013. "tools_calc_electro_width": 10.0,
  1014. "tools_calc_electro_cdensity": 13.0,
  1015. "tools_calc_electro_growth": 10.0,
  1016. # Transform Tool
  1017. "tools_transform_rotate": 90,
  1018. "tools_transform_skew_x": 0.0,
  1019. "tools_transform_skew_y": 0.0,
  1020. "tools_transform_scale_x": 1.0,
  1021. "tools_transform_scale_y": 1.0,
  1022. "tools_transform_scale_link": True,
  1023. "tools_transform_scale_reference": True,
  1024. "tools_transform_offset_x": 0.0,
  1025. "tools_transform_offset_y": 0.0,
  1026. "tools_transform_mirror_reference": False,
  1027. "tools_transform_mirror_point": (0, 0),
  1028. # SolderPaste Tool
  1029. "tools_solderpaste_tools": "0.0393701, 0.011811",
  1030. "tools_solderpaste_new": 0.011811,
  1031. "tools_solderpaste_z_start": 0.00019685039,
  1032. "tools_solderpaste_z_dispense": 0.00393701,
  1033. "tools_solderpaste_z_stop": 0.00019685039,
  1034. "tools_solderpaste_z_travel": 0.00393701,
  1035. "tools_solderpaste_z_toolchange": 0.0393701,
  1036. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  1037. "tools_solderpaste_frxy": 3.0,
  1038. "tools_solderpaste_frz": 3.0,
  1039. "tools_solderpaste_frz_dispense": 0.0393701,
  1040. "tools_solderpaste_speedfwd": 20,
  1041. "tools_solderpaste_dwellfwd": 1,
  1042. "tools_solderpaste_speedrev": 10,
  1043. "tools_solderpaste_dwellrev": 1,
  1044. "tools_solderpaste_pp": 'Paste_1',
  1045. # Subtract Tool
  1046. "tools_sub_close_paths": True,
  1047. # Utilities
  1048. # file associations
  1049. "fa_excellon": 'drd, drl, exc, ncd, tap, xln',
  1050. "fa_gcode": 'cnc, din, dnc, ecs, eia, fan, fgc, fnc, gc, gcd, gcode, h, hnc, i, min, mpf, mpr, nc, ncc, '
  1051. 'ncg, ncp, out, plt, ply, rol, sbp, tap, xpi',
  1052. "fa_gerber": 'art, bot, bsm, cmp, crc, crs, dim, g4, gb0, gb1, gb2, gb3, gb5, gb6, gb7, gb8, gb9, gbd, '
  1053. 'gbl, gbo, gbp, gbr, gbs, gdo, ger, gko, gm1, gm2, gm3, grb, gtl, gto, gtp, gts, ly15, ly2, '
  1054. 'mil, pho, plc, pls, smb, smt, sol, spb, spt, ssb, sst, stc, sts, top, tsm',
  1055. # Keyword list
  1056. "util_autocomplete_keywords": 'Desktop, Documents, FlatConfig, FlatPrj, Marius, My Documents, Paste_1, '
  1057. 'Repetier, Roland_MDX_20, Users, Toolchange_Custom, Toolchange_Probe_MACH3, '
  1058. 'Toolchange_manual, Users, all, angle_x, angle_y, axis, auto, axisoffset, '
  1059. 'box, center_x, center_y, columns, combine, connect, contour, default, '
  1060. 'depthperpass, dia, diatol, dist, drilled_dias, drillz, dwell, dwelltime, '
  1061. 'feedrate_z, grbl_11, grbl_laser, gridoffsety, gridx, gridy, has_offset, '
  1062. 'holes, hpgl, iso_type, line_xyz, margin, marlin, method, milled_dias, '
  1063. 'minoffset, multidepth, name, offset, opt_type, order, outname, overlap, '
  1064. 'passes, postamble, pp, ppname_e, ppname_g, preamble, radius, ref, rest, '
  1065. 'rows, shellvar_, scale_factor, spacing_columns, spacing_rows, spindlespeed, '
  1066. 'toolchange_xy, use_threads, value, x, x0, x1, y, y0, y1, z_cut, z_move',
  1067. "script_autocompleter": True,
  1068. "script_text": "",
  1069. "script_plot": True,
  1070. "script_source_file": "",
  1071. "document_autocompleter": False,
  1072. "document_text": "",
  1073. "document_plot": True,
  1074. "document_source_file": "",
  1075. "document_font_color": '#000000',
  1076. "document_sel_color": '#0055ff',
  1077. "document_font_size": 6,
  1078. "document_tab_size": 80,
  1079. })
  1080. # ############################################################
  1081. # ############### Load defaults from file ####################
  1082. # ############################################################
  1083. if user_defaults:
  1084. self.load_defaults(filename='current_defaults')
  1085. # #############################################################
  1086. # ############## APPLY APP LANGUAGE ###########################
  1087. # #############################################################
  1088. ret_val = fcTranslate.apply_language('strings')
  1089. if ret_val == "no language":
  1090. self.inform.emit('[ERROR] %s' %
  1091. _("Could not find the Language files. The App strings are missing."))
  1092. log.debug("Could not find the Language files. The App strings are missing.")
  1093. else:
  1094. # make the current language the current selection on the language combobox
  1095. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1096. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1097. # ##############################################################
  1098. # ################# CREATE UNIQUE SERIAL NUMBER ################
  1099. # ##############################################################
  1100. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1101. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1102. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  1103. self.save_defaults(silent=True, first_time=True)
  1104. self.propagate_defaults(silent=True)
  1105. self.restore_main_win_geom()
  1106. # def auto_save_defaults():
  1107. # try:
  1108. # self.save_defaults(silent=True)
  1109. # self.propagate_defaults(silent=True)
  1110. # finally:
  1111. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1112. # the following lines activates automatic defaults save
  1113. # if user_defaults:
  1114. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1115. # self.options_form = PreferencesUI()
  1116. self.options_form_fields = {
  1117. "units": self.ui.general_options_form.general_app_group.units_radio,
  1118. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  1119. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  1120. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  1121. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  1122. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  1123. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  1124. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  1125. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  1126. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  1127. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  1128. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  1129. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  1130. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  1131. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  1132. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  1133. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  1134. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  1135. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  1136. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  1137. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  1138. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  1139. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  1140. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  1141. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  1142. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  1143. "excellon_endz": self.ui.excellon_options_form.excellon_opt_group.eendz_entry,
  1144. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  1145. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  1146. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  1147. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  1148. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  1149. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  1150. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  1151. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  1152. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1153. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  1154. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  1155. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  1156. "excellon_spindledir": self.ui.excellon_options_form.excellon_adv_opt_group.spindledir_radio,
  1157. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  1158. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  1159. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  1160. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  1161. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  1162. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  1163. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  1164. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  1165. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  1166. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  1167. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  1168. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  1169. "geometry_endz": self.ui.geometry_options_form.geometry_opt_group.gendz_entry,
  1170. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  1171. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  1172. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  1173. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  1174. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1175. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  1176. "geometry_spindledir": self.ui.geometry_options_form.geometry_adv_opt_group.spindledir_radio,
  1177. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  1178. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  1179. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  1180. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  1181. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  1182. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  1183. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  1184. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  1185. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  1186. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  1187. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  1188. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  1189. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  1190. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  1191. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  1192. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  1193. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  1194. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  1195. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  1196. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  1197. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  1198. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  1199. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  1200. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  1201. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  1202. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  1203. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  1204. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  1205. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  1206. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  1207. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  1208. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  1209. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  1210. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  1211. }
  1212. for name in list(self.postprocessors.keys()):
  1213. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1214. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1215. self.options = LoudDict()
  1216. self.options.set_change_callback(self.on_options_dict_change)
  1217. self.options.update({
  1218. "units": "IN",
  1219. "global_gridx": 1.0,
  1220. "global_gridy": 1.0,
  1221. "global_snap_max": 0.05,
  1222. "global_background_timeout": 300000, # Default value is 5 minutes
  1223. "global_verbose_error_level": 0, # Shell verbosity:
  1224. # 0 = default(python trace only for unknown errors),
  1225. # 1 = show trace(show trace allways), 2 = (For the future).
  1226. "gerber_plot": True,
  1227. "gerber_solid": True,
  1228. "gerber_multicolored": False,
  1229. "gerber_isotooldia": 0.016,
  1230. "gerber_isopasses": 1,
  1231. "gerber_isooverlap": 0.15,
  1232. "gerber_combine_passes": True,
  1233. "gerber_noncoppermargin": 0.0,
  1234. "gerber_noncopperrounded": False,
  1235. "gerber_bboxmargin": 0.0,
  1236. "gerber_bboxrounded": False,
  1237. "excellon_plot": True,
  1238. "excellon_solid": False,
  1239. "excellon_format_upper_in": 2,
  1240. "excellon_format_lower_in": 4,
  1241. "excellon_format_upper_mm": 3,
  1242. "excellon_format_lower_mm": 3,
  1243. "excellon_units": 'INCH',
  1244. "excellon_optimization_type": 'B',
  1245. "excellon_search_time": 3,
  1246. "excellon_zeros": "L",
  1247. "excellon_drillz": -0.1,
  1248. "excellon_travelz": 0.1,
  1249. "excellon_feedrate": 3.0,
  1250. "excellon_feedrate_rapid": 3.0,
  1251. "excellon_spindlespeed": None,
  1252. "excellon_spindledir": 'CW',
  1253. "excellon_dwell": True,
  1254. "excellon_dwelltime": 1000,
  1255. "excellon_toolchange": False,
  1256. "excellon_toolchangez": 1.0,
  1257. "excellon_toolchangexy": "0.0, 0.0",
  1258. "excellon_tooldia": 0.016,
  1259. "excellon_ppname_e": 'default',
  1260. "excellon_f_plunge": False,
  1261. "excellon_startz": None,
  1262. "excellon_endz": 2.0,
  1263. "geometry_plot": True,
  1264. "geometry_segx": 0.0,
  1265. "geometry_segy": 0.0,
  1266. "geometry_cutz": -0.002,
  1267. "geometry_vtipdia": 0.1,
  1268. "geometry_vtipangle": 30,
  1269. "geometry_travelz": 0.1,
  1270. "geometry_feedrate": 3.0,
  1271. "geometry_feedrate_z": 3.0,
  1272. "geometry_feedrate_rapid": 3.0,
  1273. "geometry_spindlespeed": None,
  1274. "geometry_spindledir": 'CW',
  1275. "geometry_dwell": True,
  1276. "geometry_dwelltime": 1000,
  1277. "geometry_cnctooldia": 0.016,
  1278. "geometry_toolchange": False,
  1279. "geometry_toolchangez": 2.0,
  1280. "geometry_toolchangexy": "0.0, 0.0",
  1281. "geometry_startz": None,
  1282. "geometry_endz": 2.0,
  1283. "geometry_ppname_g": "default",
  1284. "geometry_f_plunge": False,
  1285. "geometry_depthperpass": 0.002,
  1286. "geometry_multidepth": False,
  1287. "geometry_extracut": False,
  1288. "cncjob_plot": True,
  1289. "cncjob_tooldia": 0.016,
  1290. "cncjob_prepend": "",
  1291. "cncjob_append": "",
  1292. "tools_ncctools": "1.0, 0.5",
  1293. "tools_nccoverlap": 0.4,
  1294. "tools_nccmargin": 1,
  1295. "tools_cutouttooldia": 0.07,
  1296. "tools_cutoutmargin": 0.1,
  1297. "tools_cutoutgapsize": 0.15,
  1298. "tools_gaps_ff": "8",
  1299. "tools_painttooldia": 0.07,
  1300. "tools_paintoverlap": 0.15,
  1301. "tools_paintmargin": 0.0,
  1302. "tools_paintmethod": "seed",
  1303. "tools_selectmethod": "single",
  1304. "tools_pathconnect": True,
  1305. "tools_paintcontour": True,
  1306. "tools_2sided_mirror_axis": "X",
  1307. "tools_2sided_axis_loc": 'point',
  1308. "tools_2sided_drilldia": 1,
  1309. "tools_film_type": 'neg',
  1310. "tools_film_boundary": 1,
  1311. "tools_film_scale": 0,
  1312. "tools_panelize_spacing_columns": 0,
  1313. "tools_panelize_spacing_rows": 0,
  1314. "tools_panelize_columns": 1,
  1315. "tools_panelize_rows": 1,
  1316. "tools_panelize_constrain": False,
  1317. "tools_panelize_constrainx": 0.0,
  1318. "tools_panelize_constrainy": 0.0,
  1319. "script_text": "",
  1320. "script_plot": False,
  1321. "script_source_file": "",
  1322. "document_text": "",
  1323. "document_plot": False,
  1324. "document_source_file": "",
  1325. })
  1326. self.options.update(self.defaults) # Copy app defaults to project options
  1327. self.gen_form = None
  1328. self.ger_form = None
  1329. self.exc_form = None
  1330. self.geo_form = None
  1331. self.cnc_form = None
  1332. self.tools_form = None
  1333. self.fa_form = None
  1334. self.on_options_combo_change(0) # Will show the initial form
  1335. # ################################
  1336. # ### Initialize the color box's color in Preferences -> Global -> Color
  1337. # Init Plot Colors
  1338. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  1339. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  1340. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  1341. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  1342. int(self.defaults['global_plot_fill'][7:9], 16))
  1343. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  1344. int(self.defaults['global_plot_fill'][7:9], 16))
  1345. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  1346. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  1347. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  1348. # Init Left-Right Selection colors
  1349. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  1350. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  1351. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  1352. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1353. int(self.defaults['global_sel_fill'][7:9], 16))
  1354. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1355. int(self.defaults['global_sel_fill'][7:9], 16))
  1356. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1357. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1358. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  1359. # Init Right-Left Selection colors
  1360. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1361. self.defaults['global_alt_sel_fill'])
  1362. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1363. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  1364. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1365. int(self.defaults['global_sel_fill'][7:9], 16))
  1366. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1367. int(self.defaults['global_sel_fill'][7:9], 16))
  1368. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1369. self.defaults['global_alt_sel_line'])
  1370. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1371. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  1372. # Init Draw color and Selection Draw Color
  1373. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1374. self.defaults['global_draw_color'])
  1375. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1376. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1377. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1378. self.defaults['global_sel_draw_color'])
  1379. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1380. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1381. # Init Project Items color
  1382. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1383. self.defaults['global_proj_item_color'])
  1384. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1385. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1386. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1387. self.defaults['global_proj_item_dis_color'])
  1388. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1389. "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1390. # Init the Annotation CNC Job color
  1391. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  1392. self.defaults['cncjob_annotation_fontcolor'])
  1393. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  1394. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  1395. # Init the Tool Film color
  1396. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  1397. self.defaults['tools_film_color'])
  1398. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  1399. "background-color:%s" % str(self.defaults['tools_film_color'])[:7])
  1400. # ### End of Data ####
  1401. # ##############################################
  1402. # ######### SETUP OBJECT COLLECTION ############
  1403. # ##############################################
  1404. self.collection = ObjectCollection(self)
  1405. self.ui.project_tab_layout.addWidget(self.collection.view)
  1406. # ### Adjust tabs width ## ##
  1407. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1408. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1409. self.collection.view.setMinimumWidth(290)
  1410. self.log.debug("Finished creating Object Collection.")
  1411. # ###############################################
  1412. # ############# SETUP Plot Area #################
  1413. # ###############################################
  1414. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  1415. if self.defaults["global_graphic_engine"] == '3D':
  1416. self.is_legacy = False
  1417. else:
  1418. self.is_legacy = True
  1419. # Matplotlib axis
  1420. self.axes = None
  1421. if show_splash:
  1422. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1423. "Canvas initialization started."),
  1424. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1425. color=QtGui.QColor("gray"))
  1426. start_plot_time = time.time() # debug
  1427. self.plotcanvas = None
  1428. self.app_cursor = None
  1429. self.hover_shapes = None
  1430. self.on_plotcanvas_setup()
  1431. end_plot_time = time.time()
  1432. self.used_time = end_plot_time - start_plot_time
  1433. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1434. if show_splash:
  1435. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1436. "Canvas initialization started.\n"
  1437. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1438. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1439. color=QtGui.QColor("gray"))
  1440. self.ui.splitter.setStretchFactor(1, 2)
  1441. # #################################################################
  1442. # ####################### SYS TRAY ################################
  1443. # #################################################################
  1444. if self.defaults["global_systray_icon"]:
  1445. self.parent_w = QtWidgets.QWidget()
  1446. if self.cmd_line_headless == 1:
  1447. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1448. headless=True,
  1449. parent=self.parent_w)
  1450. else:
  1451. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1452. parent=self.parent_w)
  1453. # ###############################################
  1454. # ############# Worker SETUP ####################
  1455. # ###############################################
  1456. if self.defaults["global_worker_number"]:
  1457. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1458. else:
  1459. self.workers = WorkerStack(workers_number=2)
  1460. self.worker_task.connect(self.workers.add_task)
  1461. self.log.debug("Finished creating Workers crew.")
  1462. # ################################################
  1463. # ############### Activity Monitor ###############
  1464. # ################################################
  1465. if self.defaults["global_activity_icon"] == "Ball green":
  1466. icon = 'share/active_2_static.png'
  1467. movie = "share/active_2.gif"
  1468. elif self.defaults["global_activity_icon"] == "Ball black":
  1469. icon = 'share/active_static.png'
  1470. movie = "share/active.gif"
  1471. elif self.defaults["global_activity_icon"] == "Arrow green":
  1472. icon = 'share/active_3_static.png'
  1473. movie = "share/active_3.gif"
  1474. elif self.defaults["global_activity_icon"] == "Eclipse green":
  1475. icon = 'share/active_4_static.png'
  1476. movie = "share/active_4.gif"
  1477. else:
  1478. icon = 'share/active_static.png'
  1479. movie = "share/active.gif"
  1480. self.activity_view = FlatCAMActivityView(icon=icon, movie=movie)
  1481. self.ui.infobar.addWidget(self.activity_view)
  1482. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  1483. # ################################################
  1484. # ############### Signal handling ################
  1485. # ################################################
  1486. # ############# Custom signals ##################
  1487. # signal for displaying messages in status bar
  1488. self.inform.connect(self.info)
  1489. # signal to be called when the app is quiting
  1490. self.app_quit.connect(self.quit_application)
  1491. self.message.connect(self.message_dialog)
  1492. self.progress.connect(self.set_progress_bar)
  1493. # signals that are emitted when object state changes
  1494. self.object_created.connect(self.on_object_created)
  1495. self.object_changed.connect(self.on_object_changed)
  1496. self.object_plotted.connect(self.on_object_plotted)
  1497. self.plots_updated.connect(self.on_plots_updated)
  1498. # signals emitted when file state change
  1499. self.file_opened.connect(self.register_recent)
  1500. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1501. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1502. # ############# Standard signals ###################
  1503. # ### Menu
  1504. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1505. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1506. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1507. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1508. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  1509. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1510. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1511. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1512. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1513. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1514. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1515. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1516. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1517. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1518. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1519. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1520. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1521. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1522. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1523. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1524. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1525. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1526. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1527. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1528. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1529. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1530. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1531. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1532. self.ui.menufile_exit.triggered.connect(self.final_save)
  1533. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1534. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1535. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1536. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1537. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1538. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1539. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1540. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1541. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1542. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1543. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1544. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1545. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1546. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1547. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1548. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1549. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1550. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1551. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1552. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1553. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1554. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1555. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1556. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1557. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1558. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1559. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1560. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1561. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1562. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1563. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1564. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1565. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1566. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1567. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1568. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1569. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1570. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1571. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1572. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  1573. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1574. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1575. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1576. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1577. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1578. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1579. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1580. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1581. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1582. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1583. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1584. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1585. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1586. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1587. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1588. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1589. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1590. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1591. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1592. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1593. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1594. # ToolBar signals
  1595. self.connect_toolbar_signals()
  1596. # Notebook signals
  1597. # make the right click on the notebook tab connect to a function
  1598. self.ui.notebook.setupContextMenu()
  1599. self.ui.notebook.addContextMenu(
  1600. _("Detachable Tabs"), self.on_notebook_tab_rmb_click,
  1601. initial_checked=self.defaults["global_tabs_detachable"])
  1602. # activate initial state
  1603. self.on_notebook_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1604. # Context Menu
  1605. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1606. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1607. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1608. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1609. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1610. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1611. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1612. self.ui.clearplot.triggered.connect(self.clear_plots)
  1613. self.ui.replot.triggered.connect(self.plot_all)
  1614. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1615. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1616. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1617. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1618. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1619. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1620. # Preferences Plot Area TAB
  1621. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1622. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1623. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1624. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1625. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1626. # ##############################
  1627. # ### GUI PREFERENCES SIGNALS ##
  1628. # ##############################
  1629. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  1630. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1631. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1632. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1633. )
  1634. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1635. lambda: self.on_toggle_units(no_pref=False))
  1636. # ###############################################################
  1637. # ################### GUI COLORS SIGNALS ########################
  1638. # ###############################################################
  1639. # Setting plot colors signals
  1640. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1641. self.on_pf_color_entry)
  1642. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1643. self.on_pf_color_button)
  1644. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1645. self.on_pf_color_spinner)
  1646. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1647. self.on_pf_color_slider)
  1648. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1649. self.on_pl_color_entry)
  1650. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1651. self.on_pl_color_button)
  1652. # Setting selection (left - right) colors signals
  1653. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1654. self.on_sf_color_entry)
  1655. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1656. self.on_sf_color_button)
  1657. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1658. self.on_sf_color_spinner)
  1659. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1660. self.on_sf_color_slider)
  1661. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1662. self.on_sl_color_entry)
  1663. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1664. self.on_sl_color_button)
  1665. # Setting selection (right - left) colors signals
  1666. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1667. self.on_alt_sf_color_entry)
  1668. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1669. self.on_alt_sf_color_button)
  1670. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1671. self.on_alt_sf_color_spinner)
  1672. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1673. self.on_alt_sf_color_slider)
  1674. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1675. self.on_alt_sl_color_entry)
  1676. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1677. self.on_alt_sl_color_button)
  1678. # Setting Editor Draw colors signals
  1679. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1680. self.on_draw_color_entry)
  1681. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1682. self.on_draw_color_button)
  1683. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1684. self.on_sel_draw_color_entry)
  1685. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1686. self.on_sel_draw_color_button)
  1687. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1688. self.on_proj_color_entry)
  1689. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1690. self.on_proj_color_button)
  1691. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1692. self.on_proj_color_dis_entry)
  1693. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1694. self.on_proj_color_dis_button)
  1695. # ########## workspace setting signals ###########
  1696. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1697. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1698. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1699. # #################################################
  1700. # ############ GUI SETTINGS SIGNALS ###############
  1701. # #################################################
  1702. self.ui.general_defaults_form.general_gui_set_group.theme_radio.activated_custom.connect(self.on_theme_change)
  1703. self.ui.general_defaults_form.general_gui_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  1704. # ########## CNC Job related signals #############
  1705. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1706. self.on_cnc_custom_parameters)
  1707. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.editingFinished.connect(
  1708. self.on_annotation_fontcolor_entry)
  1709. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.clicked.connect(
  1710. self.on_annotation_fontcolor_button)
  1711. # ########## Tools related signals #############
  1712. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1713. self.on_film_color_entry)
  1714. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1715. self.on_film_color_button)
  1716. # portability changed signal
  1717. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1718. # Object list
  1719. self.collection.view.activated.connect(self.on_row_activated)
  1720. self.object_status_changed.connect(self.on_collection_updated)
  1721. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1722. self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1723. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1724. # Export Excellon parameters.
  1725. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1726. self.on_update_exc_export
  1727. )
  1728. # call it once to make sure it is updated at startup
  1729. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1730. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1731. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1732. self.on_excellon_defaults_button)
  1733. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1734. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1735. self.on_excellon_options_button)
  1736. # when there are arguments at application startup this get launched
  1737. self.args_at_startup[list].connect(self.on_startup_args)
  1738. # ##############################################################
  1739. # ############### FILE ASSOCIATIONS SIGNALS ####################
  1740. # ##############################################################
  1741. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1742. lambda: self.restore_extensions(ext_type='excellon'))
  1743. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1744. lambda: self.restore_extensions(ext_type='gcode'))
  1745. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1746. lambda: self.restore_extensions(ext_type='gerber'))
  1747. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1748. lambda: self.delete_all_extensions(ext_type='excellon'))
  1749. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1750. lambda: self.delete_all_extensions(ext_type='gcode'))
  1751. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1752. lambda: self.delete_all_extensions(ext_type='gerber'))
  1753. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1754. lambda: self.add_extension(ext_type='excellon'))
  1755. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1756. lambda: self.add_extension(ext_type='gcode'))
  1757. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1758. lambda: self.add_extension(ext_type='gerber'))
  1759. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1760. lambda: self.del_extension(ext_type='excellon'))
  1761. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1762. lambda: self.del_extension(ext_type='gcode'))
  1763. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1764. lambda: self.del_extension(ext_type='gerber'))
  1765. # connect the 'Apply' buttons from the Preferences/File Associations
  1766. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1767. lambda: self.on_register_files(obj_type='excellon'))
  1768. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1769. lambda: self.on_register_files(obj_type='gcode'))
  1770. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1771. lambda: self.on_register_files(obj_type='gerber'))
  1772. # ##############################################################
  1773. # ###################### KEYWORDS SIGNALS ######################
  1774. # ##############################################################
  1775. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1776. lambda: self.restore_extensions(ext_type='keyword'))
  1777. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1778. lambda: self.delete_all_extensions(ext_type='keyword'))
  1779. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1780. lambda: self.add_extension(ext_type='keyword'))
  1781. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1782. lambda: self.del_extension(ext_type='keyword'))
  1783. # splash screen button signal
  1784. self.ui.general_defaults_form.general_gui_set_group.splash_cb.stateChanged.connect(self.on_splash_changed)
  1785. # connect the abort_all_tasks related slots to the related signals
  1786. self.proc_container.idle_flag.connect(self.app_is_idle)
  1787. # #####################################################################################
  1788. # ########### FINISHED CONNECTING SIGNALS #############################################
  1789. # #####################################################################################
  1790. self.log.debug("Finished connecting Signals.")
  1791. # #####################################################################################
  1792. # ########################## Other setups #############################################
  1793. # #####################################################################################
  1794. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  1795. # depending on from where those tools are called different actions can be done
  1796. self.call_source = 'app'
  1797. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1798. self.tool_tab_locked = False
  1799. # decide if to show or hide the Notebook side of the screen at startup
  1800. if self.defaults["global_project_at_startup"] is True:
  1801. self.ui.splitter.setSizes([1, 1])
  1802. else:
  1803. self.ui.splitter.setSizes([0, 1])
  1804. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1805. self.setup_obj_classes()
  1806. self.setup_recent_items()
  1807. self.setup_component_editor()
  1808. # this does not work in Legacy Mode
  1809. if self.is_legacy is True:
  1810. self.ui.general_defaults_form.general_gui_group.workspace_cb.setDisabled(True)
  1811. self.ui.general_defaults_form.general_gui_group.workspace_type_lbl.setDisabled(True)
  1812. self.ui.general_defaults_form.general_gui_group.wk_cb.setDisabled(True)
  1813. # #####################################################################################
  1814. # ######################### Auto-complete KEYWORDS ####################################
  1815. # #####################################################################################
  1816. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1817. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1818. 'delete', 'drillcncjob', 'export_gcode', 'export_svg', 'ext', 'exteriors', 'follow',
  1819. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1820. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1821. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1822. 'mirror', 'ncc',
  1823. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1824. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'origin',
  1825. 'paint', 'pan', 'panel', 'panelize', 'plot_all', 'plot_objects', 'quit_flatcam',
  1826. 'save', 'save_project',
  1827. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_sys',
  1828. 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1829. 'version', 'write_gcode'
  1830. ]
  1831. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'Marius', 'My Documents', 'Paste_1',
  1832. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  1833. 'Toolchange_manual', 'Users', 'all', 'angle_x', 'angle_y', 'auto', 'axis',
  1834. 'axisoffset',
  1835. 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect', 'contour', 'default',
  1836. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dwell',
  1837. 'dwelltime', 'feedrate_z', 'grbl_11', 'grbl_laser', 'gridoffsety', 'gridx', 'gridy',
  1838. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  1839. 'milled_dias', 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order',
  1840. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  1841. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  1842. 'spacing_columns',
  1843. 'spacing_rows', 'spindlespeed', 'toolchange_xy', 'use_threads', 'value', 'x',
  1844. 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1845. ]
  1846. self.tcl_keywords = [
  1847. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1848. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1849. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1850. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1851. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1852. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1853. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1854. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1855. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1856. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1857. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1858. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1859. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1860. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1861. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1862. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1863. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1864. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1865. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1866. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1867. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1868. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1869. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1870. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1871. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1872. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1873. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1874. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1875. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1876. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1877. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1878. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1879. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1880. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1881. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1882. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1883. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1884. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1885. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1886. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1887. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1888. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1889. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1890. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1891. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1892. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1893. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1894. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1895. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1896. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1897. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1898. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1899. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1900. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1901. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1902. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1903. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1904. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1905. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1906. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1907. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1908. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1909. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1910. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1911. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1912. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1913. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1914. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1915. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1916. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1917. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1918. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1919. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1920. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1921. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1922. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1923. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1924. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1925. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1926. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1927. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1928. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1929. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1930. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1931. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1932. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1933. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1934. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1935. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1936. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1937. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1938. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1939. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1940. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1941. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1942. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1943. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1944. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1945. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1946. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1947. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1948. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1949. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1950. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1951. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1952. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1953. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1954. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1955. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1956. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1957. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1958. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1959. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1960. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1961. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1962. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1963. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1964. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1965. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1966. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1967. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1968. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1969. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1970. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1971. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1972. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1973. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1974. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1975. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1976. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1977. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1978. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1979. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1980. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1981. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1982. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1983. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1984. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1985. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1986. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1987. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1988. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1989. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1990. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1991. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1992. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1993. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1994. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1995. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1996. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1997. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1998. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1999. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  2000. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  2001. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  2002. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  2003. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  2004. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  2005. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  2006. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  2007. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  2008. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  2009. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  2010. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  2011. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  2012. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  2013. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  2014. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  2015. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  2016. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  2017. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  2018. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  2019. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  2020. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  2021. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  2022. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  2023. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  2024. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  2025. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  2026. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  2027. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  2028. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  2029. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  2030. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  2031. ]
  2032. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  2033. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2034. # ####################################################################################
  2035. # ####################### Shell SETUP ################################################
  2036. # ####################################################################################
  2037. self.shell = FCShell(self, version=self.version)
  2038. self.shell._edit.set_model_data(self.myKeywords)
  2039. self.shell.setWindowIcon(self.ui.app_icon)
  2040. self.shell.setWindowTitle("FlatCAM Shell")
  2041. self.shell.resize(*self.defaults["global_shell_shape"])
  2042. self.shell.append_output("FlatCAM %s - " % self.version)
  2043. self.shell.append_output(_("Type >help< to get started\n\n"))
  2044. self.init_tcl()
  2045. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  2046. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  2047. self.ui.shell_dock.setWidget(self.shell)
  2048. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  2049. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  2050. QtWidgets.QDockWidget.DockWidgetFloatable |
  2051. QtWidgets.QDockWidget.DockWidgetClosable)
  2052. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  2053. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  2054. if self.defaults["global_shell_at_startup"]:
  2055. self.ui.shell_dock.show()
  2056. else:
  2057. self.ui.shell_dock.hide()
  2058. # ##################################################################################
  2059. # ###################### Tools and Plugins #########################################
  2060. # ##################################################################################
  2061. self.dblsidedtool = None
  2062. self.distance_tool = None
  2063. self.distance_min_tool = None
  2064. self.panelize_tool = None
  2065. self.film_tool = None
  2066. self.paste_tool = None
  2067. self.calculator_tool = None
  2068. self.rules_tool = None
  2069. self.sub_tool = None
  2070. self.move_tool = None
  2071. self.cutout_tool = None
  2072. self.ncclear_tool = None
  2073. self.optimal_tool=None
  2074. self.paint_tool = None
  2075. self.transform_tool = None
  2076. self.properties_tool = None
  2077. self.pdf_tool = None
  2078. self.image_tool = None
  2079. self.pcb_wizard_tool = None
  2080. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  2081. self.install_tools()
  2082. # ### System Font Parsing ###
  2083. # self.f_parse = ParseFont(self)
  2084. # self.parse_system_fonts()
  2085. # #####################################################################################
  2086. # ######################## Check for updates ##########################################
  2087. # #####################################################################################
  2088. # Separate thread (Not worker)
  2089. # Check for updates on startup but only if the user consent and the app is not in Beta version
  2090. if (self.beta is False or self.beta is None) and \
  2091. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  2092. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  2093. self.thr2 = QtCore.QThread()
  2094. self.worker_task.emit({'fcn': self.version_check,
  2095. 'params': []})
  2096. self.thr2.start(QtCore.QThread.LowPriority)
  2097. # #####################################################################################
  2098. # ######################### Register files with FlatCAM; #############################
  2099. # ######################### It works only for Windows for now ########################
  2100. # #####################################################################################
  2101. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  2102. self.on_register_files()
  2103. # #####################################################################################
  2104. # ###################### Variables for global usage ###################################
  2105. # #####################################################################################
  2106. # coordinates for relative position display
  2107. self.rel_point1 = (0, 0)
  2108. self.rel_point2 = (0, 0)
  2109. # variable to store coordinates
  2110. self.pos = (0, 0)
  2111. self.pos_jump = (0, 0)
  2112. # variable to store mouse coordinates
  2113. self.mouse = [0, 0]
  2114. # decide if we have a double click or single click
  2115. self.doubleclick = False
  2116. # variable to store if a command is active (then the var is not None) and which one it is
  2117. self.command_active = None
  2118. # variable to store the status of moving selection action
  2119. # None value means that it's not an selection action
  2120. # True value = a selection from left to right
  2121. # False value = a selection from right to left
  2122. self.selection_type = None
  2123. # List to store the objects that are currently loaded in FlatCAM
  2124. # This list is updated on each object creation or object delete
  2125. self.all_objects_list = list()
  2126. # List to store the objects that are selected
  2127. self.sel_objects_list = list()
  2128. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  2129. self.key_modifiers = None
  2130. # Variable to hold the status of the axis
  2131. self.toggle_axis = True
  2132. # Variable to store the status of the fullscreen event
  2133. self.toggle_fscreen = False
  2134. # Variable to store the status of the code editor
  2135. self.toggle_codeeditor = False
  2136. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  2137. self.click_noproject = False
  2138. self.cursor = None
  2139. # Variable to store the GCODE that was edited
  2140. self.gcode_edited = ""
  2141. # reference for the self.ui.code_editor
  2142. self.reference_code_editor = None
  2143. self.script_code = ''
  2144. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  2145. self.preferences_changed_flag = False
  2146. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  2147. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  2148. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'pho',
  2149. 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top', 'tsm']
  2150. self.exc_list = ['drd', 'drl', 'exc', 'ncd', 'tap', 'txt', 'xln']
  2151. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  2152. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ncp', 'out', 'plt', 'ply', 'rol', 'sbp',
  2153. 'tap', 'xpi']
  2154. self.svg_list = ['svg']
  2155. self.dxf_list = ['dxf']
  2156. self.pdf_list = ['pdf']
  2157. self.prj_list = ['flatprj']
  2158. self.conf_list = ['flatconfig']
  2159. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  2160. # flag for polygons not cleared
  2161. self.poly_not_cleared = False
  2162. # VisPy visuals
  2163. self.isHovering = False
  2164. self.notHovering = True
  2165. # Window geometry
  2166. self.x_pos = None
  2167. self.y_pos = None
  2168. self.width = None
  2169. self.height = None
  2170. # Event signals disconnect id holders
  2171. self.mp = None
  2172. self.mm = None
  2173. self.mr = None
  2174. self.mp_zc = None
  2175. # when True, the app has to return from any thread
  2176. self.abort_flag = False
  2177. # set the value used in the Windows Title
  2178. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  2179. # ###############################################################################
  2180. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  2181. # ############# It's done only once after install ###############
  2182. # ###############################################################################
  2183. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  2184. fac_def_from_file = factory_file.read()
  2185. factory_defaults = json.loads(fac_def_from_file)
  2186. # if the file contain an empty dictionary then save the factory defaults into the file
  2187. if not factory_defaults:
  2188. self.save_factory_defaults(silent=False)
  2189. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  2190. initial_lay = 'compact'
  2191. self.on_layout(lay=initial_lay)
  2192. # Set the combobox in Preferences to the current layout
  2193. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  2194. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  2195. factory_file.close()
  2196. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  2197. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  2198. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  2199. # after the first run, this object should be False
  2200. self.defaults["first_run"] = False
  2201. # ###############################################################################
  2202. # ################# ADDING FlatCAM EDITORS section ##############################
  2203. # ###############################################################################
  2204. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2205. # at the first launch of the App , the editors will not be functional.
  2206. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  2207. self.exc_editor = FlatCAMExcEditor(self)
  2208. self.grb_editor = FlatCAMGrbEditor(self)
  2209. self.log.debug("Finished adding FlatCAM Editor's.")
  2210. self.set_ui_title(name=_("New Project - Not saved"))
  2211. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2212. current_platform = platform.architecture()[0]
  2213. if current_platform != '64bit':
  2214. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2215. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2216. # ###############################################################################
  2217. # ####################### Finished the CONSTRUCTOR ##############################
  2218. # ###############################################################################
  2219. App.log.debug("END of constructor. Releasing control.")
  2220. # #####################################################################################
  2221. # ########################## SHOW GUI #################################################
  2222. # #####################################################################################
  2223. # if the app is not started as headless, show it
  2224. if self.cmd_line_headless != 1:
  2225. if show_splash:
  2226. # finish the splash
  2227. self.splash.finish(self.ui)
  2228. settings = QSettings("Open Source", "FlatCAM")
  2229. if settings.contains("maximized_gui"):
  2230. maximized_ui = settings.value('maximized_gui', type=bool)
  2231. if maximized_ui is True:
  2232. self.ui.showMaximized()
  2233. else:
  2234. self.ui.show()
  2235. else:
  2236. self.ui.show()
  2237. if self.defaults["global_systray_icon"]:
  2238. self.trayIcon.show()
  2239. else:
  2240. log.warning("******************* RUNNING HEADLESS *******************")
  2241. # #####################################################################################
  2242. # ########################## START-UP ARGUMENTS #######################################
  2243. # #####################################################################################
  2244. # test if the program was started with a script as parameter
  2245. if self.cmd_line_shellvar:
  2246. try:
  2247. cnt = 0
  2248. command_tcl = 0
  2249. for i in self.cmd_line_shellvar.split(','):
  2250. if i is not None:
  2251. try:
  2252. command_tcl = eval(i)
  2253. except:
  2254. command_tcl = i
  2255. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  2256. cnt += 1
  2257. # if there are Windows paths then replace the path separator with a Unix like one
  2258. if sys.platform == 'win32':
  2259. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  2260. self.shell._sysShell.exec_command(command_tcl_formatted, no_echo=True)
  2261. except Exception as ext:
  2262. print("ERROR: ", ext)
  2263. sys.exit(2)
  2264. if self.cmd_line_shellfile:
  2265. try:
  2266. if self.ui.shell_dock.isHidden():
  2267. self.ui.shell_dock.show()
  2268. with open(self.cmd_line_shellfile, "r") as myfile:
  2269. if show_splash:
  2270. self.splash.showMessage('%s: %ssec\n%s' % (
  2271. _("Canvas initialization started.\n"
  2272. "Canvas initialization finished in"), '%.2f' % self.used_time,
  2273. _("Executing Tcl Script ...")),
  2274. alignment=Qt.AlignBottom | Qt.AlignLeft,
  2275. color=QtGui.QColor("gray"))
  2276. cmd_line_shellfile_text = myfile.read()
  2277. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  2278. except Exception as ext:
  2279. print("ERROR: ", ext)
  2280. sys.exit(2)
  2281. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2282. # the path/file_name must be enclosed in quotes if it contain spaces
  2283. if App.args:
  2284. self.args_at_startup.emit(App.args)
  2285. @staticmethod
  2286. def copy_and_overwrite(from_path, to_path):
  2287. """
  2288. From here:
  2289. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2290. :param from_path: source path
  2291. :param to_path: destination path
  2292. :return: None
  2293. """
  2294. if os.path.exists(to_path):
  2295. shutil.rmtree(to_path)
  2296. try:
  2297. shutil.copytree(from_path, to_path)
  2298. except FileNotFoundError:
  2299. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2300. shutil.copytree(from_new_path, to_path)
  2301. def on_startup_args(self, args, silent=False):
  2302. """
  2303. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2304. :param args: a list containing the application args at startup
  2305. :return: None
  2306. """
  2307. if args is not None:
  2308. args_to_process = args
  2309. else:
  2310. args_to_process = App.args
  2311. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2312. for argument in args_to_process:
  2313. if '.FlatPrj'.lower() in argument.lower():
  2314. try:
  2315. project_name = str(argument)
  2316. if project_name == "":
  2317. if silent is False:
  2318. self.inform.emit(_("Open cancelled."))
  2319. else:
  2320. # self.open_project(project_name)
  2321. run_from_arg = True
  2322. # self.worker_task.emit({'fcn': self.open_project,
  2323. # 'params': [project_name, run_from_arg]})
  2324. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2325. except Exception as e:
  2326. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2327. elif '.FlatConfig'.lower() in argument.lower():
  2328. try:
  2329. file_name = str(argument)
  2330. if file_name == "":
  2331. if silent is False:
  2332. self.inform.emit(_("Open Config file failed."))
  2333. else:
  2334. run_from_arg = True
  2335. # self.worker_task.emit({'fcn': self.open_config_file,
  2336. # 'params': [file_name, run_from_arg]})
  2337. self.open_config_file(file_name, run_from_arg=run_from_arg)
  2338. except Exception as e:
  2339. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2340. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  2341. try:
  2342. file_name = str(argument)
  2343. if file_name == "":
  2344. if silent is False:
  2345. self.inform.emit(_("Open Script file failed."))
  2346. else:
  2347. if silent is False:
  2348. self.on_fileopenscript(name=file_name)
  2349. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  2350. self.on_filerunscript(name=file_name)
  2351. except Exception as e:
  2352. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2353. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  2354. log.debug("App.on_startup_args() --> Quit event.")
  2355. sys.exit()
  2356. elif 'save'.lower() in argument.lower():
  2357. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  2358. self.save_defaults()
  2359. else:
  2360. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2361. proc_arg = argument.lower()
  2362. for ext in exc_list:
  2363. proc_ext = ext.replace(' ', '')
  2364. proc_ext = '.%s' % proc_ext
  2365. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2366. file_name = str(argument)
  2367. if file_name == "":
  2368. if silent is False:
  2369. self.inform.emit(_("Open Excellon file failed."))
  2370. else:
  2371. self.on_fileopenexcellon(name=file_name)
  2372. return
  2373. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2374. for ext in gco_list:
  2375. proc_ext = ext.replace(' ', '')
  2376. proc_ext = '.%s' % proc_ext
  2377. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2378. file_name = str(argument)
  2379. if file_name == "":
  2380. if silent is False:
  2381. self.inform.emit(_("Open GCode file failed."))
  2382. else:
  2383. self.on_fileopengcode(name=file_name)
  2384. return
  2385. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2386. for ext in grb_list:
  2387. proc_ext = ext.replace(' ', '')
  2388. proc_ext = '.%s' % proc_ext
  2389. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2390. file_name = str(argument)
  2391. if file_name == "":
  2392. if silent is False:
  2393. self.inform.emit(_("Open Gerber file failed."))
  2394. else:
  2395. self.on_fileopengerber(name=file_name)
  2396. return
  2397. # if it reached here without already returning then the app was registered with a file that it does not
  2398. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  2399. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  2400. # for arg in args_to_process:
  2401. # if 'FlatCAM.exe' in arg:
  2402. # continue
  2403. # else:
  2404. # sys.exit(2)
  2405. def set_ui_title(self, name):
  2406. """
  2407. Sets the title of the main window.
  2408. :param name: String that store the project path and project name
  2409. :return: None
  2410. """
  2411. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  2412. (self.version,
  2413. ('BETA' if self.beta else ''),
  2414. platform.architecture()[0],
  2415. self.engine,
  2416. name)
  2417. )
  2418. def on_theme_change(self, val):
  2419. settings = QSettings("Open Source", "FlatCAM")
  2420. settings.setValue('theme', val)
  2421. # This will write the setting to the platform specific storage.
  2422. del settings
  2423. self.on_app_restart()
  2424. def on_app_restart(self):
  2425. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  2426. # be left in the SySTray
  2427. try:
  2428. self.trayIcon.hide()
  2429. except Exception as e:
  2430. pass
  2431. fcTranslate.restart_program(app=self)
  2432. def defaults_read_form(self):
  2433. """
  2434. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2435. :return: None
  2436. """
  2437. for option in self.defaults_form_fields:
  2438. try:
  2439. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2440. except Exception as e:
  2441. log.debug("App.defaults_read_form() --> %s" % str(e))
  2442. def defaults_write_form(self, factor=None, fl_units=None):
  2443. """
  2444. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2445. self.defaults dictionary.
  2446. :param factor: will apply a factor to the values that written in the GUI elements
  2447. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2448. :return: None
  2449. """
  2450. for option in self.defaults:
  2451. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2452. # try:
  2453. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2454. # except KeyError:
  2455. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2456. # # TODO: Rethink this?
  2457. # pass
  2458. def defaults_write_form_field(self, field, factor=None, units=None):
  2459. """
  2460. Basically it is the worker in the self.defaults_write_form()
  2461. :param field: the GUI element in Preferences GUI to be updated
  2462. :param factor: factor to be applied to the field parameter
  2463. :param units: current FLatCAM measuring units
  2464. :return: None, it updates GUI elements
  2465. """
  2466. try:
  2467. if factor is None:
  2468. if units is None:
  2469. self.defaults_form_fields[field].set_value(self.defaults[field])
  2470. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2471. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=6)
  2472. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2473. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=4)
  2474. else:
  2475. if units is None:
  2476. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2477. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2478. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=6)
  2479. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2480. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=4)
  2481. except KeyError:
  2482. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2483. # TODO: Rethink this?
  2484. pass
  2485. except AttributeError:
  2486. log.debug(field)
  2487. def clear_pool(self):
  2488. """
  2489. Clear the multiprocessing pool and calls garbage collector.
  2490. :return: None
  2491. """
  2492. self.pool.close()
  2493. self.pool = Pool()
  2494. self.pool_recreated.emit(self.pool)
  2495. gc.collect()
  2496. def install_tools(self):
  2497. """
  2498. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2499. Instantiation of the Tools classes.
  2500. The order that the tools are installed is important as they can depend on each other install position.
  2501. :return: None
  2502. """
  2503. self.dblsidedtool = DblSidedTool(self)
  2504. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2505. self.distance_tool = Distance(self)
  2506. self.distance_tool.install(icon=QtGui.QIcon('share/distance16.png'), pos=self.ui.menuedit,
  2507. before=self.ui.menueditorigin,
  2508. separator=False)
  2509. self.distance_min_tool = DistanceMin(self)
  2510. self.distance_min_tool.install(icon=QtGui.QIcon('share/distance_min16.png'), pos=self.ui.menuedit,
  2511. before=self.ui.menueditorigin,
  2512. separator=True)
  2513. self.panelize_tool = Panelize(self)
  2514. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  2515. self.film_tool = Film(self)
  2516. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2517. self.paste_tool = SolderPaste(self)
  2518. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2519. self.calculator_tool = ToolCalculator(self)
  2520. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator16.png'), separator=True)
  2521. self.sub_tool = ToolSub(self)
  2522. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2523. self.rules_tool = RulesCheck(self)
  2524. self.rules_tool.install(icon=QtGui.QIcon('share/rules32.png'), pos=self.ui.menutool, separator=False)
  2525. self.optimal_tool = ToolOptimal(self)
  2526. self.optimal_tool.install(icon=QtGui.QIcon('share/open_excellon32.png'), pos=self.ui.menutool, separator=True)
  2527. self.move_tool = ToolMove(self)
  2528. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2529. before=self.ui.menueditorigin, separator=True)
  2530. self.cutout_tool = CutOut(self)
  2531. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2532. before=self.sub_tool.menuAction)
  2533. self.ncclear_tool = NonCopperClear(self)
  2534. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2535. before=self.sub_tool.menuAction, separator=True)
  2536. self.paint_tool = ToolPaint(self)
  2537. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2538. before=self.sub_tool.menuAction, separator=True)
  2539. self.transform_tool = ToolTransform(self)
  2540. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2541. self.properties_tool = Properties(self)
  2542. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2543. self.pdf_tool = ToolPDF(self)
  2544. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2545. separator=True)
  2546. self.image_tool = ToolImage(self)
  2547. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2548. separator=True)
  2549. self.pcb_wizard_tool = PcbWizard(self)
  2550. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2551. self.log.debug("Tools are installed.")
  2552. def remove_tools(self):
  2553. """
  2554. Will remove all the actions in the Tool menu.
  2555. :return: None
  2556. """
  2557. for act in self.ui.menutool.actions():
  2558. self.ui.menutool.removeAction(act)
  2559. def init_tools(self):
  2560. """
  2561. Initialize the Tool tab in the notebook side of the central widget.
  2562. Remove the actions in the Tools menu.
  2563. Instantiate again the FlatCAM tools (plugins).
  2564. All this is required when changing the layout: standard, compact etc.
  2565. :return: None
  2566. """
  2567. log.debug("init_tools()")
  2568. # delete the data currently in the Tools Tab and the Tab itself
  2569. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2570. if widget is not None:
  2571. widget.deleteLater()
  2572. self.ui.notebook.removeTab(2)
  2573. # rebuild the Tools Tab
  2574. self.ui.tool_tab = QtWidgets.QWidget()
  2575. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2576. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2577. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2578. self.ui.tool_scroll_area = VerticalScrollArea()
  2579. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2580. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2581. # first remove all of them
  2582. self.remove_tools()
  2583. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2584. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2585. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2586. # third install all of them
  2587. self.install_tools()
  2588. self.log.debug("Tools are initialized.")
  2589. # def parse_system_fonts(self):
  2590. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2591. # 'params': []})
  2592. def connect_toolbar_signals(self):
  2593. """
  2594. Reconnect the signals to the actions in the toolbar.
  2595. This has to be done each time after the FlatCAM tools are removed/installed.
  2596. :return: None
  2597. """
  2598. # Toolbar
  2599. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2600. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2601. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2602. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2603. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2604. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2605. self.ui.replot_btn.triggered.connect(self.plot_all)
  2606. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2607. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2608. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2609. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2610. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2611. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2612. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2613. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2614. self.ui.delete_btn.triggered.connect(self.on_delete)
  2615. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  2616. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  2617. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  2618. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  2619. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2620. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2621. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2622. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2623. # Tools Toolbar Signals
  2624. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2625. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2626. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2627. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2628. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2629. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2630. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2631. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2632. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  2633. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  2634. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2635. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2636. def object2editor(self):
  2637. """
  2638. Send the current Geometry or Excellon object (if any) into the it's editor.
  2639. :return: None
  2640. """
  2641. self.report_usage("object2editor()")
  2642. edited_object = self.collection.get_active()
  2643. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2644. isinstance(edited_object, FlatCAMExcellon):
  2645. pass
  2646. else:
  2647. self.inform.emit('[WARNING_NOTCL] %s' %
  2648. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2649. return
  2650. if isinstance(edited_object, FlatCAMGeometry):
  2651. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2652. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2653. # we set the notebook to hidden
  2654. self.ui.splitter.setSizes([0, 1])
  2655. if edited_object.multigeo is True:
  2656. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  2657. if len(edited_tools) > 1:
  2658. self.inform.emit('[WARNING_NOTCL] %s' %
  2659. _("Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  2660. "is not possible.\n"
  2661. "Edit only one geometry at a time."))
  2662. # determine the tool dia of the selected tool
  2663. selected_tooldia = float(edited_object.ui.geo_tools_table.item((edited_tools[0] - 1), 1).text())
  2664. # now find the key in the edited_object.tools that has this tooldia
  2665. multi_tool = 1
  2666. for tool in edited_object.tools:
  2667. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2668. multi_tool = tool
  2669. break
  2670. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2671. else:
  2672. self.geo_editor.edit_fcgeometry(edited_object)
  2673. # set call source to the Editor we go into
  2674. self.call_source = 'geo_editor'
  2675. elif isinstance(edited_object, FlatCAMExcellon):
  2676. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2677. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2678. if self.ui.splitter.sizes()[0] == 0:
  2679. self.ui.splitter.setSizes([1, 1])
  2680. self.exc_editor.edit_fcexcellon(edited_object)
  2681. # set call source to the Editor we go into
  2682. self.call_source = 'exc_editor'
  2683. elif isinstance(edited_object, FlatCAMGerber):
  2684. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2685. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2686. if self.ui.splitter.sizes()[0] == 0:
  2687. self.ui.splitter.setSizes([1, 1])
  2688. self.grb_editor.edit_fcgerber(edited_object)
  2689. # set call source to the Editor we go into
  2690. self.call_source = 'grb_editor'
  2691. # make sure that we can't select another object while in Editor Mode:
  2692. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2693. self.ui.project_frame.setDisabled(True)
  2694. # delete any selection shape that might be active as they are not relevant in Editor
  2695. self.delete_selection_shape()
  2696. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2697. self.ui.plot_tab_area.protectTab(0)
  2698. self.inform.emit('[WARNING_NOTCL] %s' %
  2699. _("Editor is activated ..."))
  2700. self.should_we_save = True
  2701. def editor2object(self, cleanup=None):
  2702. """
  2703. Transfers the Geometry or Excellon from it's editor to the current object.
  2704. :return: None
  2705. """
  2706. self.report_usage("editor2object()")
  2707. # do not update a geometry or excellon object unless it comes out of an editor
  2708. if self.call_source != 'app':
  2709. edited_obj = self.collection.get_active()
  2710. if cleanup is None:
  2711. msgbox = QtWidgets.QMessageBox()
  2712. msgbox.setText(_("Do you want to save the edited object?"))
  2713. msgbox.setWindowTitle(_("Close Editor"))
  2714. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2715. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2716. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2717. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2718. msgbox.setDefaultButton(bt_yes)
  2719. msgbox.exec_()
  2720. response = msgbox.clickedButton()
  2721. if response == bt_yes:
  2722. # clean the Tools Tab
  2723. self.ui.tool_scroll_area.takeWidget()
  2724. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2725. self.ui.notebook.setTabText(2, "Tool")
  2726. if isinstance(edited_obj, FlatCAMGeometry):
  2727. obj_type = "Geometry"
  2728. if cleanup is None:
  2729. self.geo_editor.update_fcgeometry(edited_obj)
  2730. self.geo_editor.update_options(edited_obj)
  2731. self.geo_editor.deactivate()
  2732. # update the geo object options so it is including the bounding box values
  2733. try:
  2734. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2735. edited_obj.options['xmin'] = xmin
  2736. edited_obj.options['ymin'] = ymin
  2737. edited_obj.options['xmax'] = xmax
  2738. edited_obj.options['ymax'] = ymax
  2739. except AttributeError as e:
  2740. self.inform.emit('[WARNING] %s' %
  2741. _("Object empty after edit."))
  2742. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2743. elif isinstance(edited_obj, FlatCAMGerber):
  2744. obj_type = "Gerber"
  2745. if cleanup is None:
  2746. self.grb_editor.update_fcgerber()
  2747. self.grb_editor.update_options(edited_obj)
  2748. self.grb_editor.deactivate_grb_editor()
  2749. # delete the old object (the source object) if it was an empty one
  2750. try:
  2751. if len(edited_obj.solid_geometry) == 0:
  2752. old_name = edited_obj.options['name']
  2753. self.collection.set_active(old_name)
  2754. self.collection.delete_active()
  2755. except TypeError:
  2756. # if the solid_geometry is a single Polygon the len() will not work
  2757. # in any case, falling here means that we have something in the solid_geometry, even if only
  2758. # a single Polygon, therefore we pass this
  2759. pass
  2760. # restore GUI to the Selected TAB
  2761. # Remove anything else in the GUI
  2762. self.ui.selected_scroll_area.takeWidget()
  2763. # Switch notebook to Selected page
  2764. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2765. elif isinstance(edited_obj, FlatCAMExcellon):
  2766. obj_type = "Excellon"
  2767. if cleanup is None:
  2768. self.exc_editor.update_fcexcellon(edited_obj)
  2769. self.exc_editor.update_options(edited_obj)
  2770. self.exc_editor.deactivate()
  2771. # delete the old object (the source object) if it was an empty one
  2772. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  2773. old_name = edited_obj.options['name']
  2774. self.collection.set_active(old_name)
  2775. self.collection.delete_active()
  2776. # restore GUI to the Selected TAB
  2777. # Remove anything else in the GUI
  2778. self.ui.tool_scroll_area.takeWidget()
  2779. # Switch notebook to Selected page
  2780. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2781. else:
  2782. self.inform.emit('[WARNING_NOTCL] %s' %
  2783. _("Select a Gerber, Geometry or Excellon Object to update."))
  2784. return
  2785. self.inform.emit('[selected] %s %s' %
  2786. (obj_type, _("is updated, returning to App...")))
  2787. elif response == bt_no:
  2788. # clean the Tools Tab
  2789. self.ui.tool_scroll_area.takeWidget()
  2790. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2791. self.ui.notebook.setTabText(2, "Tool")
  2792. if isinstance(edited_obj, FlatCAMGeometry):
  2793. self.geo_editor.deactivate()
  2794. elif isinstance(edited_obj, FlatCAMGerber):
  2795. self.grb_editor.deactivate_grb_editor()
  2796. elif isinstance(edited_obj, FlatCAMExcellon):
  2797. self.exc_editor.deactivate()
  2798. # set focus on the project tab
  2799. else:
  2800. self.inform.emit('[WARNING_NOTCL] %s' %
  2801. _("Select a Gerber, Geometry or Excellon Object to update."))
  2802. return
  2803. edited_obj.set_ui(edited_obj.ui_type())
  2804. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2805. elif response == bt_cancel:
  2806. return
  2807. else:
  2808. if isinstance(edited_obj, FlatCAMGeometry):
  2809. self.geo_editor.deactivate()
  2810. elif isinstance(edited_obj, FlatCAMGerber):
  2811. self.grb_editor.deactivate_grb_editor()
  2812. elif isinstance(edited_obj, FlatCAMExcellon):
  2813. self.exc_editor.deactivate()
  2814. else:
  2815. self.inform.emit('[WARNING_NOTCL] %s' %
  2816. _("Select a Gerber, Geometry or Excellon Object to update."))
  2817. return
  2818. # if notebook is hidden we show it
  2819. if self.ui.splitter.sizes()[0] == 0:
  2820. self.ui.splitter.setSizes([1, 1])
  2821. # restore the call_source to app
  2822. self.call_source = 'app'
  2823. edited_obj.plot()
  2824. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2825. self.ui.plot_tab_area.protectTab(0)
  2826. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2827. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2828. self.ui.project_frame.setDisabled(False)
  2829. def get_last_folder(self):
  2830. """
  2831. Get the folder path from where the last file was opened.
  2832. :return: String, last opened folder path
  2833. """
  2834. return self.defaults["global_last_folder"]
  2835. def get_last_save_folder(self):
  2836. """
  2837. Get the folder path from where the last file was saved.
  2838. :return: String, last saved folder path
  2839. """
  2840. loc = self.defaults["global_last_save_folder"]
  2841. if loc is None:
  2842. loc = self.defaults["global_last_folder"]
  2843. if loc is None:
  2844. loc = os.path.dirname(__file__)
  2845. return loc
  2846. def report_usage(self, resource):
  2847. """
  2848. Increments usage counter for the given resource
  2849. in self.defaults['global_stats'].
  2850. :param resource: Name of the resource.
  2851. :return: None
  2852. """
  2853. if resource in self.defaults['global_stats']:
  2854. self.defaults['global_stats'][resource] += 1
  2855. else:
  2856. self.defaults['global_stats'][resource] = 1
  2857. def init_tcl(self):
  2858. """
  2859. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2860. :return: None
  2861. """
  2862. if hasattr(self, 'tcl'):
  2863. # self.tcl = None
  2864. # TODO we need to clean non default variables and procedures here
  2865. # new object cannot be used here as it will not remember values created for next passes,
  2866. # because tcl was execudted in old instance of TCL
  2867. pass
  2868. else:
  2869. self.tcl = tk.Tcl()
  2870. self.setup_shell()
  2871. self.log.debug("TCL Shell has been initialized.")
  2872. # TODO: This shouldn't be here.
  2873. class TclErrorException(Exception):
  2874. """
  2875. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2876. """
  2877. pass
  2878. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2879. """
  2880. Shows a message on the FlatCAM Shell
  2881. :param msg: Message to display.
  2882. :param show: Opens the shell.
  2883. :param error: Shows the message as an error.
  2884. :param warning: Shows the message as an warning.
  2885. :param success: Shows the message as an success.
  2886. :param selected: Indicate that something was selected on canvas
  2887. :return: None
  2888. """
  2889. if show:
  2890. self.ui.shell_dock.show()
  2891. try:
  2892. if error:
  2893. self.shell.append_error(msg + "\n")
  2894. elif warning:
  2895. self.shell.append_warning(msg + "\n")
  2896. elif success:
  2897. self.shell.append_success(msg + "\n")
  2898. elif selected:
  2899. self.shell.append_selected(msg + "\n")
  2900. else:
  2901. self.shell.append_output(msg + "\n")
  2902. except AttributeError:
  2903. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2904. def raise_tcl_unknown_error(self, unknownException):
  2905. """
  2906. Raise exception if is different type than TclErrorException
  2907. this is here mainly to show unknown errors inside TCL shell console.
  2908. :param unknownException:
  2909. :return:
  2910. """
  2911. if not isinstance(unknownException, self.TclErrorException):
  2912. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2913. else:
  2914. raise unknownException
  2915. def display_tcl_error(self, error, error_info=None):
  2916. """
  2917. Escape bracket [ with '\' otherwise there is error
  2918. "ERROR: missing close-bracket" instead of real error
  2919. :param error: it may be text or exception
  2920. :param error_info: Some informations about the error
  2921. :return: None
  2922. """
  2923. if isinstance(error, Exception):
  2924. exc_type, exc_value, exc_traceback = error_info
  2925. if not isinstance(error, self.TclErrorException):
  2926. show_trace = 1
  2927. else:
  2928. show_trace = int(self.defaults['global_verbose_error_level'])
  2929. if show_trace > 0:
  2930. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2931. trc_formated = []
  2932. for a in reversed(trc):
  2933. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2934. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2935. else:
  2936. text = "%s" % error
  2937. else:
  2938. text = error
  2939. text = text.replace('[', '\\[').replace('"', '\\"')
  2940. self.tcl.eval('return -code error "%s"' % text)
  2941. def raise_tcl_error(self, text):
  2942. """
  2943. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2944. :param text: text of error
  2945. :return: raise exception
  2946. """
  2947. self.display_tcl_error(text)
  2948. raise self.TclErrorException(text)
  2949. def exec_command(self, text, no_echo=False):
  2950. """
  2951. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2952. Also handles execution in separated threads
  2953. :param text: FlatCAM TclCommand with parameters
  2954. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2955. will create crashes of the _Expandable_Edit widget
  2956. :return: output if there was any
  2957. """
  2958. self.report_usage('exec_command')
  2959. result = self.exec_command_test(text, False, no_echo=no_echo)
  2960. # MS: added this method call so the geometry is updated once the TCL command is executed
  2961. # if no_plot is None:
  2962. # self.plot_all()
  2963. return result
  2964. def exec_command_test(self, text, reraise=True, no_echo=False):
  2965. """
  2966. Same as exec_command(...) with additional control over exceptions.
  2967. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2968. :param text: Input command
  2969. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2970. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2971. will create crashes of the _Expandable_Edit widget
  2972. :return: Output from the command
  2973. """
  2974. tcl_command_string = str(text)
  2975. try:
  2976. if no_echo is False:
  2977. self.shell.open_proccessing() # Disables input box.
  2978. result = self.tcl.eval(str(tcl_command_string))
  2979. if result != 'None' and no_echo is False:
  2980. self.shell.append_output(result + '\n')
  2981. except tk.TclError as e:
  2982. # This will display more precise answer if something in TCL shell fails
  2983. result = self.tcl.eval("set errorInfo")
  2984. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2985. if no_echo is False:
  2986. self.shell.append_error('ERROR: ' + result + '\n')
  2987. # Show error in console and just return or in test raise exception
  2988. if reraise:
  2989. raise e
  2990. finally:
  2991. if no_echo is False:
  2992. self.shell.close_proccessing()
  2993. pass
  2994. return result
  2995. # """
  2996. # Code below is unsused. Saved for later.
  2997. # """
  2998. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2999. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  3000. # self.log.debug(parts)
  3001. # try:
  3002. # if parts[0] not in commands:
  3003. # self.shell.append_error("Unknown command\n")
  3004. # return
  3005. #
  3006. # #import inspect
  3007. # #inspect.getargspec(someMethod)
  3008. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  3009. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  3010. # self.shell.append_error(
  3011. # "Command %s takes %d arguments. %d given.\n" %
  3012. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  3013. # )
  3014. # return
  3015. #
  3016. # cmdfcn = commands[parts[0]]["fcn"]
  3017. # cmdconv = commands[parts[0]]["converters"]
  3018. # if len(parts) - 1 > 0:
  3019. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  3020. # else:
  3021. # retval = cmdfcn()
  3022. # retfcn = commands[parts[0]]["retfcn"]
  3023. # if retval and retfcn(retval):
  3024. # self.shell.append_output(retfcn(retval) + "\n")
  3025. #
  3026. # except Exception as e:
  3027. # #self.shell.append_error(''.join(traceback.format_exc()))
  3028. # #self.shell.append_error("?\n")
  3029. # self.shell.append_error(str(e) + "\n")
  3030. def info(self, msg):
  3031. """
  3032. Informs the user. Normally on the status bar, optionally
  3033. also on the shell.
  3034. :param msg: Text to write.
  3035. :return: None
  3036. """
  3037. # Type of message in brackets at the beginning of the message.
  3038. match = re.search("\[([^\]]+)\](.*)", msg)
  3039. if match:
  3040. level = match.group(1)
  3041. msg_ = match.group(2)
  3042. self.ui.fcinfo.set_status(str(msg_), level=level)
  3043. if level.lower() == "error":
  3044. self.shell_message(msg, error=True, show=True)
  3045. elif level.lower() == "warning":
  3046. self.shell_message(msg, warning=True, show=True)
  3047. elif level.lower() == "error_notcl":
  3048. self.shell_message(msg, error=True, show=False)
  3049. elif level.lower() == "warning_notcl":
  3050. self.shell_message(msg, warning=True, show=False)
  3051. elif level.lower() == "success":
  3052. self.shell_message(msg, success=True, show=False)
  3053. elif level.lower() == "selected":
  3054. self.shell_message(msg, selected=True, show=False)
  3055. else:
  3056. self.shell_message(msg, show=False)
  3057. else:
  3058. self.ui.fcinfo.set_status(str(msg), level="info")
  3059. # make sure that if the message is to clear the infobar with a space
  3060. # is not printed over and over on the shell
  3061. if msg != '':
  3062. self.shell_message(msg)
  3063. def restore_toolbar_view(self):
  3064. """
  3065. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  3066. was saved in the defaults dictionary.
  3067. :return: None
  3068. """
  3069. tb = self.defaults["global_toolbar_view"]
  3070. if tb & 1:
  3071. self.ui.toolbarfile.setVisible(True)
  3072. else:
  3073. self.ui.toolbarfile.setVisible(False)
  3074. if tb & 2:
  3075. self.ui.toolbargeo.setVisible(True)
  3076. else:
  3077. self.ui.toolbargeo.setVisible(False)
  3078. if tb & 4:
  3079. self.ui.toolbarview.setVisible(True)
  3080. else:
  3081. self.ui.toolbarview.setVisible(False)
  3082. if tb & 8:
  3083. self.ui.toolbartools.setVisible(True)
  3084. else:
  3085. self.ui.toolbartools.setVisible(False)
  3086. if tb & 16:
  3087. self.ui.exc_edit_toolbar.setVisible(True)
  3088. else:
  3089. self.ui.exc_edit_toolbar.setVisible(False)
  3090. if tb & 32:
  3091. self.ui.geo_edit_toolbar.setVisible(True)
  3092. else:
  3093. self.ui.geo_edit_toolbar.setVisible(False)
  3094. if tb & 64:
  3095. self.ui.grb_edit_toolbar.setVisible(True)
  3096. else:
  3097. self.ui.grb_edit_toolbar.setVisible(False)
  3098. if tb & 128:
  3099. self.ui.snap_toolbar.setVisible(True)
  3100. else:
  3101. self.ui.snap_toolbar.setVisible(False)
  3102. if tb & 256:
  3103. self.ui.toolbarshell.setVisible(True)
  3104. else:
  3105. self.ui.toolbarshell.setVisible(False)
  3106. def load_defaults(self, filename):
  3107. """
  3108. Loads the aplication's default settings from current_defaults.FlatConfig into
  3109. ``self.defaults``.
  3110. :return: None
  3111. """
  3112. try:
  3113. f = open(self.data_path + "/" + filename + ".FlatConfig")
  3114. options = f.read()
  3115. f.close()
  3116. except IOError:
  3117. self.log.error("Could not load defaults file.")
  3118. self.inform.emit('[ERROR] %s' %
  3119. _("Could not load defaults file."))
  3120. # in case the defaults file can't be loaded, show all toolbars
  3121. self.defaults["global_toolbar_view"] = 511
  3122. return
  3123. try:
  3124. defaults = json.loads(options)
  3125. except:
  3126. # in case the defaults file can't be loaded, show all toolbars
  3127. self.defaults["global_toolbar_view"] = 511
  3128. e = sys.exc_info()[0]
  3129. App.log.error(str(e))
  3130. self.inform.emit('[ERROR] %s' %
  3131. _("Failed to parse defaults file."))
  3132. return
  3133. self.defaults.update(defaults)
  3134. log.debug("FlatCAM defaults loaded from: %s" % filename)
  3135. # restore the toolbar view
  3136. self.restore_toolbar_view()
  3137. def on_import_preferences(self):
  3138. """
  3139. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  3140. ``self.defaults``.
  3141. :return: None
  3142. """
  3143. self.report_usage("on_import_preferences")
  3144. App.log.debug("on_import_preferences()")
  3145. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  3146. try:
  3147. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3148. directory=self.data_path,
  3149. filter=filter_)
  3150. except TypeError:
  3151. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3152. filter=filter_)
  3153. filename = str(filename)
  3154. if filename == "":
  3155. self.inform.emit('[WARNING_NOTCL] %s' %
  3156. _("FlatCAM preferences import cancelled."))
  3157. else:
  3158. try:
  3159. f = open(filename)
  3160. options = f.read()
  3161. f.close()
  3162. except IOError:
  3163. self.log.error("Could not load defaults file.")
  3164. self.inform.emit('[ERROR_NOTCL] %s' %
  3165. _("Could not load defaults file."))
  3166. return
  3167. try:
  3168. defaults_from_file = json.loads(options)
  3169. except Exception as e:
  3170. e = sys.exc_info()[0]
  3171. App.log.error(str(e))
  3172. self.inform.emit('[ERROR_NOTCL] %s' %
  3173. _("Failed to parse defaults file."))
  3174. return
  3175. self.defaults.update(defaults_from_file)
  3176. self.on_preferences_edited()
  3177. self.inform.emit('[success] %s: %s' %
  3178. (_("Imported Defaults from"), filename))
  3179. def on_export_preferences(self):
  3180. """
  3181. Save the defaults dictionary to a file.
  3182. :return: None
  3183. """
  3184. self.report_usage("on_export_preferences")
  3185. App.log.debug("on_export_preferences()")
  3186. defaults_file_content = None
  3187. self.date = str(datetime.today()).rpartition('.')[0]
  3188. self.date = ''.join(c for c in self.date if c not in ':-')
  3189. self.date = self.date.replace(' ', '_')
  3190. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  3191. try:
  3192. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  3193. caption=_("Export FlatCAM Preferences"),
  3194. directory=self.data_path + '/preferences_' + self.date,
  3195. filter=filter__
  3196. )
  3197. except TypeError:
  3198. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  3199. filter=filter__)
  3200. filename = str(filename)
  3201. defaults_from_file = {}
  3202. if filename == "":
  3203. self.inform.emit('[WARNING_NOTCL] %s' %
  3204. _("FlatCAM preferences export cancelled."))
  3205. return
  3206. else:
  3207. try:
  3208. f = open(filename, 'w')
  3209. defaults_file_content = f.read()
  3210. f.close()
  3211. except PermissionError:
  3212. self.inform.emit('[WARNING] %s' %
  3213. _("Permission denied, saving not possible.\n"
  3214. "Most likely another app is holding the file open and not accessible."))
  3215. return
  3216. except IOError:
  3217. App.log.debug('Creating a new preferences file ...')
  3218. f = open(filename, 'w')
  3219. json.dump({}, f)
  3220. f.close()
  3221. except:
  3222. e = sys.exc_info()[0]
  3223. App.log.error("Could not load defaults file.")
  3224. App.log.error(str(e))
  3225. self.inform.emit('[ERROR_NOTCL] %s' %
  3226. _("Could not load preferences file."))
  3227. return
  3228. try:
  3229. defaults_from_file = json.loads(defaults_file_content)
  3230. except:
  3231. App.log.warning("Trying to read an empty Preferences file. Continue.")
  3232. # Update options
  3233. self.defaults_read_form()
  3234. defaults_from_file.update(self.defaults)
  3235. self.propagate_defaults(silent=True)
  3236. # Save update options
  3237. try:
  3238. f = open(filename, "w")
  3239. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  3240. f.close()
  3241. except:
  3242. self.inform.emit('[ERROR_NOTCL] %s' %
  3243. _("Failed to write defaults to file."))
  3244. return
  3245. if self.defaults["global_open_style"] is False:
  3246. self.file_opened.emit("preferences", filename)
  3247. self.file_saved.emit("preferences", filename)
  3248. self.inform.emit('[success] %s: %s' %
  3249. (_("Exported preferences to"), filename))
  3250. def on_preferences_open_folder(self):
  3251. """
  3252. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  3253. :return: None
  3254. """
  3255. self.report_usage("on_preferences_open_folder()")
  3256. if sys.platform == 'win32':
  3257. subprocess.Popen('explorer %s' % self.data_path)
  3258. elif sys.platform == 'darwin':
  3259. os.system('open "%s"' % self.data_path)
  3260. else:
  3261. subprocess.Popen(['xdg-open', self.data_path])
  3262. self.inform.emit('[success] %s' %
  3263. _("FlatCAM Preferences Folder opened."))
  3264. def save_geometry(self, x, y, width, height, notebook_width):
  3265. """
  3266. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  3267. launch of the application.
  3268. :param x: X position of the main window
  3269. :param y: Y position of the main window
  3270. :param width: width of the main window
  3271. :param height: height of the main window
  3272. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  3273. :return: None
  3274. """
  3275. self.defaults["global_def_win_x"] = x
  3276. self.defaults["global_def_win_y"] = y
  3277. self.defaults["global_def_win_w"] = width
  3278. self.defaults["global_def_win_h"] = height
  3279. self.defaults["global_def_notebook_width"] = notebook_width
  3280. self.save_defaults()
  3281. def restore_main_win_geom(self):
  3282. try:
  3283. self.ui.setGeometry(self.defaults["global_def_win_x"],
  3284. self.defaults["global_def_win_y"],
  3285. self.defaults["global_def_win_w"],
  3286. self.defaults["global_def_win_h"])
  3287. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  3288. except KeyError as e:
  3289. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  3290. def message_dialog(self, title, message, kind="info"):
  3291. """
  3292. Builds and show a custom QMessageBox to be used in FlatCAM.
  3293. :param title: title of the QMessageBox
  3294. :param message: message to be displayed
  3295. :param kind: type of QMessageBox; will display a specific icon.
  3296. :return:
  3297. """
  3298. icon = {"info": QtWidgets.QMessageBox.Information,
  3299. "warning": QtWidgets.QMessageBox.Warning,
  3300. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3301. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  3302. dlg.setText(message)
  3303. dlg.exec_()
  3304. def register_recent(self, kind, filename):
  3305. """
  3306. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  3307. dictionary.
  3308. :param kind: type of file that was opened
  3309. :param filename: the path and file name for the file that was opened
  3310. :return:
  3311. """
  3312. self.log.debug("register_recent()")
  3313. self.log.debug(" %s" % kind)
  3314. self.log.debug(" %s" % filename)
  3315. record = {'kind': str(kind), 'filename': str(filename)}
  3316. if record in self.recent:
  3317. return
  3318. if record in self.recent_projects:
  3319. return
  3320. if record['kind'] == 'project':
  3321. self.recent_projects.insert(0, record)
  3322. else:
  3323. self.recent.insert(0, record)
  3324. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3325. self.recent.pop()
  3326. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3327. self.recent_projects.pop()
  3328. try:
  3329. f = open(self.data_path + '/recent.json', 'w')
  3330. except IOError:
  3331. App.log.error("Failed to open recent items file for writing.")
  3332. self.inform.emit('[ERROR_NOTCL] %s' %
  3333. _('Failed to open recent files file for writing.'))
  3334. return
  3335. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3336. f.close()
  3337. try:
  3338. fp = open(self.data_path + '/recent_projects.json', 'w')
  3339. except IOError:
  3340. App.log.error("Failed to open recent items file for writing.")
  3341. self.inform.emit('[ERROR_NOTCL] %s' %
  3342. _('Failed to open recent projects file for writing.'))
  3343. return
  3344. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3345. fp.close()
  3346. # Re-build the recent items menu
  3347. self.setup_recent_items()
  3348. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3349. """
  3350. Creates a new specialized FlatCAMObj and attaches it to the application,
  3351. this is, updates the GUI accordingly, any other records and plots it.
  3352. This method is thread-safe.
  3353. Notes:
  3354. * If the name is in use, the self.collection will modify it
  3355. when appending it to the collection. There is no need to handle
  3356. name conflicts here.
  3357. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3358. :type kind: str
  3359. :param name: Name for the object.
  3360. :type name: str
  3361. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3362. The function is called with 2 parameters: the new object and the App instance.
  3363. :type initialize: function
  3364. :param active:
  3365. :param fit:
  3366. :param plot: If to plot the resulting object
  3367. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3368. self.colleaction
  3369. :return: None
  3370. :rtype: None
  3371. """
  3372. App.log.debug("new_object()")
  3373. obj_plot = plot
  3374. obj_autoselected = autoselected
  3375. t0 = time.time() # Debug
  3376. # ## Create object
  3377. classdict = {
  3378. "gerber": FlatCAMGerber,
  3379. "excellon": FlatCAMExcellon,
  3380. "cncjob": FlatCAMCNCjob,
  3381. "geometry": FlatCAMGeometry,
  3382. "script": FlatCAMScript,
  3383. "document": FlatCAMDocument
  3384. }
  3385. App.log.debug("Calling object constructor...")
  3386. obj = classdict[kind](name)
  3387. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3388. # Set options from "Project options" form
  3389. self.options_read_form()
  3390. # IMPORTANT
  3391. # The key names in defaults and options dictionary's are not random:
  3392. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3393. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  3394. # the options from project options form into the self.options. After that, below, depending on the type of
  3395. # object that is created, it will strip the name of the object and the underline (if the original key was
  3396. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3397. # "toolchange"
  3398. for option in self.options:
  3399. if option.find(kind + "_") == 0:
  3400. oname = option[len(kind) + 1:]
  3401. obj.options[oname] = self.options[option]
  3402. obj.isHovering = False
  3403. obj.notHovering = True
  3404. # Initialize as per user request
  3405. # User must take care to implement initialize
  3406. # in a thread-safe way as is is likely that we
  3407. # have been invoked in a separate thread.
  3408. t1 = time.time()
  3409. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3410. try:
  3411. return_value = initialize(obj, self)
  3412. except Exception as e:
  3413. msg = '[ERROR_NOTCL] %s' % \
  3414. _("An internal error has ocurred. See shell.\n")
  3415. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3416. msg += traceback.format_exc()
  3417. self.inform.emit(msg)
  3418. # if str(e) == "Empty Geometry":
  3419. # self.inform.emit("[ERROR_NOTCL] )
  3420. # else:
  3421. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  3422. return "fail"
  3423. t2 = time.time()
  3424. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3425. if return_value == 'fail':
  3426. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3427. return "fail"
  3428. # Check units and convert if necessary
  3429. # This condition CAN be true because initialize() can change obj.units
  3430. if self.options["units"].upper() != obj.units.upper():
  3431. self.inform.emit('%s: %s' %
  3432. (_("Converting units to "), self.options["units"]))
  3433. obj.convert_units(self.options["units"])
  3434. t3 = time.time()
  3435. self.log.debug("%f seconds converting units." % (t3 - t2))
  3436. # Create the bounding box for the object and then add the results to the obj.options
  3437. # But not for Scripts or for Documents
  3438. if kind != 'document' and kind != 'script':
  3439. try:
  3440. xmin, ymin, xmax, ymax = obj.bounds()
  3441. obj.options['xmin'] = xmin
  3442. obj.options['ymin'] = ymin
  3443. obj.options['xmax'] = xmax
  3444. obj.options['ymax'] = ymax
  3445. except Exception as e:
  3446. log.warning("The object has no bounds properties. %s" % str(e))
  3447. return "fail"
  3448. # update the KeyWords list with the name of the file
  3449. self.myKeywords.append(obj.options['name'])
  3450. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3451. # Move the object to the main thread and let the app know that it is available.
  3452. obj.moveToThread(self.main_thread)
  3453. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3454. return obj
  3455. def new_excellon_object(self):
  3456. """
  3457. Creates a new, blank Excellon object.
  3458. :return: None
  3459. """
  3460. self.report_usage("new_excellon_object()")
  3461. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3462. def new_geometry_object(self):
  3463. """
  3464. Creates a new, blank and single-tool Geometry object.
  3465. :return: None
  3466. """
  3467. self.report_usage("new_geometry_object()")
  3468. def initialize(obj, self):
  3469. obj.multitool = False
  3470. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3471. def new_gerber_object(self):
  3472. """
  3473. Creates a new, blank Gerber object.
  3474. :return: None
  3475. """
  3476. self.report_usage("new_gerber_object()")
  3477. def initialize(grb_obj, self):
  3478. grb_obj.multitool = False
  3479. grb_obj.source_file = []
  3480. grb_obj.multigeo = False
  3481. grb_obj.follow = False
  3482. grb_obj.apertures = {}
  3483. grb_obj.solid_geometry = []
  3484. try:
  3485. grb_obj.options['xmin'] = 0
  3486. grb_obj.options['ymin'] = 0
  3487. grb_obj.options['xmax'] = 0
  3488. grb_obj.options['ymax'] = 0
  3489. except KeyError:
  3490. pass
  3491. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3492. def new_script_object(self, name=None, text=None):
  3493. """
  3494. Creates a new, blank TCL Script object.
  3495. :param name: a name for the new object
  3496. :return: None
  3497. """
  3498. self.report_usage("new_script_object()")
  3499. if text is not None:
  3500. new_source_file = text
  3501. else:
  3502. new_source_file = _(
  3503. "#\n"
  3504. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  3505. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  3506. "#\n\n"
  3507. "# FlatCAM commands list:\n"
  3508. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, "
  3509. "ClearCopper,\n"
  3510. "# Cncjob, Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, "
  3511. "GetNames,\n"
  3512. "# GetSys, ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillDrills,\n"
  3513. "# MillSlots, Mirror, New, NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"
  3514. "# Options, Paint, Panelize, Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, "
  3515. "SubtractPoly,\n"
  3516. "# SubtractRectangle, Version, WriteGCode\n"
  3517. "#\n\n"
  3518. )
  3519. def initialize(obj, self):
  3520. obj.source_file = deepcopy(new_source_file)
  3521. if name is None:
  3522. outname = 'new_script'
  3523. else:
  3524. outname = name
  3525. self.new_object('script', outname, initialize, plot=False)
  3526. def new_document_object(self):
  3527. """
  3528. Creates a new, blank Document object.
  3529. :return: None
  3530. """
  3531. self.report_usage("new_document_object()")
  3532. def initialize(obj, self):
  3533. obj.source_file = ""
  3534. self.new_object('document', 'new_document', initialize, plot=False)
  3535. def on_object_created(self, obj, plot, autoselect):
  3536. """
  3537. Event callback for object creation.
  3538. It will add the new object to the collection. After that it will plot the object in a threaded way
  3539. :param obj: The newly created FlatCAM object.
  3540. :param plot: if the newly create object t obe plotted
  3541. :param autoselect: if the newly created object to be autoselected after creation
  3542. :return: None
  3543. """
  3544. t0 = time.time() # DEBUG
  3545. self.log.debug("on_object_created()")
  3546. # The Collection might change the name if there is a collision
  3547. self.collection.append(obj)
  3548. # after adding the object to the collection always update the list of objects that are in the collection
  3549. self.all_objects_list = self.collection.get_list()
  3550. # self.inform.emit('[selected] %s created & selected: %s' %
  3551. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3552. if obj.kind == 'gerber':
  3553. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3554. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3555. elif obj.kind == 'excellon':
  3556. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3557. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3558. elif obj.kind == 'cncjob':
  3559. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3560. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3561. elif obj.kind == 'geometry':
  3562. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3563. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3564. elif obj.kind == 'script':
  3565. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3566. kind=obj.kind.capitalize(), color='orange', name=str(obj.options['name'])))
  3567. elif obj.kind == 'document':
  3568. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3569. kind=obj.kind.capitalize(), color='darkCyan', name=str(obj.options['name'])))
  3570. # update the SHELL auto-completer model with the name of the new object
  3571. self.shell._edit.set_model_data(self.myKeywords)
  3572. if autoselect:
  3573. # select the just opened object but deselect the previous ones
  3574. self.collection.set_all_inactive()
  3575. self.collection.set_active(obj.options["name"])
  3576. else:
  3577. self.collection.set_all_inactive()
  3578. # here it is done the object plotting
  3579. def worker_task(t_obj):
  3580. with self.proc_container.new(_("Plotting")):
  3581. if isinstance(t_obj, FlatCAMCNCjob):
  3582. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3583. else:
  3584. t_obj.plot()
  3585. t1 = time.time() # DEBUG
  3586. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3587. self.object_plotted.emit(t_obj)
  3588. # Send to worker
  3589. # self.worker.add_task(worker_task, [self])
  3590. if plot is True:
  3591. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3592. def on_object_changed(self, obj):
  3593. """
  3594. Called whenever the geometry of the object was changed in some way.
  3595. This require the update of it's bounding values so it can be the selected on canvas.
  3596. Update the bounding box data from obj.options
  3597. :param obj: the object that was changed
  3598. :return: None
  3599. """
  3600. xmin, ymin, xmax, ymax = obj.bounds()
  3601. obj.options['xmin'] = xmin
  3602. obj.options['ymin'] = ymin
  3603. obj.options['xmax'] = xmax
  3604. obj.options['ymax'] = ymax
  3605. log.debug("Object changed, updating the bounding box data on self.options")
  3606. # delete the old selection shape
  3607. self.delete_selection_shape()
  3608. self.should_we_save = True
  3609. def on_object_plotted(self, obj):
  3610. """
  3611. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3612. :param obj: object to be fit into view
  3613. :return: None
  3614. """
  3615. self.on_zoom_fit(None)
  3616. def options_read_form(self):
  3617. """
  3618. Same as it's equivalent from the defaults.
  3619. self.options use to store the preferences per project. No longer used.
  3620. :return: None
  3621. """
  3622. for option in self.options_form_fields:
  3623. self.options[option] = self.options_form_fields[option].get_value()
  3624. def options_write_form(self):
  3625. """
  3626. Same as it's equivalent from the defaults.
  3627. self.options use to store the preferences per project. No longer used.
  3628. :return: None
  3629. """
  3630. for option in self.options:
  3631. self.options_write_form_field(option)
  3632. def options_write_form_field(self, field):
  3633. """
  3634. Same as it's equivalent from the defaults.
  3635. self.options use to store the preferences per project. No longer used.
  3636. :return: None
  3637. """
  3638. try:
  3639. self.options_form_fields[field].set_value(self.options[field])
  3640. except KeyError:
  3641. # Changed from error to debug. This allows to have data stored
  3642. # which is not user-editable.
  3643. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  3644. pass
  3645. def on_about(self):
  3646. """
  3647. Displays the "about" dialog found in the Menu --> Help.
  3648. :return: None
  3649. """
  3650. self.report_usage("on_about")
  3651. version = self.version
  3652. version_date = self.version_date
  3653. beta = self.beta
  3654. class AboutDialog(QtWidgets.QDialog):
  3655. def __init__(self, parent=None):
  3656. QtWidgets.QDialog.__init__(self, parent)
  3657. # Icon and title
  3658. self.setWindowIcon(parent.app_icon)
  3659. self.setWindowTitle(_("About FlatCAM"))
  3660. self.resize(600, 200)
  3661. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3662. # self.setStyleSheet(
  3663. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3664. # "background-attachment: fixed"
  3665. # )
  3666. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3667. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3668. # palette = QtGui.QPalette()
  3669. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3670. # self.setPalette(palette)
  3671. logo = QtWidgets.QLabel()
  3672. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3673. title = QtWidgets.QLabel(
  3674. "<font size=8><B>FlatCAM</B></font><BR>"
  3675. "{title}<BR>"
  3676. "<BR>"
  3677. "<BR>"
  3678. # "<B>{devel}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3679. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3680. # "<b>{down}</B> area &nbsp;&nbsp;&nbsp;&nbsp;"
  3681. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3682. # "<b> {issue}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3683. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3684. "<B>{issue}</B></a><BR>".format(
  3685. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3686. devel=_("Development"),
  3687. down=_("DOWNLOAD"),
  3688. issue=_("Issue tracker"))
  3689. )
  3690. title.setOpenExternalLinks(True)
  3691. closebtn = QtWidgets.QPushButton(_("Close"))
  3692. tab_widget = QtWidgets.QTabWidget()
  3693. description_label = QtWidgets.QLabel(
  3694. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3695. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3696. version=version,
  3697. beta=('BETA' if beta else ''),
  3698. date=version_date,
  3699. arch=platform.architecture()[0])
  3700. )
  3701. description_label.setOpenExternalLinks(True)
  3702. license_label = QtWidgets.QLabel(
  3703. _(
  3704. '\n'
  3705. 'Licensed under the MIT license:\n'
  3706. 'http://www.opensource.org/licenses/mit-license.php\n\n'
  3707. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3708. 'of this software and associated documentation files (the "Software"), to deal\n'
  3709. 'in the Software without restriction, including without limitation the rights\n'
  3710. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3711. 'copies of the Software, and to permit persons to whom the Software is\n'
  3712. 'furnished to do so, subject to the following conditions:\n\n'
  3713. 'The above copyright notice and this permission notice shall be included in\n'
  3714. 'all copies or substantial portions of the Software.\n\n'
  3715. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3716. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3717. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3718. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3719. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3720. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3721. 'THE SOFTWARE.'
  3722. )
  3723. )
  3724. license_label.setOpenExternalLinks(True)
  3725. attributions_label = QtWidgets.QLabel(
  3726. _(
  3727. 'Some of the icons used are from the following sources: <BR>'
  3728. '<div>Icons made by <a href="https://www.flaticon.com/authors/freepik" '
  3729. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  3730. 'title="Flaticon">www.flaticon.com</a></div><br>'
  3731. 'Icons by <a target="_blank" href="https://icons8.com">Icons8</a>'
  3732. )
  3733. )
  3734. # layouts
  3735. layout1 = QtWidgets.QVBoxLayout()
  3736. layout1_1 = QtWidgets.QHBoxLayout()
  3737. layout1_2 = QtWidgets.QHBoxLayout()
  3738. layout2 = QtWidgets.QHBoxLayout()
  3739. layout3 = QtWidgets.QHBoxLayout()
  3740. self.setLayout(layout1)
  3741. layout1.addLayout(layout1_1)
  3742. layout1.addLayout(layout1_2)
  3743. layout1.addLayout(layout2)
  3744. layout1.addLayout(layout3)
  3745. layout1_1.addStretch()
  3746. layout1_1.addWidget(description_label)
  3747. layout1_2.addWidget(tab_widget)
  3748. self.splash_tab = QtWidgets.QWidget()
  3749. self.splash_tab.setObjectName("splash_about")
  3750. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3751. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3752. tab_widget.addTab(self.splash_tab, _("Splash"))
  3753. self.programmmers_tab = QtWidgets.QWidget()
  3754. self.programmmers_tab.setObjectName("programmers_about")
  3755. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3756. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3757. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3758. self.translators_tab = QtWidgets.QWidget()
  3759. self.translators_tab.setObjectName("translators_about")
  3760. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3761. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3762. tab_widget.addTab(self.translators_tab, _("Translators"))
  3763. self.license_tab = QtWidgets.QWidget()
  3764. self.license_tab.setObjectName("license_about")
  3765. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3766. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3767. tab_widget.addTab(self.license_tab, _("License"))
  3768. self.attributions_tab = QtWidgets.QWidget()
  3769. self.attributions_tab.setObjectName("attributions_about")
  3770. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  3771. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  3772. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  3773. self.splash_tab_layout.addWidget(logo, stretch=0)
  3774. self.splash_tab_layout.addWidget(title, stretch=1)
  3775. pal = QtGui.QPalette()
  3776. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3777. self.prog_form_lay = QtWidgets.QFormLayout()
  3778. self.prog_form_lay.setHorizontalSpacing(20)
  3779. prog_widget = QtWidgets.QWidget()
  3780. prog_widget.setLayout(self.prog_form_lay)
  3781. prog_scroll = QtWidgets.QScrollArea()
  3782. prog_scroll.setWidget(prog_widget)
  3783. prog_scroll.setWidgetResizable(True)
  3784. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3785. prog_scroll.setPalette(pal)
  3786. self.programmmers_tab_layout.addWidget(prog_scroll)
  3787. self.prog_form_lay.addRow(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")),
  3788. QtWidgets.QLabel('<b>%s</b>' % _("Status")))
  3789. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Juan Pablo Caram"),
  3790. QtWidgets.QLabel('%s' % _("Program Author")))
  3791. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Denis Hayrullin"))
  3792. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Kamil Sopko"))
  3793. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marius Stanciu"),
  3794. QtWidgets.QLabel('%s' % _("Maintainer >= 2019")))
  3795. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3796. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Alex Lazar"))
  3797. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Matthieu Berthomé"))
  3798. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Evans"))
  3799. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Victor Benso"))
  3800. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3801. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Barnaby Walters"))
  3802. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"))
  3803. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lei Zheng"))
  3804. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marco A Quezada"))
  3805. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3806. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Cedric Dussud"))
  3807. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Chris Hemingway"))
  3808. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Damian Wrobel"))
  3809. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Daniel Sallin"))
  3810. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3811. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Bruno Vunderl"))
  3812. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Gonzalo Lopez"))
  3813. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jakob Staudt"))
  3814. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Smith"))
  3815. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3816. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lubos Medovarsky"))
  3817. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Steve Martina"))
  3818. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Thomas Duffin"))
  3819. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3820. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Idechix"))
  3821. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@SM"))
  3822. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@grbf"))
  3823. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Symonty"))
  3824. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@mgix"))
  3825. self.translator_grid_lay = QtWidgets.QGridLayout()
  3826. # trans_widget = QtWidgets.QWidget()
  3827. # trans_widget.setLayout(self.translator_grid_lay)
  3828. # self.translators_tab_layout.addWidget(trans_widget)
  3829. # self.translators_tab_layout.addStretch()
  3830. trans_widget = QtWidgets.QWidget()
  3831. trans_widget.setLayout(self.translator_grid_lay)
  3832. trans_scroll = QtWidgets.QScrollArea()
  3833. trans_scroll.setWidget(trans_widget)
  3834. trans_scroll.setWidgetResizable(True)
  3835. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3836. trans_scroll.setPalette(pal)
  3837. self.translators_tab_layout.addWidget(trans_scroll)
  3838. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  3839. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  3840. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3841. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Brasilian - Portuguese"), 1, 0)
  3842. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  3843. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 1, 2)
  3844. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  3845. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 2, 1)
  3846. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 2)
  3847. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  3848. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 3, 1)
  3849. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  3850. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  3851. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  3852. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  3853. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  3854. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  3855. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 2)
  3856. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  3857. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 6, 1)
  3858. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 2)
  3859. self.translator_grid_lay.setColumnStretch(0, 0)
  3860. self.translators_tab_layout.addStretch()
  3861. self.license_tab_layout.addWidget(license_label)
  3862. self.license_tab_layout.addStretch()
  3863. self.attributions_tab_layout.addWidget(attributions_label)
  3864. self.attributions_tab_layout.addStretch()
  3865. layout3.addStretch()
  3866. layout3.addWidget(closebtn)
  3867. closebtn.clicked.connect(self.accept)
  3868. AboutDialog(self.ui).exec_()
  3869. def on_file_savedefaults(self):
  3870. """
  3871. Callback for menu item File->Save Defaults. Saves application default options
  3872. ``self.defaults`` to current_defaults.FlatConfig.
  3873. :return: None
  3874. """
  3875. self.save_defaults()
  3876. # def on_app_exit(self):
  3877. # self.report_usage("on_app_exit()")
  3878. #
  3879. # if self.collection.get_list():
  3880. # msgbox = QtWidgets.QMessageBox()
  3881. # # msgbox.setText("<B>Save changes ...</B>")
  3882. # msgbox.setText("There are files/objects opened in FlatCAM. "
  3883. # "\n"
  3884. # "Do you want to Save the project?")
  3885. # msgbox.setWindowTitle("Save changes")
  3886. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3887. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  3888. # QtWidgets.QMessageBox.Cancel)
  3889. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  3890. #
  3891. # response = msgbox.exec_()
  3892. #
  3893. # if response == QtWidgets.QMessageBox.Yes:
  3894. # self.on_file_saveprojectas(thread=False)
  3895. # elif response == QtWidgets.QMessageBox.Cancel:
  3896. # return
  3897. # self.save_defaults()
  3898. # else:
  3899. # self.save_defaults()
  3900. # log.debug("Application defaults saved ... Exit event.")
  3901. # QtWidgets.qApp.quit()
  3902. def save_defaults(self, silent=False, data_path=None, first_time=False):
  3903. """
  3904. Saves application default options
  3905. ``self.defaults`` to current_defaults.FlatConfig file.
  3906. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  3907. used at the next launch of the application.
  3908. :param silent: whether to display a message in status bar or not; boolean
  3909. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  3910. When the application is portable it should be a mobile location.
  3911. :return: None
  3912. """
  3913. self.report_usage("save_defaults")
  3914. if data_path is None:
  3915. data_path = self.data_path
  3916. # Read options from file
  3917. try:
  3918. f = open(data_path + "/current_defaults.FlatConfig")
  3919. defaults_file_content = f.read()
  3920. f.close()
  3921. except:
  3922. e = sys.exc_info()[0]
  3923. App.log.error("Could not load defaults file.")
  3924. App.log.error(str(e))
  3925. self.inform.emit('[ERROR_NOTCL] %s' %
  3926. _("Could not load defaults file."))
  3927. return
  3928. try:
  3929. defaults = json.loads(defaults_file_content)
  3930. except:
  3931. e = sys.exc_info()[0]
  3932. App.log.error("Failed to parse defaults file.")
  3933. App.log.error(str(e))
  3934. self.inform.emit('[ERROR_NOTCL] %s' %
  3935. _("Failed to parse defaults file."))
  3936. return
  3937. # Update options
  3938. self.defaults_read_form()
  3939. defaults.update(self.defaults)
  3940. self.propagate_defaults(silent=True)
  3941. # Save the toolbar view
  3942. tb_status = 0
  3943. if self.ui.toolbarfile.isVisible():
  3944. tb_status += 1
  3945. if self.ui.toolbargeo.isVisible():
  3946. tb_status += 2
  3947. if self.ui.toolbarview.isVisible():
  3948. tb_status += 4
  3949. if self.ui.toolbartools.isVisible():
  3950. tb_status += 8
  3951. if self.ui.exc_edit_toolbar.isVisible():
  3952. tb_status += 16
  3953. if self.ui.geo_edit_toolbar.isVisible():
  3954. tb_status += 32
  3955. if self.ui.grb_edit_toolbar.isVisible():
  3956. tb_status += 64
  3957. if self.ui.snap_toolbar.isVisible():
  3958. tb_status += 128
  3959. if self.ui.toolbarshell.isVisible():
  3960. tb_status += 256
  3961. if first_time is False:
  3962. self.defaults["global_toolbar_view"] = tb_status
  3963. # Save update options
  3964. try:
  3965. f = open(data_path + "/current_defaults.FlatConfig", "w")
  3966. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  3967. f.close()
  3968. except:
  3969. self.inform.emit('[ERROR_NOTCL] %s' %
  3970. _("Failed to write defaults to file."))
  3971. return
  3972. if not silent:
  3973. self.inform.emit('[success] %s' %
  3974. _("Preferences saved."))
  3975. def save_factory_defaults(self, silent=False, data_path=None):
  3976. """
  3977. Saves application factory default options
  3978. ``self.defaults`` to factory_defaults.FlatConfig.
  3979. It's a one time job done just after the first install.
  3980. :param silent: whether to display a message in status bar or not; boolean
  3981. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  3982. When the application is portable it should be a mobile location.
  3983. :return: None
  3984. """
  3985. self.report_usage("save_factory_defaults")
  3986. if data_path is None:
  3987. data_path = self.data_path
  3988. # Read options from file
  3989. try:
  3990. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  3991. factory_defaults_file_content = f_f_def.read()
  3992. f_f_def.close()
  3993. except:
  3994. e = sys.exc_info()[0]
  3995. App.log.error("Could not load factory defaults file.")
  3996. App.log.error(str(e))
  3997. self.inform.emit('[ERROR_NOTCL] %s' %
  3998. _("Could not load factory defaults file."))
  3999. return
  4000. try:
  4001. factory_defaults = json.loads(factory_defaults_file_content)
  4002. except:
  4003. e = sys.exc_info()[0]
  4004. App.log.error("Failed to parse factory defaults file.")
  4005. App.log.error(str(e))
  4006. self.inform.emit('[ERROR_NOTCL] %s' %
  4007. _("Failed to parse factory defaults file."))
  4008. return
  4009. # Update options
  4010. self.defaults_read_form()
  4011. factory_defaults.update(self.defaults)
  4012. self.propagate_defaults(silent=True)
  4013. # Save update options
  4014. try:
  4015. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  4016. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  4017. f_f_def_s.close()
  4018. except:
  4019. self.inform.emit('[ERROR_NOTCL] %s' %
  4020. _("Failed to write factory defaults to file."))
  4021. return
  4022. if silent is False:
  4023. self.inform.emit(_("Factory defaults saved."))
  4024. def final_save(self):
  4025. """
  4026. Callback for doing a preferences save to file whenever the application is about to quit.
  4027. If the project has changes, it will ask the user to save the project.
  4028. :return: None
  4029. """
  4030. if self.save_in_progress:
  4031. self.inform.emit('[WARNING_NOTCL] %s' %
  4032. _("Application is saving the project. Please wait ..."))
  4033. return
  4034. if self.should_we_save and self.collection.get_list():
  4035. msgbox = QtWidgets.QMessageBox()
  4036. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  4037. "\n"
  4038. "Do you want to Save the project?"))
  4039. msgbox.setWindowTitle(_("Save changes"))
  4040. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4041. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4042. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4043. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4044. msgbox.setDefaultButton(bt_yes)
  4045. msgbox.exec_()
  4046. response = msgbox.clickedButton()
  4047. if response == bt_yes:
  4048. try:
  4049. self.trayIcon.hide()
  4050. except:
  4051. pass
  4052. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  4053. elif response == bt_no:
  4054. try:
  4055. self.trayIcon.hide()
  4056. except:
  4057. pass
  4058. self.quit_application()
  4059. elif response == bt_cancel:
  4060. return
  4061. else:
  4062. try:
  4063. self.trayIcon.hide()
  4064. except:
  4065. pass
  4066. self.quit_application()
  4067. def quit_application(self):
  4068. """
  4069. Called (as a pyslot or not) when the application is quit.
  4070. :return: None
  4071. """
  4072. self.save_defaults()
  4073. log.debug("App.final_save() --> App Defaults saved.")
  4074. if self.cmd_line_headless != 1:
  4075. # save app state to file
  4076. settings = QSettings("Open Source", "FlatCAM")
  4077. settings.setValue('saved_gui_state', self.ui.saveState())
  4078. settings.setValue('maximized_gui', self.ui.isMaximized())
  4079. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  4080. settings.setValue(
  4081. 'notebook_font_size',
  4082. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  4083. )
  4084. settings.setValue('axis_font_size',
  4085. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value())
  4086. settings.setValue(
  4087. 'textbox_font_size',
  4088. self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  4089. )
  4090. settings.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  4091. # This will write the setting to the platform specific storage.
  4092. del settings
  4093. log.debug("App.final_save() --> App UI state saved.")
  4094. QtWidgets.qApp.quit()
  4095. def on_portable_checked(self, state):
  4096. """
  4097. Callback called when the checkbox in Preferences GUI is checked.
  4098. It will set the application as portable by creating the preferences and recent files in the
  4099. 'config' folder found in the FlatCAM installation folder.
  4100. :param state: boolean, the state of the checkbox when clicked/checked
  4101. :return:
  4102. """
  4103. line_no = 0
  4104. data = None
  4105. if sys.platform != 'win32':
  4106. # this won't work in Linux or MacOS
  4107. return
  4108. # test if the app was frozen and choose the path for the configuration file
  4109. if getattr(sys, "frozen", False) is True:
  4110. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  4111. else:
  4112. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  4113. config_file = current_data_path + '\\configuration.txt'
  4114. try:
  4115. with open(config_file, 'r') as f:
  4116. try:
  4117. data = f.readlines()
  4118. except Exception as e:
  4119. log.debug('App.__init__() -->%s' % str(e))
  4120. return
  4121. except FileNotFoundError:
  4122. pass
  4123. for line in data:
  4124. line = line.strip('\n')
  4125. param = str(line).rpartition('=')
  4126. if param[0] == 'portable':
  4127. break
  4128. line_no += 1
  4129. if state:
  4130. data[line_no] = 'portable=True\n'
  4131. # create the new defauults files
  4132. # create current_defaults.FlatConfig file if there is none
  4133. try:
  4134. f = open(current_data_path + '/current_defaults.FlatConfig')
  4135. f.close()
  4136. except IOError:
  4137. App.log.debug('Creating empty current_defaults.FlatConfig')
  4138. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  4139. json.dump({}, f)
  4140. f.close()
  4141. # create factory_defaults.FlatConfig file if there is none
  4142. try:
  4143. f = open(current_data_path + '/factory_defaults.FlatConfig')
  4144. f.close()
  4145. except IOError:
  4146. App.log.debug('Creating empty factory_defaults.FlatConfig')
  4147. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  4148. json.dump({}, f)
  4149. f.close()
  4150. try:
  4151. f = open(current_data_path + '/recent.json')
  4152. f.close()
  4153. except IOError:
  4154. App.log.debug('Creating empty recent.json')
  4155. f = open(current_data_path + '/recent.json', 'w')
  4156. json.dump([], f)
  4157. f.close()
  4158. try:
  4159. fp = open(current_data_path + '/recent_projects.json')
  4160. fp.close()
  4161. except IOError:
  4162. App.log.debug('Creating empty recent_projects.json')
  4163. fp = open(current_data_path + '/recent_projects.json', 'w')
  4164. json.dump([], fp)
  4165. fp.close()
  4166. # save the current defaults to the new defaults file
  4167. self.save_defaults(silent=True, data_path=current_data_path)
  4168. self.save_factory_defaults(silent=True, data_path=current_data_path)
  4169. else:
  4170. data[line_no] = 'portable=False\n'
  4171. with open(config_file, 'w') as f:
  4172. f.writelines(data)
  4173. def on_toggle_shell(self):
  4174. """
  4175. Toggle shell: if is visible close it, if it is closed then open it
  4176. :return:
  4177. """
  4178. self.report_usage("on_toggle_shell()")
  4179. if self.ui.shell_dock.isVisible():
  4180. self.ui.shell_dock.hide()
  4181. else:
  4182. self.ui.shell_dock.show()
  4183. def on_register_files(self, obj_type=None):
  4184. """
  4185. Called whenever there is a need to register file extensions with FlatCAM.
  4186. Works only in Windows and should be called only when FlatCAM is run in Windows.
  4187. :param obj_type: the type of object to be register for.
  4188. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  4189. :return: None
  4190. """
  4191. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  4192. new_reg_path = 'Software\\Classes\\'
  4193. # find if the current user is admin
  4194. try:
  4195. is_admin = os.getuid() == 0
  4196. except AttributeError:
  4197. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  4198. if is_admin is True:
  4199. root_path = winreg.HKEY_LOCAL_MACHINE
  4200. else:
  4201. root_path = winreg.HKEY_CURRENT_USER
  4202. # create the keys
  4203. def set_reg(name, root_path, new_reg_path, value):
  4204. try:
  4205. winreg.CreateKey(root_path, new_reg_path)
  4206. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  4207. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  4208. return True
  4209. except WindowsError:
  4210. return False
  4211. # delete key in registry
  4212. def delete_reg(root_path, reg_path, key_to_del):
  4213. key_to_del_path = reg_path + key_to_del
  4214. try:
  4215. winreg.DeleteKey(root_path, key_to_del_path)
  4216. return True
  4217. except WindowsError:
  4218. return False
  4219. if obj_type is None or obj_type == 'excellon':
  4220. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4221. exc_list = [x for x in exc_list if x != '']
  4222. # register all keys in the Preferences window
  4223. for ext in exc_list:
  4224. new_k = new_reg_path + '.%s' % ext
  4225. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4226. # and unregister those that are no longer in the Preferences windows but are in the file
  4227. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  4228. if ext not in exc_list:
  4229. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4230. # now write the updated extensions to the self.defaults
  4231. # new_ext = ''
  4232. # for ext in exc_list:
  4233. # new_ext = new_ext + ext + ', '
  4234. # self.defaults["fa_excellon"] = new_ext
  4235. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  4236. if obj_type is None or obj_type == 'gcode':
  4237. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4238. gco_list = [x for x in gco_list if x != '']
  4239. # register all keys in the Preferences window
  4240. for ext in gco_list:
  4241. new_k = new_reg_path + '.%s' % ext
  4242. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4243. # and unregister those that are no longer in the Preferences windows but are in the file
  4244. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  4245. if ext not in gco_list:
  4246. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4247. # now write the updated extensions to the self.defaults
  4248. # new_ext = ''
  4249. # for ext in gco_list:
  4250. # new_ext = new_ext + ext + ', '
  4251. # self.defaults["fa_gcode"] = new_ext
  4252. self.inform.emit('[success] %s' %
  4253. _("Selected GCode file extensions registered with FlatCAM."))
  4254. if obj_type is None or obj_type == 'gerber':
  4255. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4256. grb_list = [x for x in grb_list if x != '']
  4257. # register all keys in the Preferences window
  4258. for ext in grb_list:
  4259. new_k = new_reg_path + '.%s' % ext
  4260. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4261. # and unregister those that are no longer in the Preferences windows but are in the file
  4262. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  4263. if ext not in grb_list:
  4264. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4265. # now write the updated extensions to the self.defaults
  4266. # new_ext = ''
  4267. # for ext in grb_list:
  4268. # new_ext = new_ext + ext + ', '
  4269. # self.defaults["fa_gerber"] = new_ext
  4270. self.inform.emit('[success] %s' %
  4271. _("Selected Gerber file extensions registered with FlatCAM."))
  4272. def add_extension(self, ext_type):
  4273. if ext_type == 'excellon':
  4274. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4275. if new_ext == '':
  4276. return
  4277. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4278. if new_ext in old_val:
  4279. return
  4280. old_val.append(new_ext)
  4281. old_val.sort()
  4282. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4283. if ext_type == 'gcode':
  4284. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4285. if new_ext == '':
  4286. return
  4287. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4288. if new_ext in old_val:
  4289. return
  4290. old_val.append(new_ext)
  4291. old_val.sort()
  4292. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4293. if ext_type == 'gerber':
  4294. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4295. if new_ext == '':
  4296. return
  4297. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4298. if new_ext in old_val:
  4299. return
  4300. old_val.append(new_ext)
  4301. old_val.sort()
  4302. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4303. if ext_type == 'keyword':
  4304. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4305. if new_kw == '':
  4306. return
  4307. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4308. if new_kw in old_val:
  4309. return
  4310. old_val.append(new_kw)
  4311. old_val.sort()
  4312. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4313. # update the self.myKeywords so the model is updated
  4314. self.autocomplete_kw_list = \
  4315. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4316. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4317. self.shell._edit.set_model_data(self.myKeywords)
  4318. def del_extension(self, ext_type):
  4319. if ext_type == 'excellon':
  4320. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4321. if new_ext == '':
  4322. return
  4323. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4324. if new_ext not in old_val:
  4325. return
  4326. old_val.remove(new_ext)
  4327. old_val.sort()
  4328. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4329. if ext_type == 'gcode':
  4330. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4331. if new_ext == '':
  4332. return
  4333. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4334. if new_ext not in old_val:
  4335. return
  4336. old_val.remove(new_ext)
  4337. old_val.sort()
  4338. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4339. if ext_type == 'gerber':
  4340. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4341. if new_ext == '':
  4342. return
  4343. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4344. if new_ext not in old_val:
  4345. return
  4346. old_val.remove(new_ext)
  4347. old_val.sort()
  4348. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4349. if ext_type == 'keyword':
  4350. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4351. if new_kw == '':
  4352. return
  4353. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4354. if new_kw not in old_val:
  4355. return
  4356. old_val.remove(new_kw)
  4357. old_val.sort()
  4358. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4359. # update the self.myKeywords so the model is updated
  4360. self.autocomplete_kw_list = \
  4361. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4362. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4363. self.shell._edit.set_model_data(self.myKeywords)
  4364. def restore_extensions(self, ext_type):
  4365. if ext_type == 'excellon':
  4366. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  4367. # for the ability to open Excellon files with .txt extension
  4368. new_exc_list = deepcopy(self.exc_list)
  4369. try:
  4370. new_exc_list.remove('txt')
  4371. except ValueError:
  4372. pass
  4373. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  4374. if ext_type == 'gcode':
  4375. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  4376. if ext_type == 'gerber':
  4377. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  4378. if ext_type == 'keyword':
  4379. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  4380. # update the self.myKeywords so the model is updated
  4381. self.autocomplete_kw_list = self.default_keywords
  4382. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4383. self.shell._edit.set_model_data(self.myKeywords)
  4384. def delete_all_extensions(self, ext_type):
  4385. if ext_type == 'excellon':
  4386. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4387. if ext_type == 'gcode':
  4388. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4389. if ext_type == 'gerber':
  4390. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4391. if ext_type == 'keyword':
  4392. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4393. # update the self.myKeywords so the model is updated
  4394. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4395. self.shell._edit.set_model_data(self.myKeywords)
  4396. def on_edit_join(self, name=None):
  4397. """
  4398. Callback for Edit->Join. Joins the selected geometry objects into
  4399. a new one.
  4400. :return: None
  4401. """
  4402. self.report_usage("on_edit_join()")
  4403. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4404. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4405. geo_type_list = set()
  4406. objs = self.collection.get_selected()
  4407. if len(objs) < 2:
  4408. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4409. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4410. return 'fail'
  4411. for obj in objs:
  4412. geo_type_list.add(obj.multigeo)
  4413. # if len(geo_type_list) == 1 means that all list elements are the same
  4414. if len(geo_type_list) != 1:
  4415. self.inform.emit('[ERROR] %s' %
  4416. _("Failed join. The Geometry objects are of different types.\n"
  4417. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4418. "convert from one to another and retry joining \n"
  4419. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4420. "the result may not be what was expected. \n"
  4421. "Check the generated GCODE."))
  4422. return
  4423. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4424. if True in geo_type_list:
  4425. def initialize(obj, app):
  4426. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=True)
  4427. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4428. for v in obj.tools.values():
  4429. v['data']['name'] = obj_name_multi
  4430. self.new_object("geometry", obj_name_multi, initialize)
  4431. else:
  4432. def initialize(obj, app):
  4433. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=False)
  4434. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4435. for v in obj.tools.values():
  4436. v['data']['name'] = obj_name_single
  4437. self.new_object("geometry", obj_name_single, initialize)
  4438. self.should_we_save = True
  4439. def on_edit_join_exc(self):
  4440. """
  4441. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4442. a new Excellon.
  4443. :return: None
  4444. """
  4445. self.report_usage("on_edit_join_exc()")
  4446. objs = self.collection.get_selected()
  4447. for obj in objs:
  4448. if not isinstance(obj, FlatCAMExcellon):
  4449. self.inform.emit('[ERROR_NOTCL] %s' %
  4450. _("Failed. Excellon joining works only on Excellon objects."))
  4451. return
  4452. if len(objs) < 2:
  4453. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4454. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4455. return 'fail'
  4456. def initialize(obj, app):
  4457. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=obj)
  4458. self.new_object("excellon", 'Combo_Excellon', initialize)
  4459. self.should_we_save = True
  4460. def on_edit_join_grb(self):
  4461. """
  4462. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4463. a new Gerber object.
  4464. :return: None
  4465. """
  4466. self.report_usage("on_edit_join_grb()")
  4467. objs = self.collection.get_selected()
  4468. for obj in objs:
  4469. if not isinstance(obj, FlatCAMGerber):
  4470. self.inform.emit('[ERROR_NOTCL] %s' %
  4471. _("Failed. Gerber joining works only on Gerber objects."))
  4472. return
  4473. if len(objs) < 2:
  4474. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4475. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4476. return 'fail'
  4477. def initialize(obj, app):
  4478. FlatCAMGerber.merge(self, grb_list=objs, grb_final=obj)
  4479. self.new_object("gerber", 'Combo_Gerber', initialize)
  4480. self.should_we_save = True
  4481. def on_convert_singlegeo_to_multigeo(self):
  4482. """
  4483. Called for converting a Geometry object from single-geo to multi-geo.
  4484. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4485. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4486. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4487. the solid-geometry of that tool.
  4488. :return: None
  4489. """
  4490. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4491. obj = self.collection.get_active()
  4492. if obj is None:
  4493. self.inform.emit('[ERROR_NOTCL] %s' %
  4494. _("Failed. Select a Geometry Object and try again."))
  4495. return
  4496. if not isinstance(obj, FlatCAMGeometry):
  4497. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4498. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4499. return
  4500. obj.multigeo = True
  4501. for tooluid, dict_value in obj.tools.items():
  4502. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4503. if not isinstance(obj.solid_geometry, list):
  4504. obj.solid_geometry = [obj.solid_geometry]
  4505. obj.solid_geometry[:] = []
  4506. obj.plot()
  4507. self.should_we_save = True
  4508. self.inform.emit('[success] %s' %
  4509. _("A Geometry object was converted to MultiGeo type."))
  4510. def on_convert_multigeo_to_singlegeo(self):
  4511. """
  4512. Called for converting a Geometry object from multi-geo to single-geo.
  4513. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4514. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4515. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4516. the solid-geometry of that tool.
  4517. :return: None
  4518. """
  4519. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4520. obj = self.collection.get_active()
  4521. if obj is None:
  4522. self.inform.emit('[ERROR_NOTCL] %s' %
  4523. _("Failed. Select a Geometry Object and try again."))
  4524. return
  4525. if not isinstance(obj, FlatCAMGeometry):
  4526. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4527. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4528. return
  4529. obj.multigeo = False
  4530. total_solid_geometry = []
  4531. for tooluid, dict_value in obj.tools.items():
  4532. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4533. # clear the original geometry
  4534. dict_value['solid_geometry'][:] = []
  4535. obj.solid_geometry = deepcopy(total_solid_geometry)
  4536. obj.plot()
  4537. self.should_we_save = True
  4538. self.inform.emit('[success] %s' %
  4539. _("A Geometry object was converted to SingleGeo type."))
  4540. def on_options_dict_change(self, field):
  4541. """
  4542. Called whenever a key changed in the self.options dictionary. This dict was used to store the preferences of the
  4543. current project. This feature is no longer used.
  4544. :param field:
  4545. :return:
  4546. """
  4547. self.options_write_form_field(field)
  4548. if field == "units":
  4549. self.set_screen_units(self.options['units'])
  4550. def on_defaults_dict_change(self, field):
  4551. """
  4552. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4553. Edit -> Preferences tab window.
  4554. :param field: the key of the self.defaults dictionary that was changed.
  4555. :return: None
  4556. """
  4557. self.defaults_write_form_field(field)
  4558. if field == "units":
  4559. self.set_screen_units(self.defaults['units'])
  4560. def set_screen_units(self, units):
  4561. """
  4562. Set the FlatCAM units on the status bar.
  4563. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4564. :return: None
  4565. """
  4566. self.ui.units_label.setText("[" + units.lower() + "]")
  4567. def on_toggle_units(self, no_pref=False):
  4568. """
  4569. Callback for the Units radio-button change in the Preferences tab.
  4570. Changes the application's default units adn for the project too.
  4571. If changing the project's units, the change propagates to all of
  4572. the objects in the project.
  4573. :return: None
  4574. """
  4575. self.report_usage("on_toggle_units")
  4576. if self.toggle_units_ignore:
  4577. return
  4578. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4579. # If option is the same, then ignore
  4580. if new_units == self.defaults["units"].upper():
  4581. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4582. return
  4583. # Options to scale
  4584. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin', "gerber_isooverlap",
  4585. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f"
  4586. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  4587. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4588. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  4589. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  4590. "excellon_editor_slot_lin_pitch",
  4591. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4592. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4593. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  4594. "geometry_feedrate_probe", "geometry_startz",
  4595. 'cncjob_tooldia',
  4596. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4597. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia"
  4598. "tools_2sided_drilldia", "tools_film_boundary",
  4599. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4600. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4601. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4602. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4603. "tools_transform_offset_y",
  4604. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4605. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4606. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4607. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4608. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance"]
  4609. def scale_options(sfactor):
  4610. for dim in dimensions:
  4611. if dim == 'excellon_toolchangexy':
  4612. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4613. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4614. coords_xy[0] *= sfactor
  4615. coords_xy[1] *= sfactor
  4616. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4617. elif dim == 'geometry_toolchangexy':
  4618. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4619. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4620. coords_xy[0] *= sfactor
  4621. coords_xy[1] *= sfactor
  4622. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4623. elif dim == 'geometry_cnctooldia':
  4624. tools_diameters = []
  4625. try:
  4626. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4627. tools_diameters = [eval(a) for a in tools_string if a != '']
  4628. except Exception as e:
  4629. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4630. self.options['geometry_cnctooldia'] = ''
  4631. for t in range(len(tools_diameters)):
  4632. tools_diameters[t] *= sfactor
  4633. self.options['geometry_cnctooldia'] += "%f," % tools_diameters[t]
  4634. elif dim == 'tools_ncctools':
  4635. ncctools = []
  4636. try:
  4637. tools_string = self.defaults["tools_ncctools"].split(",")
  4638. ncctools = [eval(a) for a in tools_string if a != '']
  4639. except Exception as e:
  4640. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4641. self.options['tools_ncctools'] = ''
  4642. for t in range(len(ncctools)):
  4643. ncctools[t] *= sfactor
  4644. self.options['tools_ncctools'] += "%f," % ncctools[t]
  4645. elif dim == 'tools_solderpaste_tools':
  4646. sptools = []
  4647. try:
  4648. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4649. sptools = [eval(a) for a in tools_string if a != '']
  4650. except Exception as e:
  4651. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4652. self.options['tools_solderpaste_tools'] = ""
  4653. for t in range(len(sptools)):
  4654. sptools[t] *= sfactor
  4655. self.options['tools_solderpaste_tools'] += "%f," % sptools[t]
  4656. elif dim == 'tools_solderpaste_xy_toolchange':
  4657. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4658. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4659. sp_coords[0] *= sfactor
  4660. sp_coords[1] *= sfactor
  4661. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  4662. elif dim == 'global_gridx' or dim == 'global_gridy':
  4663. if new_units == 'IN':
  4664. val = 0.1
  4665. try:
  4666. val = float(self.defaults[dim]) * sfactor
  4667. except Exception as e:
  4668. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4669. self.options[dim] = float('%.6f' % val)
  4670. else:
  4671. val = 0.1
  4672. try:
  4673. val = float(self.defaults[dim]) * sfactor
  4674. except Exception as e:
  4675. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4676. self.options[dim] = float('%.4f' % val)
  4677. else:
  4678. val = 0.1
  4679. try:
  4680. val = float(self.options[dim]) * sfactor
  4681. except Exception as e:
  4682. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  4683. self.options[dim] = val
  4684. def scale_defaults(sfactor):
  4685. for dim in dimensions:
  4686. if dim == 'excellon_toolchangexy':
  4687. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4688. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4689. coords_xy[0] *= sfactor
  4690. coords_xy[1] *= sfactor
  4691. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4692. elif dim == 'geometry_toolchangexy':
  4693. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4694. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4695. coords_xy[0] *= sfactor
  4696. coords_xy[1] *= sfactor
  4697. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4698. elif dim == 'geometry_cnctooldia':
  4699. tools_diameters = []
  4700. try:
  4701. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4702. tools_diameters = [eval(a) for a in tools_string if a != '']
  4703. except Exception as e:
  4704. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4705. self.defaults['geometry_cnctooldia'] = ''
  4706. for t in range(len(tools_diameters)):
  4707. tools_diameters[t] *= sfactor
  4708. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  4709. elif dim == 'tools_ncctools':
  4710. ncctools = []
  4711. try:
  4712. tools_string = self.defaults["tools_ncctools"].split(",")
  4713. ncctools = [eval(a) for a in tools_string if a != '']
  4714. except Exception as e:
  4715. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4716. self.defaults['tools_ncctools'] = ''
  4717. for t in range(len(ncctools)):
  4718. ncctools[t] *= sfactor
  4719. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  4720. elif dim == 'tools_solderpaste_tools':
  4721. sptools = []
  4722. try:
  4723. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4724. sptools = [eval(a) for a in tools_string if a != '']
  4725. except Exception as e:
  4726. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4727. self.defaults['tools_solderpaste_tools'] = ""
  4728. for t in range(len(sptools)):
  4729. sptools[t] *= sfactor
  4730. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  4731. elif dim == 'tools_solderpaste_xy_toolchange':
  4732. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4733. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4734. sp_coords[0] *= sfactor
  4735. sp_coords[1] *= sfactor
  4736. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  4737. elif dim == 'global_gridx' or dim == 'global_gridy':
  4738. if new_units == 'IN':
  4739. val = 0.1
  4740. try:
  4741. val = float(self.defaults[dim]) * sfactor
  4742. except Exception as e:
  4743. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4744. self.defaults[dim] = float('%.6f' % val)
  4745. else:
  4746. val = 0.1
  4747. try:
  4748. val = float(self.defaults[dim]) * sfactor
  4749. except Exception as e:
  4750. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4751. self.defaults[dim] = float('%.4f' % val)
  4752. else:
  4753. val = 0.1
  4754. try:
  4755. val = float(self.defaults[dim]) * sfactor
  4756. except Exception as e:
  4757. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4758. self.defaults[dim] = val
  4759. # The scaling factor depending on choice of units.
  4760. factor = 1/25.4
  4761. if new_units == 'MM':
  4762. factor = 25.4
  4763. # Changing project units. Warn user.
  4764. msgbox = QtWidgets.QMessageBox()
  4765. msgbox.setWindowTitle(_("Toggle Units"))
  4766. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  4767. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4768. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  4769. "properties of all objects to be scaled accordingly.\nContinue?"))
  4770. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4771. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4772. msgbox.setDefaultButton(bt_ok)
  4773. msgbox.exec_()
  4774. response = msgbox.clickedButton()
  4775. if response == bt_ok:
  4776. if no_pref is False:
  4777. self.options_read_form()
  4778. scale_options(factor)
  4779. self.options_write_form()
  4780. self.defaults_read_form()
  4781. scale_defaults(factor)
  4782. self.defaults_write_form(fl_units=new_units)
  4783. # save the defaults to file, some may assume that the conversion is enough and it's not
  4784. self.on_save_button()
  4785. self.should_we_save = True
  4786. # change this only if the workspace is active
  4787. if self.defaults['global_workspace'] is True:
  4788. self.plotcanvas.draw_workspace()
  4789. # adjust the grid values on the main toolbar
  4790. dec = 6 if new_units == 'IN'else 4
  4791. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  4792. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  4793. if not self.ui.grid_gap_link_cb.isChecked():
  4794. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  4795. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  4796. for obj in self.collection.get_list():
  4797. obj.convert_units(new_units)
  4798. # make that the properties stored in the object are also updated
  4799. self.object_changed.emit(obj)
  4800. obj.build_ui()
  4801. current = self.collection.get_active()
  4802. if current is not None:
  4803. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4804. if not isinstance(current, FlatCAMGeometry):
  4805. current.to_form()
  4806. self.plot_all()
  4807. self.inform.emit('[success] %s: %s' %
  4808. (_("Converted units to"), new_units))
  4809. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4810. self.set_screen_units(new_units)
  4811. else:
  4812. # Undo toggling
  4813. self.toggle_units_ignore = True
  4814. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4815. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4816. else:
  4817. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4818. self.toggle_units_ignore = False
  4819. self.inform.emit('[WARNING_NOTCL]%s' %
  4820. _(" Units conversion cancelled."))
  4821. self.options_read_form()
  4822. self.defaults_read_form()
  4823. def on_toggle_units_click(self):
  4824. try:
  4825. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4826. except (TypeError, AttributeError):
  4827. pass
  4828. if self.defaults["units"] == 'MM':
  4829. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4830. else:
  4831. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4832. self.on_toggle_units(no_pref=True)
  4833. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4834. lambda: self.on_toggle_units(no_pref=False))
  4835. def on_fullscreen(self, disable=False):
  4836. self.report_usage("on_fullscreen()")
  4837. if self.toggle_fscreen is False and disable is False:
  4838. # self.ui.showFullScreen()
  4839. self.ui.setWindowFlags(self.ui.windowFlags() | Qt.FramelessWindowHint)
  4840. a = self.ui.geometry()
  4841. self.x_pos = a.x()
  4842. self.y_pos = a.y()
  4843. self.width = a.width()
  4844. self.height = a.height()
  4845. # set new geometry to full desktop rect
  4846. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  4847. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  4848. # everything else will not work without this hack. This happen in Windows.
  4849. # https://bugreports.qt.io/browse/QTBUG-41309
  4850. desktop = QtWidgets.QApplication.desktop()
  4851. screen = desktop.screenNumber(QtGui.QCursor.pos())
  4852. rec = desktop.screenGeometry(screen)
  4853. x = rec.x() - 1
  4854. y = rec.y() - 1
  4855. h = rec.height() + 2
  4856. w = rec.width() + 2
  4857. self.ui.setGeometry(x, y, w, h)
  4858. self.ui.show()
  4859. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4860. tb.setVisible(False)
  4861. self.ui.splitter_left.setVisible(False)
  4862. self.toggle_fscreen = True
  4863. elif self.toggle_fscreen is True or disable is True:
  4864. self.ui.setWindowFlags(self.ui.windowFlags() & ~Qt.FramelessWindowHint)
  4865. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  4866. self.ui.showNormal()
  4867. self.restore_toolbar_view()
  4868. self.ui.splitter_left.setVisible(True)
  4869. self.toggle_fscreen = False
  4870. def on_toggle_plotarea(self):
  4871. self.report_usage("on_toggle_plotarea()")
  4872. try:
  4873. name = self.ui.plot_tab_area.widget(0).objectName()
  4874. except AttributeError:
  4875. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4876. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4877. self.ui.plot_tab_area.protectTab(0)
  4878. return
  4879. if name != 'plotarea':
  4880. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4881. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4882. self.ui.plot_tab_area.protectTab(0)
  4883. else:
  4884. self.ui.plot_tab_area.closeTab(0)
  4885. def on_toggle_notebook(self):
  4886. if self.ui.splitter.sizes()[0] == 0:
  4887. self.ui.splitter.setSizes([1, 1])
  4888. self.ui.menu_toggle_nb.setChecked(True)
  4889. else:
  4890. self.ui.splitter.setSizes([0, 1])
  4891. self.ui.menu_toggle_nb.setChecked(False)
  4892. def on_toggle_axis(self):
  4893. self.report_usage("on_toggle_axis()")
  4894. if self.toggle_axis is False:
  4895. if self.is_legacy is False:
  4896. # self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4897. # self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4898. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  4899. parent=self.plotcanvas.view.scene)
  4900. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  4901. parent=self.plotcanvas.view.scene)
  4902. # self.plotcanvas.redraw()
  4903. else:
  4904. self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  4905. self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  4906. self.plotcanvas.canvas.draw()
  4907. pass
  4908. self.toggle_axis = True
  4909. else:
  4910. if self.is_legacy is False:
  4911. # self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4912. # self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4913. # self.plotcanvas.redraw()
  4914. self.plotcanvas.v_line.parent = None
  4915. self.plotcanvas.h_line.parent = None
  4916. else:
  4917. self.plotcanvas.axes.lines[:] = []
  4918. self.plotcanvas.canvas.draw()
  4919. self.toggle_axis = False
  4920. def on_toggle_grid(self):
  4921. self.report_usage("on_toggle_grid()")
  4922. self.ui.grid_snap_btn.trigger()
  4923. def on_options_combo_change(self, sel):
  4924. """
  4925. Called when the combo box to choose between application defaults and
  4926. project option changes value. The corresponding variables are
  4927. copied to the UI.
  4928. :param sel: The option index that was chosen.
  4929. :return: None
  4930. """
  4931. # combo_sel = self.ui.notebook.combo_options.get_active()
  4932. App.log.debug("Options --> %s" % sel)
  4933. # form = [self.defaults_form, self.options_form][sel]
  4934. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  4935. if sel == 0:
  4936. self.gen_form = self.ui.general_defaults_form
  4937. self.ger_form = self.ui.gerber_defaults_form
  4938. self.exc_form = self.ui.excellon_defaults_form
  4939. self.geo_form = self.ui.geometry_defaults_form
  4940. self.cnc_form = self.ui.cncjob_defaults_form
  4941. self.tools_form = self.ui.tools_defaults_form
  4942. self.fa_form = self.ui.util_defaults_form
  4943. elif sel == 1:
  4944. self.gen_form = self.ui.general_options_form
  4945. self.ger_form = self.ui.gerber_options_form
  4946. self.exc_form = self.ui.excellon_options_form
  4947. self.geo_form = self.ui.geometry_options_form
  4948. self.cnc_form = self.ui.cncjob_options_form
  4949. self.tools_form = self.ui.tools_options_form
  4950. self.fa_form = self.ui.util_options_form
  4951. else:
  4952. return
  4953. try:
  4954. self.ui.general_scroll_area.takeWidget()
  4955. except:
  4956. self.log.debug("Nothing to remove")
  4957. self.ui.general_scroll_area.setWidget(self.gen_form)
  4958. self.gen_form.show()
  4959. try:
  4960. self.ui.gerber_scroll_area.takeWidget()
  4961. except:
  4962. self.log.debug("Nothing to remove")
  4963. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  4964. self.ger_form.show()
  4965. try:
  4966. self.ui.excellon_scroll_area.takeWidget()
  4967. except:
  4968. self.log.debug("Nothing to remove")
  4969. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  4970. self.exc_form.show()
  4971. try:
  4972. self.ui.geometry_scroll_area.takeWidget()
  4973. except:
  4974. self.log.debug("Nothing to remove")
  4975. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  4976. self.geo_form.show()
  4977. try:
  4978. self.ui.cncjob_scroll_area.takeWidget()
  4979. except:
  4980. self.log.debug("Nothing to remove")
  4981. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  4982. self.cnc_form.show()
  4983. try:
  4984. self.ui.tools_scroll_area.takeWidget()
  4985. except:
  4986. self.log.debug("Nothing to remove")
  4987. self.ui.tools_scroll_area.setWidget(self.tools_form)
  4988. self.tools_form.show()
  4989. try:
  4990. self.ui.fa_scroll_area.takeWidget()
  4991. except:
  4992. self.log.debug("Nothing to remove")
  4993. self.ui.fa_scroll_area.setWidget(self.fa_form)
  4994. self.fa_form.show()
  4995. self.log.debug("Finished GUI form initialization.")
  4996. # self.options2form()
  4997. def on_excellon_defaults_button(self):
  4998. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  4999. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  5000. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  5001. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  5002. self.defaults_form_fields["excellon_zeros"].set_value('L')
  5003. self.defaults_form_fields["excellon_units"].set_value('INCH')
  5004. log.debug("Excellon app defaults loaded ...")
  5005. def on_excellon_options_button(self):
  5006. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  5007. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  5008. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  5009. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  5010. self.options_form_fields["excellon_zeros"].set_value('L')
  5011. self.options_form_fields["excellon_units"].set_value('INCH')
  5012. log.debug("Excellon options defaults loaded ...")
  5013. def on_update_exc_export(self, state):
  5014. """
  5015. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  5016. if the update_excellon_cb checkbox is checked
  5017. :param state: state of the checkbox whose signals is tied to his slot
  5018. :return:
  5019. """
  5020. if state:
  5021. # first try to disconnect
  5022. try:
  5023. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.editingFinished.\
  5024. disconnect(self.on_excellon_format_changed)
  5025. except TypeError:
  5026. pass
  5027. try:
  5028. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.editingFinished.\
  5029. disconnect(self.on_excellon_format_changed)
  5030. except TypeError:
  5031. pass
  5032. try:
  5033. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.editingFinished.\
  5034. disconnect(self.on_excellon_format_changed)
  5035. except TypeError:
  5036. pass
  5037. try:
  5038. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.editingFinished.\
  5039. disconnect(self.on_excellon_format_changed)
  5040. except TypeError:
  5041. pass
  5042. try:
  5043. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  5044. disconnect(self.on_excellon_zeros_changed)
  5045. except TypeError:
  5046. pass
  5047. try:
  5048. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  5049. disconnect(self.on_excellon_zeros_changed)
  5050. except TypeError:
  5051. pass
  5052. # the connect them
  5053. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.editingFinished.connect(
  5054. self.on_excellon_format_changed)
  5055. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.editingFinished.connect(
  5056. self.on_excellon_format_changed)
  5057. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.editingFinished.connect(
  5058. self.on_excellon_format_changed)
  5059. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.editingFinished.connect(
  5060. self.on_excellon_format_changed)
  5061. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  5062. self.on_excellon_zeros_changed)
  5063. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  5064. self.on_excellon_units_changed)
  5065. else:
  5066. # disconnect the signals
  5067. try:
  5068. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.editingFinished. \
  5069. disconnect(self.on_excellon_format_changed)
  5070. except TypeError:
  5071. pass
  5072. try:
  5073. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.editingFinished. \
  5074. disconnect(self.on_excellon_format_changed)
  5075. except TypeError:
  5076. pass
  5077. try:
  5078. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.editingFinished. \
  5079. disconnect(self.on_excellon_format_changed)
  5080. except TypeError:
  5081. pass
  5082. try:
  5083. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.editingFinished. \
  5084. disconnect(self.on_excellon_format_changed)
  5085. except TypeError:
  5086. pass
  5087. try:
  5088. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  5089. disconnect(self.on_excellon_zeros_changed)
  5090. except TypeError:
  5091. pass
  5092. try:
  5093. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  5094. disconnect(self.on_excellon_zeros_changed)
  5095. except TypeError:
  5096. pass
  5097. def on_excellon_format_changed(self):
  5098. """
  5099. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  5100. :return: None
  5101. """
  5102. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  5103. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5104. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  5105. )
  5106. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5107. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  5108. )
  5109. else:
  5110. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5111. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  5112. )
  5113. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5114. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  5115. )
  5116. def on_excellon_zeros_changed(self):
  5117. """
  5118. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  5119. :return: None
  5120. """
  5121. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  5122. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  5123. )
  5124. def on_excellon_units_changed(self):
  5125. """
  5126. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  5127. :return: None
  5128. """
  5129. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  5130. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  5131. )
  5132. self.on_excellon_format_changed()
  5133. # Setting plot colors handlers
  5134. def on_pf_color_entry(self):
  5135. self.defaults['global_plot_fill'] = \
  5136. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  5137. self.defaults['global_plot_fill'][7:9]
  5138. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5139. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  5140. def on_pf_color_button(self):
  5141. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  5142. c_dialog = QtWidgets.QColorDialog()
  5143. plot_fill_color = c_dialog.getColor(initial=current_color)
  5144. if plot_fill_color.isValid() is False:
  5145. return
  5146. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5147. "background-color:%s" % str(plot_fill_color.name()))
  5148. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  5149. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  5150. self.defaults['global_plot_fill'] = new_val
  5151. def on_pf_color_spinner(self):
  5152. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  5153. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  5154. self.defaults['global_plot_fill'] = \
  5155. self.defaults['global_plot_fill'][:7] + \
  5156. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5157. self.defaults['global_plot_line'] = \
  5158. self.defaults['global_plot_line'][:7] + \
  5159. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5160. def on_pf_color_slider(self):
  5161. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  5162. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  5163. def on_pl_color_entry(self):
  5164. self.defaults['global_plot_line'] = \
  5165. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  5166. self.defaults['global_plot_line'][7:9]
  5167. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5168. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  5169. def on_pl_color_button(self):
  5170. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  5171. # print(current_color)
  5172. c_dialog = QtWidgets.QColorDialog()
  5173. plot_line_color = c_dialog.getColor(initial=current_color)
  5174. if plot_line_color.isValid() is False:
  5175. return
  5176. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5177. "background-color:%s" % str(plot_line_color.name()))
  5178. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  5179. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  5180. self.defaults['global_plot_line'] = new_val_line
  5181. # Setting selection colors (left - right) handlers
  5182. def on_sf_color_entry(self):
  5183. self.defaults['global_sel_fill'] = \
  5184. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  5185. self.defaults['global_sel_fill'][7:9]
  5186. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5187. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  5188. def on_sf_color_button(self):
  5189. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  5190. c_dialog = QtWidgets.QColorDialog()
  5191. plot_fill_color = c_dialog.getColor(initial=current_color)
  5192. if plot_fill_color.isValid() is False:
  5193. return
  5194. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5195. "background-color:%s" % str(plot_fill_color.name()))
  5196. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  5197. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  5198. self.defaults['global_sel_fill'] = new_val
  5199. def on_sf_color_spinner(self):
  5200. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  5201. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  5202. self.defaults['global_sel_fill'] = \
  5203. self.defaults['global_sel_fill'][:7] + \
  5204. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5205. self.defaults['global_sel_line'] = \
  5206. self.defaults['global_sel_line'][:7] + \
  5207. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5208. def on_sf_color_slider(self):
  5209. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  5210. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  5211. def on_sl_color_entry(self):
  5212. self.defaults['global_sel_line'] = \
  5213. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  5214. self.defaults['global_sel_line'][7:9]
  5215. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5216. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  5217. def on_sl_color_button(self):
  5218. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  5219. c_dialog = QtWidgets.QColorDialog()
  5220. plot_line_color = c_dialog.getColor(initial=current_color)
  5221. if plot_line_color.isValid() is False:
  5222. return
  5223. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5224. "background-color:%s" % str(plot_line_color.name()))
  5225. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  5226. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  5227. self.defaults['global_sel_line'] = new_val_line
  5228. # Setting selection colors (right - left) handlers
  5229. def on_alt_sf_color_entry(self):
  5230. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  5231. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  5232. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5233. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  5234. def on_alt_sf_color_button(self):
  5235. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  5236. c_dialog = QtWidgets.QColorDialog()
  5237. plot_fill_color = c_dialog.getColor(initial=current_color)
  5238. if plot_fill_color.isValid() is False:
  5239. return
  5240. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5241. "background-color:%s" % str(plot_fill_color.name()))
  5242. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  5243. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  5244. self.defaults['global_alt_sel_fill'] = new_val
  5245. def on_alt_sf_color_spinner(self):
  5246. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  5247. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  5248. self.defaults['global_alt_sel_fill'] = \
  5249. self.defaults['global_alt_sel_fill'][:7] + \
  5250. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5251. self.defaults['global_alt_sel_line'] = \
  5252. self.defaults['global_alt_sel_line'][:7] + \
  5253. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5254. def on_alt_sf_color_slider(self):
  5255. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  5256. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  5257. def on_alt_sl_color_entry(self):
  5258. self.defaults['global_alt_sel_line'] = \
  5259. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  5260. self.defaults['global_alt_sel_line'][7:9]
  5261. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5262. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  5263. def on_alt_sl_color_button(self):
  5264. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  5265. c_dialog = QtWidgets.QColorDialog()
  5266. plot_line_color = c_dialog.getColor(initial=current_color)
  5267. if plot_line_color.isValid() is False:
  5268. return
  5269. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5270. "background-color:%s" % str(plot_line_color.name()))
  5271. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  5272. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  5273. self.defaults['global_alt_sel_line'] = new_val_line
  5274. # Setting Editor colors
  5275. def on_draw_color_entry(self):
  5276. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5277. .draw_color_entry.get_value()
  5278. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5279. "background-color:%s" % str(self.defaults['global_draw_color']))
  5280. def on_draw_color_button(self):
  5281. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  5282. c_dialog = QtWidgets.QColorDialog()
  5283. draw_color = c_dialog.getColor(initial=current_color)
  5284. if draw_color.isValid() is False:
  5285. return
  5286. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5287. "background-color:%s" % str(draw_color.name()))
  5288. new_val = str(draw_color.name())
  5289. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  5290. self.defaults['global_draw_color'] = new_val
  5291. def on_sel_draw_color_entry(self):
  5292. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5293. .sel_draw_color_entry.get_value()
  5294. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5295. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  5296. def on_sel_draw_color_button(self):
  5297. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  5298. c_dialog = QtWidgets.QColorDialog()
  5299. sel_draw_color = c_dialog.getColor(initial=current_color)
  5300. if sel_draw_color.isValid() is False:
  5301. return
  5302. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5303. "background-color:%s" % str(sel_draw_color.name()))
  5304. new_val_sel = str(sel_draw_color.name())
  5305. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  5306. self.defaults['global_sel_draw_color'] = new_val_sel
  5307. def on_proj_color_entry(self):
  5308. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  5309. .proj_color_entry.get_value()
  5310. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5311. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  5312. def on_proj_color_button(self):
  5313. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  5314. c_dialog = QtWidgets.QColorDialog()
  5315. proj_color = c_dialog.getColor(initial=current_color)
  5316. if proj_color.isValid() is False:
  5317. return
  5318. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5319. "background-color:%s" % str(proj_color.name()))
  5320. new_val_sel = str(proj_color.name())
  5321. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  5322. self.defaults['global_proj_item_color'] = new_val_sel
  5323. def on_proj_color_dis_entry(self):
  5324. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  5325. .proj_color_dis_entry.get_value()
  5326. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5327. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  5328. def on_proj_color_dis_button(self):
  5329. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  5330. c_dialog = QtWidgets.QColorDialog()
  5331. proj_color = c_dialog.getColor(initial=current_color)
  5332. if proj_color.isValid() is False:
  5333. return
  5334. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5335. "background-color:%s" % str(proj_color.name()))
  5336. new_val_sel = str(proj_color.name())
  5337. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  5338. self.defaults['global_proj_item_dis_color'] = new_val_sel
  5339. def on_annotation_fontcolor_entry(self):
  5340. self.defaults['cncjob_annotation_fontcolor'] = \
  5341. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.get_value()
  5342. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5343. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  5344. def on_annotation_fontcolor_button(self):
  5345. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  5346. c_dialog = QtWidgets.QColorDialog()
  5347. annotation_color = c_dialog.getColor(initial=current_color)
  5348. if annotation_color.isValid() is False:
  5349. return
  5350. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5351. "background-color:%s" % str(annotation_color.name()))
  5352. new_val_sel = str(annotation_color.name())
  5353. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(new_val_sel)
  5354. self.defaults['cncjob_annotation_fontcolor'] = new_val_sel
  5355. def on_film_color_entry(self):
  5356. self.defaults['tools_film_color'] = \
  5357. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  5358. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5359. "background-color:%s" % str(self.defaults['tools_film_color']))
  5360. def on_film_color_button(self):
  5361. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  5362. c_dialog = QtWidgets.QColorDialog()
  5363. film_color = c_dialog.getColor(initial=current_color)
  5364. if film_color.isValid() is False:
  5365. return
  5366. # if new color is different then mark that the Preferences are changed
  5367. if film_color != current_color:
  5368. self.on_preferences_edited()
  5369. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5370. "background-color:%s" % str(film_color.name()))
  5371. new_val_sel = str(film_color.name())
  5372. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  5373. self.defaults['tools_film_color'] = new_val_sel
  5374. def on_splash_changed(self, state):
  5375. settings = QSettings("Open Source", "FlatCAM")
  5376. settings.setValue('splash_screen', 1) if state else settings.setValue('splash_screen', 0)
  5377. # This will write the setting to the platform specific storage.
  5378. del settings
  5379. def on_notebook_tab_rmb_click(self, checked):
  5380. self.ui.notebook.set_detachable(val=checked)
  5381. self.defaults["global_tabs_detachable"] = checked
  5382. self.ui.plot_tab_area.set_detachable(val=checked)
  5383. self.defaults["global_tabs_detachable"] = checked
  5384. def on_deselect_all(self):
  5385. self.collection.set_all_inactive()
  5386. self.delete_selection_shape()
  5387. def on_workspace_modified(self):
  5388. self.save_defaults(silent=True)
  5389. self.plotcanvas.draw_workspace()
  5390. def on_workspace(self):
  5391. self.report_usage("on_workspace()")
  5392. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5393. self.plotcanvas.restore_workspace()
  5394. else:
  5395. self.plotcanvas.delete_workspace()
  5396. self.save_defaults(silent=True)
  5397. def on_workspace_menu(self):
  5398. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5399. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  5400. else:
  5401. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  5402. self.on_workspace()
  5403. def on_layout(self, index=None, lay=None):
  5404. """
  5405. Set the toolbars layout (location)
  5406. :param index:
  5407. :param lay: type of layout to be set on the toolbard
  5408. :return: None
  5409. """
  5410. self.report_usage("on_layout()")
  5411. if lay:
  5412. current_layout = lay
  5413. else:
  5414. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  5415. settings = QSettings("Open Source", "FlatCAM")
  5416. settings.setValue('layout', current_layout)
  5417. # This will write the setting to the platform specific storage.
  5418. del settings
  5419. # first remove the toolbars:
  5420. try:
  5421. self.ui.removeToolBar(self.ui.toolbarfile)
  5422. self.ui.removeToolBar(self.ui.toolbargeo)
  5423. self.ui.removeToolBar(self.ui.toolbarview)
  5424. self.ui.removeToolBar(self.ui.toolbarshell)
  5425. self.ui.removeToolBar(self.ui.toolbartools)
  5426. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  5427. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  5428. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  5429. self.ui.removeToolBar(self.ui.snap_toolbar)
  5430. self.ui.removeToolBar(self.ui.toolbarshell)
  5431. except Exception as e:
  5432. pass
  5433. if current_layout == 'standard':
  5434. # ## TOOLBAR INSTALLATION # ##
  5435. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5436. self.ui.toolbarfile.setObjectName('File_TB')
  5437. self.ui.addToolBar(self.ui.toolbarfile)
  5438. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5439. self.ui.toolbargeo.setObjectName('Edit_TB')
  5440. self.ui.addToolBar(self.ui.toolbargeo)
  5441. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5442. self.ui.toolbarview.setObjectName('View_TB')
  5443. self.ui.addToolBar(self.ui.toolbarview)
  5444. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5445. self.ui.toolbarshell.setObjectName('Shell_TB')
  5446. self.ui.addToolBar(self.ui.toolbarshell)
  5447. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5448. self.ui.toolbartools.setObjectName('Tools_TB')
  5449. self.ui.addToolBar(self.ui.toolbartools)
  5450. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5451. # self.ui.exc_edit_toolbar.setVisible(False)
  5452. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5453. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  5454. self.ui.addToolBarBreak()
  5455. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5456. # self.ui.geo_edit_toolbar.setVisible(False)
  5457. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5458. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  5459. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5460. # self.ui.grb_edit_toolbar.setVisible(False)
  5461. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5462. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  5463. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5464. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5465. # self.ui.snap_toolbar.setMaximumHeight(30)
  5466. self.ui.addToolBar(self.ui.snap_toolbar)
  5467. self.ui.corner_snap_btn.setVisible(False)
  5468. self.ui.snap_magnet.setVisible(False)
  5469. elif current_layout == 'compact':
  5470. # ## TOOLBAR INSTALLATION # ##
  5471. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5472. self.ui.toolbarfile.setObjectName('File_TB')
  5473. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  5474. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5475. self.ui.toolbargeo.setObjectName('Edit_TB')
  5476. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  5477. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5478. self.ui.toolbarshell.setObjectName('Shell_TB')
  5479. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  5480. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5481. self.ui.toolbartools.setObjectName('Tools_TB')
  5482. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  5483. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5484. # self.ui.geo_edit_toolbar.setVisible(False)
  5485. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5486. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  5487. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5488. self.ui.toolbarview.setObjectName('View_TB')
  5489. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  5490. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  5491. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5492. # self.ui.grb_edit_toolbar.setVisible(False)
  5493. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5494. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  5495. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5496. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5497. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  5498. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5499. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5500. self.ui.snap_toolbar.setMaximumHeight(30)
  5501. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  5502. self.ui.corner_snap_btn.setVisible(True)
  5503. self.ui.snap_magnet.setVisible(True)
  5504. # add all the actions to the toolbars
  5505. self.ui.populate_toolbars()
  5506. # reconnect all the signals to the toolbar actions
  5507. self.connect_toolbar_signals()
  5508. self.ui.grid_snap_btn.setChecked(True)
  5509. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  5510. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  5511. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  5512. self.ui.grid_gap_link_cb.setChecked(True)
  5513. def on_cursor_type(self, val):
  5514. """
  5515. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  5516. :return: None
  5517. """
  5518. self.app_cursor.enabled = False
  5519. if val == 'small':
  5520. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(False)
  5521. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(False)
  5522. self.app_cursor = self.plotcanvas.new_cursor()
  5523. else:
  5524. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(True)
  5525. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(True)
  5526. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  5527. if self.ui.grid_snap_btn.isChecked():
  5528. self.app_cursor.enabled = True
  5529. else:
  5530. self.app_cursor.enabled = False
  5531. def on_cnc_custom_parameters(self, signal_text):
  5532. if signal_text == 'Parameters':
  5533. return
  5534. else:
  5535. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  5536. def on_save_button(self):
  5537. log.debug("App.on_save_button() --> Saving preferences to file.")
  5538. self.preferences_changed_flag = False
  5539. self.save_defaults(silent=False)
  5540. # load the defaults so they are updated into the app
  5541. self.load_defaults(filename='current_defaults')
  5542. # Re-fresh project options
  5543. self.on_options_app2project()
  5544. settings = QSettings("Open Source", "FlatCAM")
  5545. # save the notebook font size
  5546. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  5547. settings.setValue('notebook_font_size', fsize)
  5548. # save the axis font size
  5549. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  5550. settings.setValue('axis_font_size', g_fsize)
  5551. # save the textbox font size
  5552. tb_fsize = self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  5553. settings.setValue('textbox_font_size', tb_fsize)
  5554. # This will write the setting to the platform specific storage.
  5555. del settings
  5556. def on_tool_add_keypress(self):
  5557. # ## Current application units in Upper Case
  5558. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5559. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5560. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5561. if notebook_widget_name == 'selected_tab':
  5562. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5563. # Tool add works for Geometry only if Advanced is True in Preferences
  5564. if self.defaults["global_app_level"] == 'a':
  5565. tool_add_popup = FCInputDialog(title="New Tool ...",
  5566. text='Enter a Tool Diameter:',
  5567. min=0.0000, max=99.9999, decimals=4)
  5568. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5569. val, ok = tool_add_popup.get_value()
  5570. if ok:
  5571. if float(val) == 0:
  5572. self.inform.emit('[WARNING_NOTCL] %s' %
  5573. _("Please enter a tool diameter with non-zero value, in Float format."))
  5574. return
  5575. self.collection.get_active().on_tool_add(dia=float(val))
  5576. else:
  5577. self.inform.emit('[WARNING_NOTCL] %s...' %
  5578. _("Adding Tool cancelled"))
  5579. else:
  5580. msgbox = QtWidgets.QMessageBox()
  5581. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5582. "Go to Preferences -> General - Show Advanced Options."))
  5583. msgbox.setWindowTitle("Tool adding ...")
  5584. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  5585. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5586. msgbox.setDefaultButton(bt_ok)
  5587. msgbox.exec_()
  5588. # work only if the notebook tab on focus is the Tools_Tab
  5589. if notebook_widget_name == 'tool_tab':
  5590. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5591. # and only if the tool is NCC Tool
  5592. if tool_widget == self.ncclear_tool.toolName:
  5593. self.ncclear_tool.on_add_tool_by_key()
  5594. # and only if the tool is Paint Area Tool
  5595. elif tool_widget == self.paint_tool.toolName:
  5596. self.paint_tool.on_add_tool_by_key()
  5597. # and only if the tool is Solder Paste Dispensing Tool
  5598. elif tool_widget == self.paste_tool.toolName:
  5599. self.paste_tool.on_add_tool_by_key()
  5600. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5601. # See description bellow.
  5602. def on_delete_keypress(self):
  5603. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5604. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5605. if notebook_widget_name == 'selected_tab':
  5606. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5607. self.collection.get_active().on_tool_delete()
  5608. # work only if the notebook tab on focus is the Tools_Tab
  5609. elif notebook_widget_name == 'tool_tab':
  5610. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5611. # and only if the tool is NCC Tool
  5612. if tool_widget == self.ncclear_tool.toolName:
  5613. self.ncclear_tool.on_tool_delete()
  5614. # and only if the tool is Paint Tool
  5615. elif tool_widget == self.paint_tool.toolName:
  5616. self.paint_tool.on_tool_delete()
  5617. # and only if the tool is Solder Paste Dispensing Tool
  5618. elif tool_widget == self.paste_tool.toolName:
  5619. self.paste_tool.on_tool_delete()
  5620. else:
  5621. self.on_delete()
  5622. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5623. # some screens you have to be careful where you hover with your mouse.
  5624. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5625. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5626. # Complicated, I know :)
  5627. def on_delete(self):
  5628. """
  5629. Delete the currently selected FlatCAMObjs.
  5630. :return: None
  5631. """
  5632. self.report_usage("on_delete()")
  5633. response = None
  5634. bt_ok = None
  5635. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5636. # a geometry object before we update it.
  5637. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5638. and self.grb_editor.editor_active is False:
  5639. if self.defaults["global_delete_confirmation"] is True:
  5640. msgbox = QtWidgets.QMessageBox()
  5641. msgbox.setWindowTitle(_("Delete objects"))
  5642. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  5643. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5644. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5645. "the selected objects?"))
  5646. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5647. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5648. msgbox.setDefaultButton(bt_ok)
  5649. msgbox.exec_()
  5650. response = msgbox.clickedButton()
  5651. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  5652. if self.collection.get_active():
  5653. self.log.debug("App.on_delete()")
  5654. while self.collection.get_active():
  5655. obj_active = self.collection.get_active()
  5656. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  5657. if isinstance(obj_active, FlatCAMGerber):
  5658. for el in obj_active.mark_shapes:
  5659. obj_active.mark_shapes[el].clear(update=True)
  5660. obj_active.mark_shapes[el].enabled = False
  5661. # obj_active.mark_shapes[el] = None
  5662. del el
  5663. elif isinstance(obj_active, FlatCAMCNCjob):
  5664. try:
  5665. obj_active.annotation.clear(update=True)
  5666. obj_active.annotation.enabled = False
  5667. except AttributeError:
  5668. pass
  5669. self.delete_first_selected()
  5670. self.inform.emit('%s...' %
  5671. _("Object(s) deleted"))
  5672. # make sure that the selection shape is deleted, too
  5673. self.delete_selection_shape()
  5674. else:
  5675. self.inform.emit(_("Failed. No object(s) selected..."))
  5676. else:
  5677. self.inform.emit(_("Save the work in Editor and try again ..."))
  5678. def delete_first_selected(self):
  5679. # Keep this for later
  5680. try:
  5681. sel_obj = self.collection.get_active()
  5682. name = sel_obj.options["name"]
  5683. isPlotted = sel_obj.options["plot"]
  5684. except AttributeError:
  5685. self.log.debug("Nothing selected for deletion")
  5686. return
  5687. if self.is_legacy is True:
  5688. # Remove plot only if the object was plotted otherwise delaxes will fail
  5689. if isPlotted:
  5690. try:
  5691. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  5692. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  5693. except Exception as e:
  5694. log.debug("App.delete_first_selected() --> %s" % str(e))
  5695. self.plotcanvas.auto_adjust_axes()
  5696. # Remove from dictionary
  5697. self.collection.delete_active()
  5698. # Clear form
  5699. self.setup_component_editor()
  5700. self.inform.emit('%s: %s' %
  5701. (_("Object deleted"), name))
  5702. def on_set_origin(self):
  5703. """
  5704. Set the origin to the left mouse click position
  5705. :return: None
  5706. """
  5707. # display the message for the user
  5708. # and ask him to click on the desired position
  5709. self.report_usage("on_set_origin()")
  5710. def origin_replot():
  5711. def worker_task():
  5712. with self.proc_container.new('%s...' % _("Plotting")):
  5713. for obj in self.collection.get_list():
  5714. obj.plot()
  5715. self.plotcanvas.fit_view()
  5716. if self.is_legacy:
  5717. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  5718. else:
  5719. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  5720. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5721. self.inform.emit(_('Click to set the origin ...'))
  5722. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  5723. # first disconnect it as it may have been used by something else
  5724. try:
  5725. self.replot_signal.disconnect()
  5726. except TypeError:
  5727. pass
  5728. self.replot_signal[list].connect(origin_replot)
  5729. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  5730. """
  5731. :param event:
  5732. :param location:
  5733. :param noplot:
  5734. :param use_thread:
  5735. :return:
  5736. """
  5737. noplot_sig = noplot
  5738. def worker_task():
  5739. with self.proc_container.new(_("Setting Origin...")):
  5740. for obj in self.collection.get_list():
  5741. obj.offset((x, y))
  5742. self.object_changed.emit(obj)
  5743. # Update the object bounding box options
  5744. a, b, c, d = obj.bounds()
  5745. obj.options['xmin'] = a
  5746. obj.options['ymin'] = b
  5747. obj.options['xmax'] = c
  5748. obj.options['ymax'] = d
  5749. self.inform.emit('[success] %s...' %
  5750. _('Origin set'))
  5751. if noplot_sig is False:
  5752. self.replot_signal.emit([])
  5753. if location is not None:
  5754. if len(location) != 2:
  5755. self.inform.emit('[ERROR_NOTCL] %s...' %
  5756. _("Origin coordinates specified but incomplete."))
  5757. return 'fail'
  5758. x, y = location
  5759. if use_thread is True:
  5760. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5761. else:
  5762. worker_task()
  5763. self.should_we_save = True
  5764. return
  5765. if event.button == 1:
  5766. if self.is_legacy is False:
  5767. event_pos = event.pos
  5768. else:
  5769. event_pos = (event.xdata, event.ydata)
  5770. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5771. if self.grid_status() == True:
  5772. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5773. else:
  5774. pos = pos_canvas
  5775. x = 0 - pos[0]
  5776. y = 0 - pos[1]
  5777. if use_thread is True:
  5778. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5779. else:
  5780. worker_task()
  5781. self.should_we_save = True
  5782. def on_jump_to(self, custom_location=None, fit_center=True):
  5783. """
  5784. Jump to a location by setting the mouse cursor location
  5785. :return:
  5786. """
  5787. self.report_usage("on_jump_to()")
  5788. # if self.is_legacy is True:
  5789. # self.inform.emit(_("Not available with the current Graphic Engine Legacy(2D)."))
  5790. # return
  5791. if not custom_location:
  5792. dia_box_location = None
  5793. try:
  5794. dia_box_location = eval(self.clipboard.text())
  5795. except Exception as e:
  5796. pass
  5797. if type(dia_box_location) == tuple:
  5798. dia_box_location = str(dia_box_location)
  5799. else:
  5800. dia_box_location = None
  5801. dia_box = Dialog_box(title=_("Jump to ..."),
  5802. label=_("Enter the coordinates in format X,Y:"),
  5803. icon=QtGui.QIcon('share/jump_to16.png'),
  5804. initial_text=dia_box_location)
  5805. if dia_box.ok is True:
  5806. try:
  5807. location = eval(dia_box.location)
  5808. if not isinstance(location, tuple):
  5809. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  5810. return
  5811. except:
  5812. return
  5813. else:
  5814. return
  5815. else:
  5816. location = custom_location
  5817. if fit_center:
  5818. self.plotcanvas.fit_center(loc=location)
  5819. cursor = QtGui.QCursor()
  5820. if self.is_legacy is False:
  5821. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5822. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  5823. j_pos = (canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  5824. cursor.setPos(j_pos[0], j_pos[1])
  5825. else:
  5826. # find the canvas origin which is in the top left corner
  5827. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5828. # determine the coordinates for the lowest left point of the canvas
  5829. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  5830. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  5831. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  5832. # canvas) and the point (width, height) is in the top-right location
  5833. loc = self.plotcanvas.axes.transData.transform_point(location)
  5834. j_pos = (x0 + loc[0], y0 - loc[1])
  5835. cursor.setPos(j_pos[0], j_pos[1])
  5836. if self.grid_status() == True:
  5837. # Update cursor
  5838. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  5839. symbol='++', edge_color=self.cursor_color_3D,
  5840. size=self.defaults["global_cursor_size"])
  5841. # Set the position label
  5842. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5843. "<b>Y</b>: %.4f" % (location[0], location[1]))
  5844. # Set the relative position label
  5845. dx = location[0] - float(self.rel_point1[0])
  5846. dy = location[1] - float(self.rel_point1[1])
  5847. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5848. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  5849. self.inform.emit('[success] %s' %
  5850. _("Done."))
  5851. return location
  5852. def on_copy_object(self):
  5853. self.report_usage("on_copy_object()")
  5854. def initialize(obj_init, app):
  5855. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5856. try:
  5857. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5858. except AttributeError:
  5859. pass
  5860. try:
  5861. obj_init.apertures = deepcopy(obj.apertures)
  5862. except AttributeError:
  5863. pass
  5864. try:
  5865. if obj.tools:
  5866. obj_init.tools = deepcopy(obj.tools)
  5867. except Exception as e:
  5868. log.debug("App.on_copy_object() --> %s" % str(e))
  5869. def initialize_excellon(obj_init, app):
  5870. obj_init.tools = deepcopy(obj.tools)
  5871. # drills are offset, so they need to be deep copied
  5872. obj_init.drills = deepcopy(obj.drills)
  5873. # slots are offset, so they need to be deep copied
  5874. obj_init.slots = deepcopy(obj.slots)
  5875. obj_init.create_geometry()
  5876. def initialize_script(obj_init, app_obj):
  5877. obj_init.source_file = deepcopy(obj.source_file)
  5878. def initialize_document(obj_init, app_obj):
  5879. obj_init.source_file = deepcopy(obj.source_file)
  5880. for obj in self.collection.get_selected():
  5881. obj_name = obj.options["name"]
  5882. try:
  5883. if isinstance(obj, FlatCAMExcellon):
  5884. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  5885. elif isinstance(obj, FlatCAMGerber):
  5886. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  5887. elif isinstance(obj, FlatCAMGeometry):
  5888. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  5889. elif isinstance(obj, FlatCAMScript):
  5890. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  5891. elif isinstance(obj, FlatCAMDocument):
  5892. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  5893. except Exception as e:
  5894. return "Operation failed: %s" % str(e)
  5895. def on_copy_object2(self, custom_name):
  5896. def initialize_geometry(obj_init, app):
  5897. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5898. try:
  5899. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5900. except AttributeError:
  5901. pass
  5902. try:
  5903. obj_init.apertures = deepcopy(obj.apertures)
  5904. except AttributeError:
  5905. pass
  5906. try:
  5907. if obj.tools:
  5908. obj_init.tools = deepcopy(obj.tools)
  5909. except Exception as e:
  5910. log.debug("on_copy_object2() --> %s" % str(e))
  5911. def initialize_gerber(obj_init, app):
  5912. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5913. obj_init.apertures = deepcopy(obj.apertures)
  5914. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  5915. def initialize_excellon(obj_init, app):
  5916. obj_init.tools = deepcopy(obj.tools)
  5917. # drills are offset, so they need to be deep copied
  5918. obj_init.drills = deepcopy(obj.drills)
  5919. # slots are offset, so they need to be deep copied
  5920. obj_init.slots = deepcopy(obj.slots)
  5921. obj_init.create_geometry()
  5922. for obj in self.collection.get_selected():
  5923. obj_name = obj.options["name"]
  5924. try:
  5925. if isinstance(obj, FlatCAMExcellon):
  5926. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  5927. elif isinstance(obj, FlatCAMGerber):
  5928. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  5929. elif isinstance(obj, FlatCAMGeometry):
  5930. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  5931. except Exception as e:
  5932. return "Operation failed: %s" % str(e)
  5933. def on_rename_object(self, text):
  5934. self.report_usage("on_rename_object()")
  5935. named_obj = self.collection.get_active()
  5936. for obj in named_obj:
  5937. if obj is list:
  5938. self.on_rename_object(text)
  5939. else:
  5940. try:
  5941. obj.options['name'] = text
  5942. except Exception as e:
  5943. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  5944. def convert_any2geo(self):
  5945. self.report_usage("convert_any2geo()")
  5946. def initialize(obj_init, app):
  5947. obj_init.solid_geometry = obj.solid_geometry
  5948. try:
  5949. obj_init.follow_geometry = obj.follow_geometry
  5950. except AttributeError:
  5951. pass
  5952. try:
  5953. obj_init.apertures = obj.apertures
  5954. except AttributeError:
  5955. pass
  5956. try:
  5957. if obj.tools:
  5958. obj_init.tools = obj.tools
  5959. except AttributeError:
  5960. pass
  5961. def initialize_excellon(obj_init, app):
  5962. # objs = self.collection.get_selected()
  5963. # FlatCAMGeometry.merge(objs, obj)
  5964. solid_geo = []
  5965. for tool in obj.tools:
  5966. for geo in obj.tools[tool]['solid_geometry']:
  5967. solid_geo.append(geo)
  5968. obj_init.solid_geometry = deepcopy(solid_geo)
  5969. if not self.collection.get_selected():
  5970. log.warning("App.convert_any2geo --> No object selected")
  5971. self.inform.emit('[WARNING_NOTCL] %s' %
  5972. _("No object is selected. Select an object and try again."))
  5973. return
  5974. for obj in self.collection.get_selected():
  5975. obj_name = obj.options["name"]
  5976. try:
  5977. if isinstance(obj, FlatCAMExcellon):
  5978. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  5979. else:
  5980. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  5981. except Exception as e:
  5982. return "Operation failed: %s" % str(e)
  5983. def convert_any2gerber(self):
  5984. self.report_usage("convert_any2gerber()")
  5985. def initialize_geometry(obj_init, app):
  5986. apertures = {}
  5987. apid = 0
  5988. apertures[str(apid)] = {}
  5989. apertures[str(apid)]['geometry'] = []
  5990. for obj_orig in obj.solid_geometry:
  5991. new_elem = dict()
  5992. new_elem['solid'] = obj_orig
  5993. new_elem['follow'] = obj_orig.exterior
  5994. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  5995. apertures[str(apid)]['size'] = 0.0
  5996. apertures[str(apid)]['type'] = 'C'
  5997. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5998. obj_init.apertures = deepcopy(apertures)
  5999. def initialize_excellon(obj_init, app):
  6000. apertures = {}
  6001. apid = 10
  6002. for tool in obj.tools:
  6003. apertures[str(apid)] = {}
  6004. apertures[str(apid)]['geometry'] = []
  6005. for geo in obj.tools[tool]['solid_geometry']:
  6006. new_el = dict()
  6007. new_el['solid'] = geo
  6008. new_el['follow'] = geo.exterior
  6009. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  6010. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  6011. apertures[str(apid)]['type'] = 'C'
  6012. apid += 1
  6013. # create solid_geometry
  6014. solid_geometry = []
  6015. for apid in apertures:
  6016. for geo_el in apertures[apid]['geometry']:
  6017. solid_geometry.append(geo_el['solid'])
  6018. solid_geometry = MultiPolygon(solid_geometry)
  6019. solid_geometry = solid_geometry.buffer(0.0000001)
  6020. obj_init.solid_geometry = deepcopy(solid_geometry)
  6021. obj_init.apertures = deepcopy(apertures)
  6022. # clear the working objects (perhaps not necessary due of Python GC)
  6023. apertures.clear()
  6024. if not self.collection.get_selected():
  6025. log.warning("App.convert_any2gerber --> No object selected")
  6026. self.inform.emit('[WARNING_NOTCL] %s' %
  6027. _("No object is selected. Select an object and try again."))
  6028. return
  6029. for obj in self.collection.get_selected():
  6030. obj_name = obj.options["name"]
  6031. try:
  6032. if isinstance(obj, FlatCAMExcellon):
  6033. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  6034. elif isinstance(obj, FlatCAMGeometry):
  6035. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  6036. else:
  6037. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  6038. except Exception as e:
  6039. return "Operation failed: %s" % str(e)
  6040. def abort_all_tasks(self):
  6041. if self.abort_flag is False:
  6042. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  6043. self.abort_flag = True
  6044. def app_is_idle(self):
  6045. if self.abort_flag:
  6046. self.inform.emit('[WARNING_NOTCL] %s' %
  6047. _("The current task was gracefully closed on user request..."))
  6048. self.abort_flag = False
  6049. def on_selectall(self):
  6050. self.report_usage("on_selectall()")
  6051. # delete the possible selection box around a possible selected object
  6052. self.delete_selection_shape()
  6053. for name in self.collection.get_names():
  6054. self.collection.set_active(name)
  6055. curr_sel_obj = self.collection.get_by_name(name)
  6056. # create the selection box around the selected object
  6057. if self.defaults['global_selection_shape'] is True:
  6058. self.draw_selection_shape(curr_sel_obj)
  6059. def on_preferences(self):
  6060. # add the tab if it was closed
  6061. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  6062. # delete the absolute and relative position and messages in the infobar
  6063. self.ui.position_label.setText("")
  6064. self.ui.rel_position_label.setText("")
  6065. # Switch plot_area to preferences page
  6066. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  6067. # self.ui.show()
  6068. # this disconnect() is done so the slot will be connected only once
  6069. try:
  6070. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_preferences_closed)
  6071. except (TypeError, AttributeError):
  6072. pass
  6073. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_preferences_closed)
  6074. # detect changes in the preferences
  6075. for idx in range(self.ui.pref_tab_area.count()):
  6076. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6077. try:
  6078. try:
  6079. tb.textEdited.disconnect(self.on_preferences_edited)
  6080. except (TypeError, AttributeError):
  6081. pass
  6082. tb.textEdited.connect(self.on_preferences_edited)
  6083. except AttributeError:
  6084. pass
  6085. try:
  6086. try:
  6087. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6088. except (TypeError, AttributeError):
  6089. pass
  6090. tb.modificationChanged.connect(self.on_preferences_edited)
  6091. except AttributeError:
  6092. pass
  6093. try:
  6094. try:
  6095. tb.toggled.disconnect(self.on_preferences_edited)
  6096. except (TypeError, AttributeError):
  6097. pass
  6098. tb.toggled.connect(self.on_preferences_edited)
  6099. except AttributeError:
  6100. pass
  6101. try:
  6102. try:
  6103. tb.valueChanged.disconnect(self.on_preferences_edited)
  6104. except (TypeError, AttributeError):
  6105. pass
  6106. tb.valueChanged.connect(self.on_preferences_edited)
  6107. except AttributeError:
  6108. pass
  6109. try:
  6110. try:
  6111. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6112. except (TypeError, AttributeError):
  6113. pass
  6114. tb.currentIndexChanged.connect(self.on_preferences_edited)
  6115. except AttributeError:
  6116. pass
  6117. def on_preferences_edited(self):
  6118. self.inform.emit('[WARNING_NOTCL] %s' %
  6119. _("Preferences edited but not saved."))
  6120. self.preferences_changed_flag = True
  6121. def on_preferences_closed(self):
  6122. # disconnect
  6123. for idx in range(self.ui.pref_tab_area.count()):
  6124. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6125. try:
  6126. tb.textEdited.disconnect(self.on_preferences_edited)
  6127. except (TypeError, AttributeError):
  6128. pass
  6129. try:
  6130. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6131. except (TypeError, AttributeError):
  6132. pass
  6133. try:
  6134. tb.toggled.disconnect(self.on_preferences_edited)
  6135. except (TypeError, AttributeError):
  6136. pass
  6137. try:
  6138. tb.valueChanged.disconnect(self.on_preferences_edited)
  6139. except (TypeError, AttributeError):
  6140. pass
  6141. try:
  6142. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6143. except (TypeError, AttributeError):
  6144. pass
  6145. if self.preferences_changed_flag is True:
  6146. msgbox = QtWidgets.QMessageBox()
  6147. msgbox.setText(_("One or more values are changed.\n"
  6148. "Do you want to save the Preferences?"))
  6149. msgbox.setWindowTitle(_("Save Preferences"))
  6150. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6151. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6152. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6153. msgbox.setDefaultButton(bt_yes)
  6154. msgbox.exec_()
  6155. response = msgbox.clickedButton()
  6156. if response == bt_yes:
  6157. self.on_save_button()
  6158. self.inform.emit('[success] %s' %
  6159. _("Preferences saved."))
  6160. else:
  6161. self.preferences_changed_flag = False
  6162. return
  6163. def on_flipy(self):
  6164. self.report_usage("on_flipy()")
  6165. obj_list = self.collection.get_selected()
  6166. xminlist = []
  6167. yminlist = []
  6168. xmaxlist = []
  6169. ymaxlist = []
  6170. if not obj_list:
  6171. self.inform.emit('[WARNING_NOTCL] %s' %
  6172. _("No object selected to Flip on Y axis."))
  6173. else:
  6174. try:
  6175. # first get a bounding box to fit all
  6176. for obj in obj_list:
  6177. xmin, ymin, xmax, ymax = obj.bounds()
  6178. xminlist.append(xmin)
  6179. yminlist.append(ymin)
  6180. xmaxlist.append(xmax)
  6181. ymaxlist.append(ymax)
  6182. # get the minimum x,y and maximum x,y for all objects selected
  6183. xminimal = min(xminlist)
  6184. yminimal = min(yminlist)
  6185. xmaximal = max(xmaxlist)
  6186. ymaximal = max(ymaxlist)
  6187. px = 0.5 * (xminimal + xmaximal)
  6188. py = 0.5 * (yminimal + ymaximal)
  6189. # execute mirroring
  6190. for obj in obj_list:
  6191. obj.mirror('X', [px, py])
  6192. obj.plot()
  6193. self.object_changed.emit(obj)
  6194. self.inform.emit('[success] %s' %
  6195. _("Flip on Y axis done."))
  6196. except Exception as e:
  6197. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6198. (_("Flip action was not executed."), str(e)))
  6199. return
  6200. def on_flipx(self):
  6201. self.report_usage("on_flipx()")
  6202. obj_list = self.collection.get_selected()
  6203. xminlist = []
  6204. yminlist = []
  6205. xmaxlist = []
  6206. ymaxlist = []
  6207. if not obj_list:
  6208. self.inform.emit('[WARNING_NOTCL] %s' %
  6209. _("No object selected to Flip on X axis."))
  6210. else:
  6211. try:
  6212. # first get a bounding box to fit all
  6213. for obj in obj_list:
  6214. xmin, ymin, xmax, ymax = obj.bounds()
  6215. xminlist.append(xmin)
  6216. yminlist.append(ymin)
  6217. xmaxlist.append(xmax)
  6218. ymaxlist.append(ymax)
  6219. # get the minimum x,y and maximum x,y for all objects selected
  6220. xminimal = min(xminlist)
  6221. yminimal = min(yminlist)
  6222. xmaximal = max(xmaxlist)
  6223. ymaximal = max(ymaxlist)
  6224. px = 0.5 * (xminimal + xmaximal)
  6225. py = 0.5 * (yminimal + ymaximal)
  6226. # execute mirroring
  6227. for obj in obj_list:
  6228. obj.mirror('Y', [px, py])
  6229. obj.plot()
  6230. self.object_changed.emit(obj)
  6231. self.inform.emit('[success] %s' %
  6232. _("Flip on X axis done."))
  6233. except Exception as e:
  6234. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6235. (_("Flip action was not executed."), str(e)))
  6236. return
  6237. def on_rotate(self, silent=False, preset=None):
  6238. self.report_usage("on_rotate()")
  6239. obj_list = self.collection.get_selected()
  6240. xminlist = []
  6241. yminlist = []
  6242. xmaxlist = []
  6243. ymaxlist = []
  6244. if not obj_list:
  6245. self.inform.emit('[WARNING_NOTCL] %s' %
  6246. _("No object selected to Rotate."))
  6247. else:
  6248. if silent is False:
  6249. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6250. min=-360, max=360, decimals=4,
  6251. init_val=float(self.defaults['tools_transform_rotate']))
  6252. num, ok = rotatebox.get_value()
  6253. else:
  6254. num = preset
  6255. ok = True
  6256. if ok:
  6257. try:
  6258. # first get a bounding box to fit all
  6259. for obj in obj_list:
  6260. xmin, ymin, xmax, ymax = obj.bounds()
  6261. xminlist.append(xmin)
  6262. yminlist.append(ymin)
  6263. xmaxlist.append(xmax)
  6264. ymaxlist.append(ymax)
  6265. # get the minimum x,y and maximum x,y for all objects selected
  6266. xminimal = min(xminlist)
  6267. yminimal = min(yminlist)
  6268. xmaximal = max(xmaxlist)
  6269. ymaximal = max(ymaxlist)
  6270. px = 0.5 * (xminimal + xmaximal)
  6271. py = 0.5 * (yminimal + ymaximal)
  6272. for sel_obj in obj_list:
  6273. sel_obj.rotate(-float(num), point=(px, py))
  6274. sel_obj.plot()
  6275. self.object_changed.emit(sel_obj)
  6276. self.inform.emit('[success] %s' %
  6277. _("Rotation done."))
  6278. except Exception as e:
  6279. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6280. (_("Rotation movement was not executed."), str(e)))
  6281. return
  6282. def on_skewx(self):
  6283. self.report_usage("on_skewx()")
  6284. obj_list = self.collection.get_selected()
  6285. xminlist = []
  6286. yminlist = []
  6287. if not obj_list:
  6288. self.inform.emit('[WARNING_NOTCL] %s' %
  6289. _("No object selected to Skew/Shear on X axis."))
  6290. else:
  6291. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6292. min=-360, max=360, decimals=4,
  6293. init_val=float(self.defaults['tools_transform_skew_x']))
  6294. num, ok = skewxbox.get_value()
  6295. if ok:
  6296. # first get a bounding box to fit all
  6297. for obj in obj_list:
  6298. xmin, ymin, xmax, ymax = obj.bounds()
  6299. xminlist.append(xmin)
  6300. yminlist.append(ymin)
  6301. # get the minimum x,y and maximum x,y for all objects selected
  6302. xminimal = min(xminlist)
  6303. yminimal = min(yminlist)
  6304. for obj in obj_list:
  6305. obj.skew(num, 0, point=(xminimal, yminimal))
  6306. obj.plot()
  6307. self.object_changed.emit(obj)
  6308. self.inform.emit('[success] %s' %
  6309. _("Skew on X axis done."))
  6310. def on_skewy(self):
  6311. self.report_usage("on_skewy()")
  6312. obj_list = self.collection.get_selected()
  6313. xminlist = []
  6314. yminlist = []
  6315. if not obj_list:
  6316. self.inform.emit('[WARNING_NOTCL] %s' %
  6317. _("No object selected to Skew/Shear on Y axis."))
  6318. else:
  6319. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6320. min=-360, max=360, decimals=4,
  6321. init_val=float(self.defaults['tools_transform_skew_y']))
  6322. num, ok = skewybox.get_value()
  6323. if ok:
  6324. # first get a bounding box to fit all
  6325. for obj in obj_list:
  6326. xmin, ymin, xmax, ymax = obj.bounds()
  6327. xminlist.append(xmin)
  6328. yminlist.append(ymin)
  6329. # get the minimum x,y and maximum x,y for all objects selected
  6330. xminimal = min(xminlist)
  6331. yminimal = min(yminlist)
  6332. for obj in obj_list:
  6333. obj.skew(0, num, point=(xminimal, yminimal))
  6334. obj.plot()
  6335. self.object_changed.emit(obj)
  6336. self.inform.emit('[success] %s' %
  6337. _("Skew on Y axis done."))
  6338. def on_plots_updated(self):
  6339. """
  6340. Callback used to report when the plots have changed.
  6341. Adjust axes and zooms to fit.
  6342. :return: None
  6343. """
  6344. if self.is_legacy is False:
  6345. self.plotcanvas.update() # TODO: Need update canvas?
  6346. else:
  6347. self.plotcanvas.auto_adjust_axes()
  6348. self.on_zoom_fit(None)
  6349. self.collection.update_view()
  6350. # self.inform.emit(_("Plots updated ..."))
  6351. # TODO: Rework toolbar 'clear', 'replot' functions
  6352. def on_toolbar_replot(self):
  6353. """
  6354. Callback for toolbar button. Re-plots all objects.
  6355. :return: None
  6356. """
  6357. self.report_usage("on_toolbar_replot")
  6358. self.log.debug("on_toolbar_replot()")
  6359. try:
  6360. self.collection.get_active().read_form()
  6361. except AttributeError:
  6362. self.log.debug("on_toolbar_replot(): AttributeError")
  6363. pass
  6364. self.plot_all()
  6365. def on_row_activated(self, index):
  6366. if index.isValid():
  6367. if index.internalPointer().parent_item != self.collection.root_item:
  6368. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6369. self.collection.on_item_activated(index)
  6370. def on_collection_updated(self, obj, state, old_name):
  6371. """
  6372. Create a menu from the object loaded in the collection.
  6373. TODO: should use the collection model to do this
  6374. :param obj: object that was changd (added, deleted, renamed)
  6375. :param state: what was done with the objectCand be: added, deleted, delete_all, renamed
  6376. :param old_name: the old name of the object before the action that triggered this slot happened
  6377. :return: None
  6378. """
  6379. icon_files = {
  6380. "gerber": "share/flatcam_icon16.png",
  6381. "excellon": "share/drill16.png",
  6382. "cncjob": "share/cnc16.png",
  6383. "geometry": "share/geometry16.png",
  6384. "script": "share/script_new16.png",
  6385. "document": "share/notes16_1.png"
  6386. }
  6387. if state == 'append':
  6388. for act in self.ui.menuobjects.actions():
  6389. try:
  6390. act.triggered.disconnect()
  6391. except TypeError:
  6392. pass
  6393. self.ui.menuobjects.clear()
  6394. gerber_list = list()
  6395. exc_list = list()
  6396. cncjob_list = list()
  6397. geo_list = list()
  6398. script_list = list()
  6399. doc_list = list()
  6400. for name in self.collection.get_names():
  6401. obj_named = self.collection.get_by_name(name)
  6402. if obj_named.kind == 'gerber':
  6403. gerber_list.append(name)
  6404. elif obj_named.kind == 'excellon':
  6405. exc_list.append(name)
  6406. elif obj_named.kind == 'cncjob':
  6407. cncjob_list.append(name)
  6408. elif obj_named.kind == 'geometry':
  6409. geo_list.append(name)
  6410. elif obj_named.kind == 'script':
  6411. script_list.append(name)
  6412. elif obj_named.kind == 'document':
  6413. doc_list.append(name)
  6414. def add_act(name):
  6415. obj_for_icon = self.collection.get_by_name(name)
  6416. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6417. add_action.setText(name)
  6418. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  6419. add_action.triggered.connect(lambda: self.collection.set_exclusive_active(name))
  6420. self.ui.menuobjects.addAction(add_action)
  6421. for name in gerber_list:
  6422. add_act(name)
  6423. self.ui.menuobjects.addSeparator()
  6424. for name in exc_list:
  6425. add_act(name)
  6426. self.ui.menuobjects.addSeparator()
  6427. for name in cncjob_list:
  6428. add_act(name)
  6429. self.ui.menuobjects.addSeparator()
  6430. for name in geo_list:
  6431. add_act(name)
  6432. self.ui.menuobjects.addSeparator()
  6433. for name in script_list:
  6434. add_act(name)
  6435. self.ui.menuobjects.addSeparator()
  6436. for name in doc_list:
  6437. add_act(name)
  6438. elif state == 'delete':
  6439. for act in self.ui.menuobjects.actions():
  6440. if act.text() == obj.options['name']:
  6441. try:
  6442. act.triggered.disconnect()
  6443. except TypeError:
  6444. pass
  6445. self.ui.menuobjects.removeAction(act)
  6446. break
  6447. elif state == 'rename':
  6448. for act in self.ui.menuobjects.actions():
  6449. if act.text() == old_name:
  6450. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6451. add_action.setText(obj.options['name'])
  6452. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  6453. add_action.triggered.connect(lambda: self.collection.set_exclusive_active(obj.options['name']))
  6454. self.ui.menuobjects.insertAction(act, add_action)
  6455. try:
  6456. act.triggered.disconnect()
  6457. except TypeError:
  6458. pass
  6459. self.ui.menuobjects.removeAction(act)
  6460. break
  6461. elif state =='delete_all':
  6462. for act in self.ui.menuobjects.actions():
  6463. try:
  6464. act.triggered.disconnect()
  6465. except TypeError:
  6466. pass
  6467. self.ui.menuobjects.clear()
  6468. def grid_status(self):
  6469. if self.ui.grid_snap_btn.isChecked():
  6470. return True
  6471. else:
  6472. return False
  6473. def populate_cmenu_grids(self):
  6474. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6475. self.ui.cmenu_gridmenu.clear()
  6476. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  6477. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  6478. grid_toggle.setCheckable(True)
  6479. if self.grid_status() == True:
  6480. grid_toggle.setChecked(True)
  6481. else:
  6482. grid_toggle.setChecked(False)
  6483. self.ui.cmenu_gridmenu.addSeparator()
  6484. for grid in sorted_list:
  6485. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  6486. action.triggered.connect(self.set_grid)
  6487. self.ui.cmenu_gridmenu.addSeparator()
  6488. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  6489. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  6490. grid_add.triggered.connect(self.on_grid_add)
  6491. grid_delete.triggered.connect(self.on_grid_delete)
  6492. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  6493. def set_grid(self):
  6494. self.ui.grid_gap_x_entry.setText(self.sender().text())
  6495. self.ui.grid_gap_y_entry.setText(self.sender().text())
  6496. def on_grid_add(self):
  6497. # ## Current application units in lower Case
  6498. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6499. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  6500. text=_('Enter a Grid Value:'),
  6501. min=0.0000, max=99.9999, decimals=4)
  6502. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  6503. val, ok = grid_add_popup.get_value()
  6504. if ok:
  6505. if float(val) == 0:
  6506. self.inform.emit('[WARNING_NOTCL] %s' %
  6507. _("Please enter a grid value with non-zero value, in Float format."))
  6508. return
  6509. else:
  6510. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  6511. self.defaults["global_grid_context_menu"][str(units)].append(val)
  6512. self.inform.emit('[success] %s...' %
  6513. _("New Grid added"))
  6514. else:
  6515. self.inform.emit('[WARNING_NOTCL] %s...' %
  6516. _("Grid already exists"))
  6517. else:
  6518. self.inform.emit('[WARNING_NOTCL] %s...' %
  6519. _("Adding New Grid cancelled"))
  6520. def on_grid_delete(self):
  6521. # ## Current application units in lower Case
  6522. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6523. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  6524. text='Enter a Grid Value:',
  6525. min=0.0000, max=99.9999, decimals=4)
  6526. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  6527. val, ok = grid_del_popup.get_value()
  6528. if ok:
  6529. if float(val) == 0:
  6530. self.inform.emit('[WARNING_NOTCL] %s' %
  6531. _("Please enter a grid value with non-zero value, in Float format."))
  6532. return
  6533. else:
  6534. try:
  6535. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  6536. except ValueError:
  6537. self.inform.emit('[ERROR_NOTCL]%s...' %
  6538. _(" Grid Value does not exist"))
  6539. return
  6540. self.inform.emit('[success] %s...' %
  6541. _("Grid Value deleted"))
  6542. else:
  6543. self.inform.emit('[WARNING_NOTCL] %s...' %
  6544. _("Delete Grid value cancelled"))
  6545. def on_shortcut_list(self):
  6546. self.report_usage("on_shortcut_list()")
  6547. # add the tab if it was closed
  6548. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  6549. # delete the absolute and relative position and messages in the infobar
  6550. self.ui.position_label.setText("")
  6551. self.ui.rel_position_label.setText("")
  6552. # Switch plot_area to preferences page
  6553. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  6554. # self.ui.show()
  6555. def on_select_tab(self, name):
  6556. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  6557. if self.ui.splitter.sizes()[0] == 0:
  6558. self.ui.splitter.setSizes([1, 1])
  6559. else:
  6560. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  6561. self.ui.splitter.setSizes([0, 1])
  6562. if name == 'project':
  6563. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6564. elif name == 'selected':
  6565. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6566. elif name == 'tool':
  6567. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  6568. def on_copy_name(self):
  6569. self.report_usage("on_copy_name()")
  6570. obj = self.collection.get_active()
  6571. try:
  6572. name = obj.options["name"]
  6573. except AttributeError:
  6574. log.debug("on_copy_name() --> No object selected to copy it's name")
  6575. self.inform.emit('[WARNING_NOTCL]%s' %
  6576. _(" No object selected to copy it's name"))
  6577. return
  6578. self.clipboard.setText(name)
  6579. self.inform.emit(_("Name copied on clipboard ..."))
  6580. def on_mouse_click_over_plot(self, event):
  6581. """
  6582. Default actions are:
  6583. :param event: Contains information about the event, like which button
  6584. was clicked, the pixel coordinates and the axes coordinates.
  6585. :return: None
  6586. """
  6587. self.pos = []
  6588. if self.is_legacy is False:
  6589. event_pos = event.pos
  6590. if self.defaults["global_pan_button"] == '2':
  6591. pan_button = 2
  6592. else:
  6593. pan_button = 3
  6594. # Set the mouse button for panning
  6595. self.plotcanvas.view.camera.pan_button_setting = pan_button
  6596. else:
  6597. event_pos = (event.xdata, event.ydata)
  6598. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6599. if self.defaults["global_pan_button"] == '2':
  6600. pan_button = 3
  6601. else:
  6602. pan_button = 2
  6603. # So it can receive key presses
  6604. self.plotcanvas.native.setFocus()
  6605. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6606. if self.grid_status() == True:
  6607. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  6608. else:
  6609. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  6610. try:
  6611. if event.button == 1:
  6612. # Reset here the relative coordinates so there is a new reference on the click position
  6613. if self.rel_point1 is None:
  6614. self.rel_point1 = self.pos
  6615. else:
  6616. self.rel_point2 = copy(self.rel_point1)
  6617. self.rel_point1 = self.pos
  6618. self.on_mouse_move_over_plot(event, origin_click=True)
  6619. except Exception as e:
  6620. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  6621. def on_double_click_over_plot(self, event):
  6622. if event.button == 1:
  6623. self.doubleclick = True
  6624. def on_mouse_move_over_plot(self, event, origin_click=None):
  6625. """
  6626. Callback for the mouse motion event over the plot.
  6627. :param event: Contains information about the event.
  6628. :param origin_click
  6629. :return: None
  6630. """
  6631. if self.is_legacy is False:
  6632. event_pos = event.pos
  6633. if self.defaults["global_pan_button"] == '2':
  6634. pan_button = 2
  6635. else:
  6636. pan_button = 3
  6637. event_is_dragging = event.is_dragging
  6638. else:
  6639. event_pos = (event.xdata, event.ydata)
  6640. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6641. if self.defaults["global_pan_button"] == '2':
  6642. pan_button = 3
  6643. else:
  6644. pan_button = 2
  6645. event_is_dragging = self.plotcanvas.is_dragging
  6646. # So it can receive key presses
  6647. self.plotcanvas.native.setFocus()
  6648. self.pos_jump = event_pos
  6649. self.ui.popMenu.mouse_is_panning = False
  6650. if not origin_click:
  6651. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  6652. if event.button == pan_button and event_is_dragging == 1:
  6653. self.ui.popMenu.mouse_is_panning = True
  6654. return
  6655. if self.rel_point1 is not None:
  6656. try: # May fail in case mouse not within axes
  6657. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6658. if self.grid_status() == True:
  6659. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6660. # Update cursor
  6661. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  6662. symbol='++', edge_color=self.cursor_color_3D,
  6663. size=self.defaults["global_cursor_size"])
  6664. else:
  6665. pos = (pos_canvas[0], pos_canvas[1])
  6666. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6667. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  6668. dx = pos[0] - float(self.rel_point1[0])
  6669. dy = pos[1] - float(self.rel_point1[1])
  6670. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6671. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6672. self.mouse = [pos[0], pos[1]]
  6673. # if the mouse is moved and the LMB is clicked then the action is a selection
  6674. if event_is_dragging == 1 and event.button == 1:
  6675. self.delete_selection_shape()
  6676. if dx < 0:
  6677. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  6678. face_color=self.defaults['global_alt_sel_fill'])
  6679. self.selection_type = False
  6680. elif dx > 0:
  6681. self.draw_moving_selection_shape(self.pos, pos)
  6682. self.selection_type = True
  6683. else:
  6684. self.selection_type = None
  6685. # hover effect - enabled in Preferences -> General -> GUI Settings
  6686. if self.defaults['global_hover']:
  6687. for obj in self.collection.get_list():
  6688. try:
  6689. # select the object(s) only if it is enabled (plotted)
  6690. if obj.options['plot']:
  6691. if obj not in self.collection.get_selected():
  6692. poly_obj = Polygon(
  6693. [(obj.options['xmin'], obj.options['ymin']),
  6694. (obj.options['xmax'], obj.options['ymin']),
  6695. (obj.options['xmax'], obj.options['ymax']),
  6696. (obj.options['xmin'], obj.options['ymax'])]
  6697. )
  6698. if Point(pos).within(poly_obj):
  6699. if obj.isHovering is False:
  6700. obj.isHovering = True
  6701. obj.notHovering = True
  6702. # create the selection box around the selected object
  6703. self.draw_hover_shape(obj, color='#d1e0e0FF')
  6704. else:
  6705. if obj.notHovering is True:
  6706. obj.notHovering = False
  6707. obj.isHovering = False
  6708. self.delete_hover_shape()
  6709. except:
  6710. # the Exception here will happen if we try to select on screen and we have an
  6711. # newly (and empty) just created Geometry or Excellon object that do not have the
  6712. # xmin, xmax, ymin, ymax options.
  6713. # In this case poly_obj creation (see above) will fail
  6714. pass
  6715. except:
  6716. self.ui.position_label.setText("")
  6717. self.ui.rel_position_label.setText("")
  6718. self.mouse = None
  6719. def on_mouse_click_release_over_plot(self, event):
  6720. """
  6721. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  6722. and has been registered in ''self.__init__()''.
  6723. :param event: contains information about the event.
  6724. :return:
  6725. """
  6726. pos = 0, 0
  6727. if self.is_legacy is False:
  6728. event_pos = event.pos
  6729. right_button = 2
  6730. else:
  6731. event_pos = (event.xdata, event.ydata)
  6732. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6733. right_button = 3
  6734. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6735. if self.grid_status() == True:
  6736. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6737. else:
  6738. pos = (pos_canvas[0], pos_canvas[1])
  6739. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  6740. # canvas menu
  6741. if event.button == right_button: # right click
  6742. if self.ui.popMenu.mouse_is_panning is False:
  6743. self.cursor = QtGui.QCursor()
  6744. self.populate_cmenu_grids()
  6745. self.ui.popMenu.popup(self.cursor.pos())
  6746. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  6747. # selection and then select a type of selection ("enclosing" or "touching")
  6748. try:
  6749. if event.button == 1: # left click
  6750. modifiers = QtWidgets.QApplication.keyboardModifiers()
  6751. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  6752. if modifiers == QtCore.Qt.ShiftModifier:
  6753. # do not auto open the Project Tab
  6754. self.click_noproject = True
  6755. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  6756. self.inform.emit('[success] %s' %
  6757. _("Coordinates copied to clipboard."))
  6758. return
  6759. if self.doubleclick is True:
  6760. self.doubleclick = False
  6761. if self.collection.get_selected():
  6762. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6763. if self.ui.splitter.sizes()[0] == 0:
  6764. self.ui.splitter.setSizes([1, 1])
  6765. # delete the selection shape(S) as it may be in the way
  6766. self.delete_selection_shape()
  6767. self.delete_hover_shape()
  6768. else:
  6769. if self.selection_type is not None:
  6770. self.selection_area_handler(self.pos, pos, self.selection_type)
  6771. self.selection_type = None
  6772. else:
  6773. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  6774. if key_modifier == QtCore.Qt.ShiftModifier:
  6775. mod_key = 'Shift'
  6776. elif key_modifier == QtCore.Qt.ControlModifier:
  6777. mod_key = 'Control'
  6778. else:
  6779. mod_key = None
  6780. if mod_key == self.defaults["global_mselect_key"]:
  6781. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  6782. # deselect, and if it's not selected then it will be selected
  6783. # If there is no active command (self.command_active is None) then we check if we clicked
  6784. # on a object by checking the bounding limits against mouse click position
  6785. if self.command_active is None:
  6786. self.select_objects(key='CTRL')
  6787. self.delete_hover_shape()
  6788. else:
  6789. # If there is no active command (self.command_active is None) then we check if we clicked
  6790. # on a object by checking the bounding limits against mouse click position
  6791. if self.command_active is None:
  6792. self.select_objects()
  6793. self.delete_hover_shape()
  6794. except Exception as e:
  6795. log.warning("Error: %s" % str(e))
  6796. return
  6797. def selection_area_handler(self, start_pos, end_pos, sel_type):
  6798. """
  6799. :param start_pos: mouse position when the selection LMB click was done
  6800. :param end_pos: mouse position when the left mouse button is released
  6801. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  6802. :return:
  6803. """
  6804. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  6805. self.delete_selection_shape()
  6806. for obj in self.collection.get_list():
  6807. try:
  6808. # select the object(s) only if it is enabled (plotted)
  6809. if obj.options['plot']:
  6810. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  6811. (obj.options['xmax'], obj.options['ymin']),
  6812. (obj.options['xmax'], obj.options['ymax']),
  6813. (obj.options['xmin'], obj.options['ymax'])])
  6814. if sel_type is True:
  6815. if poly_obj.within(poly_selection):
  6816. # create the selection box around the selected object
  6817. if self.defaults['global_selection_shape'] is True:
  6818. self.draw_selection_shape(obj)
  6819. self.collection.set_active(obj.options['name'])
  6820. else:
  6821. if poly_selection.intersects(poly_obj):
  6822. # create the selection box around the selected object
  6823. if self.defaults['global_selection_shape'] is True:
  6824. self.draw_selection_shape(obj)
  6825. self.collection.set_active(obj.options['name'])
  6826. except Exception as e:
  6827. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  6828. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  6829. # In this case poly_obj creation (see above) will fail
  6830. log.debug("App.selection_area_handler() --> %s" % str(e))
  6831. def select_objects(self, key=None):
  6832. # list where we store the overlapped objects under our mouse left click position
  6833. objects_under_the_click_list = []
  6834. # Populate the list with the overlapped objects on the click position
  6835. curr_x, curr_y = self.pos
  6836. for obj in self.all_objects_list:
  6837. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  6838. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  6839. if obj.options['name'] not in objects_under_the_click_list:
  6840. if obj.options['plot']:
  6841. # add objects to the objects_under_the_click list only if the object is plotted
  6842. # (active and not disabled)
  6843. objects_under_the_click_list.append(obj.options['name'])
  6844. try:
  6845. # If there is no element in the overlapped objects list then make everyone inactive
  6846. # because we selected "nothing"
  6847. if not objects_under_the_click_list:
  6848. self.collection.set_all_inactive()
  6849. # delete the possible selection box around a possible selected object
  6850. self.delete_selection_shape()
  6851. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  6852. # only when working on App
  6853. if self.call_source == 'app':
  6854. if self.click_noproject is False:
  6855. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6856. else:
  6857. # restore auto open the Project Tab
  6858. self.click_noproject = False
  6859. # delete any text in the status bar, implicitly the last object name that was selected
  6860. self.inform.emit("")
  6861. else:
  6862. self.call_source = 'app'
  6863. else:
  6864. # case when there is only an object under the click and we toggle it
  6865. if len(objects_under_the_click_list) == 1:
  6866. if self.collection.get_active() is None:
  6867. self.collection.set_active(objects_under_the_click_list[0])
  6868. # create the selection box around the selected object
  6869. curr_sel_obj = self.collection.get_active()
  6870. if self.defaults['global_selection_shape'] is True:
  6871. self.draw_selection_shape(curr_sel_obj)
  6872. # self.inform.emit('[selected] %s: %s selected' %
  6873. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6874. if curr_sel_obj.kind == 'gerber':
  6875. self.inform.emit(
  6876. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6877. color='green', name=str(curr_sel_obj.options['name'])))
  6878. elif curr_sel_obj.kind == 'excellon':
  6879. self.inform.emit(
  6880. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6881. color='brown', name=str(curr_sel_obj.options['name'])))
  6882. elif curr_sel_obj.kind == 'cncjob':
  6883. self.inform.emit(
  6884. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6885. color='blue', name=str(curr_sel_obj.options['name'])))
  6886. elif curr_sel_obj.kind == 'geometry':
  6887. self.inform.emit(
  6888. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6889. color='red', name=str(curr_sel_obj.options['name'])))
  6890. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  6891. self.collection.set_all_inactive()
  6892. self.delete_selection_shape()
  6893. self.collection.set_active(objects_under_the_click_list[0])
  6894. # create the selection box around the selected object
  6895. curr_sel_obj = self.collection.get_active()
  6896. if self.defaults['global_selection_shape'] is True:
  6897. self.draw_selection_shape(curr_sel_obj)
  6898. # self.inform.emit('[selected] %s: %s selected' %
  6899. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6900. if curr_sel_obj.kind == 'gerber':
  6901. self.inform.emit(
  6902. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6903. color='green', name=str(curr_sel_obj.options['name'])))
  6904. elif curr_sel_obj.kind == 'excellon':
  6905. self.inform.emit(
  6906. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6907. color='brown', name=str(curr_sel_obj.options['name'])))
  6908. elif curr_sel_obj.kind == 'cncjob':
  6909. self.inform.emit(
  6910. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6911. color='blue', name=str(curr_sel_obj.options['name'])))
  6912. elif curr_sel_obj.kind == 'geometry':
  6913. self.inform.emit(
  6914. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6915. color='red', name=str(curr_sel_obj.options['name'])))
  6916. else:
  6917. self.collection.set_all_inactive()
  6918. self.delete_selection_shape()
  6919. if self.call_source == 'app':
  6920. # delete any text in the status bar, implicitly the last object name that was selected
  6921. self.inform.emit("")
  6922. else:
  6923. self.call_source = 'app'
  6924. else:
  6925. # If there is no selected object
  6926. # make active the first element of the overlapped objects list
  6927. if self.collection.get_active() is None:
  6928. self.collection.set_active(objects_under_the_click_list[0])
  6929. name_sel_obj = self.collection.get_active().options['name']
  6930. # In case that there is a selected object but it is not in the overlapped object list
  6931. # make that object inactive and activate the first element in the overlapped object list
  6932. if name_sel_obj not in objects_under_the_click_list:
  6933. self.collection.set_inactive(name_sel_obj)
  6934. name_sel_obj = objects_under_the_click_list[0]
  6935. self.collection.set_active(name_sel_obj)
  6936. else:
  6937. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  6938. self.collection.set_all_inactive()
  6939. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  6940. len(objects_under_the_click_list)])
  6941. curr_sel_obj = self.collection.get_active()
  6942. # delete the possible selection box around a possible selected object
  6943. self.delete_selection_shape()
  6944. # create the selection box around the selected object
  6945. if self.defaults['global_selection_shape'] is True:
  6946. self.draw_selection_shape(curr_sel_obj)
  6947. # self.inform.emit('[selected] %s: %s selected' %
  6948. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6949. if curr_sel_obj.kind == 'gerber':
  6950. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6951. color='green', name=str(curr_sel_obj.options['name'])))
  6952. elif curr_sel_obj.kind == 'excellon':
  6953. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6954. color='brown', name=str(curr_sel_obj.options['name'])))
  6955. elif curr_sel_obj.kind == 'cncjob':
  6956. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6957. color='blue', name=str(curr_sel_obj.options['name'])))
  6958. elif curr_sel_obj.kind == 'geometry':
  6959. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6960. color='red', name=str(curr_sel_obj.options['name'])))
  6961. # for obj in self.collection.get_list():
  6962. # obj.plot()
  6963. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  6964. # TODO: on selected objects change the object colors and do not draw the selection box
  6965. # self.plotcanvas.update() # this updates the canvas
  6966. except Exception as e:
  6967. log.error("[ERROR] Something went bad. %s" % str(e))
  6968. return
  6969. def delete_hover_shape(self):
  6970. self.hover_shapes.clear()
  6971. self.hover_shapes.redraw()
  6972. def draw_hover_shape(self, sel_obj, color=None):
  6973. """
  6974. :param sel_obj: the object for which the hover shape must be drawn
  6975. :return:
  6976. """
  6977. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6978. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6979. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6980. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6981. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  6982. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6983. hover_rect = hover_rect.buffer(-0.1)
  6984. hover_rect = hover_rect.buffer(0.2)
  6985. else:
  6986. hover_rect = hover_rect.buffer(-0.00393)
  6987. hover_rect = hover_rect.buffer(0.00787)
  6988. # if color:
  6989. # face = Color(color)
  6990. # face.alpha = 0.2
  6991. # outline = Color(color, alpha=0.8)
  6992. # else:
  6993. # face = Color(self.defaults['global_sel_fill'])
  6994. # face.alpha = 0.2
  6995. # outline = self.defaults['global_sel_line']
  6996. if color:
  6997. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  6998. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  6999. else:
  7000. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7001. outline = self.defaults['global_sel_line']
  7002. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  7003. if self.is_legacy is True:
  7004. self.hover_shapes.redraw()
  7005. def delete_selection_shape(self):
  7006. self.move_tool.sel_shapes.clear()
  7007. self.move_tool.sel_shapes.redraw()
  7008. def draw_selection_shape(self, sel_obj, color=None):
  7009. """
  7010. :param sel_obj: the object for which the selection shape must be drawn
  7011. :return:
  7012. """
  7013. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7014. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7015. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7016. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7017. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7018. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  7019. sel_rect = sel_rect.buffer(-0.1)
  7020. sel_rect = sel_rect.buffer(0.2)
  7021. else:
  7022. sel_rect = sel_rect.buffer(-0.00393)
  7023. sel_rect = sel_rect.buffer(0.00787)
  7024. # if color:
  7025. # face = Color(color, alpha=0.2)
  7026. # outline = Color(color, alpha=0.8)
  7027. # else:
  7028. # face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  7029. # outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  7030. if color:
  7031. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7032. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7033. else:
  7034. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7035. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  7036. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  7037. color=outline,
  7038. face_color=face,
  7039. update=True,
  7040. layer=0,
  7041. tolerance=None))
  7042. if self.is_legacy is True:
  7043. self.move_tool.sel_shapes.redraw()
  7044. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  7045. """
  7046. :param old_coords: old coordinates
  7047. :param coords: new coordinates
  7048. :return:
  7049. """
  7050. if 'color' in kwargs:
  7051. color = kwargs['color']
  7052. else:
  7053. color = self.defaults['global_sel_line']
  7054. if 'face_color' in kwargs:
  7055. face_color = kwargs['face_color']
  7056. else:
  7057. face_color = self.defaults['global_sel_fill']
  7058. if 'face_alpha' in kwargs:
  7059. face_alpha = kwargs['face_alpha']
  7060. else:
  7061. face_alpha = 0.3
  7062. x0, y0 = old_coords
  7063. x1, y1 = coords
  7064. pt1 = (x0, y0)
  7065. pt2 = (x1, y0)
  7066. pt3 = (x1, y1)
  7067. pt4 = (x0, y1)
  7068. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7069. # color_t = Color(face_color)
  7070. # color_t.alpha = face_alpha
  7071. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  7072. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  7073. layer=0, tolerance=None)
  7074. if self.is_legacy is True:
  7075. self.move_tool.sel_shapes.redraw()
  7076. def on_file_new_click(self):
  7077. if self.collection.get_list() and self.should_we_save:
  7078. msgbox = QtWidgets.QMessageBox()
  7079. # msgbox.setText("<B>Save changes ...</B>")
  7080. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7081. "Creating a New project will delete them.\n"
  7082. "Do you want to Save the project?"))
  7083. msgbox.setWindowTitle(_("Save changes"))
  7084. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  7085. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7086. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7087. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7088. msgbox.setDefaultButton(bt_yes)
  7089. msgbox.exec_()
  7090. response = msgbox.clickedButton()
  7091. if response == bt_yes:
  7092. self.on_file_saveprojectas()
  7093. elif response == bt_cancel:
  7094. return
  7095. elif response == bt_no:
  7096. self.on_file_new()
  7097. else:
  7098. self.on_file_new()
  7099. self.inform.emit('[success] %s...' %
  7100. _("New Project created"))
  7101. def on_file_new(self, cli=None):
  7102. """
  7103. Callback for menu item File->New. Returns the application to its
  7104. startup state. This method is thread-safe.
  7105. :return: None
  7106. """
  7107. self.report_usage("on_file_new")
  7108. # Remove everything from memory
  7109. App.log.debug("on_file_new()")
  7110. if self.call_source != 'app':
  7111. self.editor2object(cleanup=True)
  7112. # ## EDITOR section
  7113. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  7114. self.exc_editor = FlatCAMExcEditor(self)
  7115. self.grb_editor = FlatCAMGrbEditor(self)
  7116. # Clear pool
  7117. self.clear_pool()
  7118. for obj in self.collection.get_list():
  7119. # delete shapes left drawn from mark shape_collections, if any
  7120. if isinstance(obj, FlatCAMGerber):
  7121. try:
  7122. obj.mark_shapes.enabled = False
  7123. obj.mark_shapes.clear(update=True)
  7124. except AttributeError:
  7125. pass
  7126. # also delete annotation shapes, if any
  7127. elif isinstance(obj, FlatCAMCNCjob):
  7128. try:
  7129. obj.annotation.enabled = False
  7130. obj.annotation.clear(update=True)
  7131. except AttributeError:
  7132. pass
  7133. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7134. self.init_tcl()
  7135. self.delete_selection_shape()
  7136. self.collection.delete_all()
  7137. self.setup_component_editor()
  7138. # Clear project filename
  7139. self.project_filename = None
  7140. # Load the application defaults
  7141. self.load_defaults(filename='current_defaults')
  7142. # Re-fresh project options
  7143. self.on_options_app2project()
  7144. # Init Tools
  7145. self.init_tools()
  7146. if cli is None:
  7147. # Close any Tabs opened in the Plot Tab Area section
  7148. for index in range(self.ui.plot_tab_area.count()):
  7149. self.ui.plot_tab_area.closeTab(index)
  7150. # for whatever reason previous command does not close the last tab so I do it manually
  7151. self.ui.plot_tab_area.closeTab(0)
  7152. # # And then add again the Plot Area
  7153. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  7154. self.ui.plot_tab_area.protectTab(0)
  7155. # take the focus of the Notebook on Project Tab.
  7156. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7157. self.set_ui_title(name=_("New Project - Not saved"))
  7158. def obj_properties(self):
  7159. self.report_usage("obj_properties()")
  7160. self.properties_tool.run(toggle=False)
  7161. def on_project_context_save(self):
  7162. obj = self.collection.get_active()
  7163. if type(obj) == FlatCAMGeometry:
  7164. self.on_file_exportdxf()
  7165. elif type(obj) == FlatCAMExcellon:
  7166. self.on_file_saveexcellon()
  7167. elif type(obj) == FlatCAMCNCjob:
  7168. obj.on_exportgcode_button_click()
  7169. elif type(obj) == FlatCAMGerber:
  7170. self.on_file_savegerber()
  7171. elif type(obj) == FlatCAMScript:
  7172. self.on_file_savescript()
  7173. elif type(obj) == FlatCAMDocument:
  7174. self.on_file_savedocument()
  7175. def obj_move(self):
  7176. self.report_usage("obj_move()")
  7177. self.move_tool.run(toggle=False)
  7178. def on_fileopengerber(self, checked=None, name=None):
  7179. """
  7180. File menu callback for opening a Gerber.
  7181. :return: None
  7182. """
  7183. self.report_usage("on_fileopengerber")
  7184. App.log.debug("on_fileopengerber()")
  7185. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  7186. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  7187. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  7188. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  7189. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  7190. "*.mil);;" \
  7191. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  7192. "Allegro Files (*.art);;" \
  7193. "Mentor Files (*.pho *.gdo);;" \
  7194. "All Files (*.*)"
  7195. if name is None:
  7196. try:
  7197. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  7198. directory=self.get_last_folder(),
  7199. filter=_filter_)
  7200. except TypeError:
  7201. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  7202. filenames = [str(filename) for filename in filenames]
  7203. else:
  7204. filenames = [name]
  7205. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7206. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7207. _("Opening Gerber file.")),
  7208. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7209. color=QtGui.QColor("gray"))
  7210. if len(filenames) == 0:
  7211. self.inform.emit('[WARNING_NOTCL] %s' %
  7212. _("Open Gerber cancelled."))
  7213. else:
  7214. for filename in filenames:
  7215. if filename != '':
  7216. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  7217. def on_fileopenexcellon(self, checked=None, name=None):
  7218. """
  7219. File menu callback for opening an Excellon file.
  7220. :return: None
  7221. """
  7222. self.report_usage("on_fileopenexcellon")
  7223. App.log.debug("on_fileopenexcellon()")
  7224. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  7225. "All Files (*.*)"
  7226. if name is None:
  7227. try:
  7228. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  7229. directory=self.get_last_folder(),
  7230. filter=_filter_)
  7231. except TypeError:
  7232. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  7233. filenames = [str(filename) for filename in filenames]
  7234. else:
  7235. filenames = [str(name)]
  7236. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7237. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7238. _("Opening Excellon file.")),
  7239. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7240. color=QtGui.QColor("gray"))
  7241. if len(filenames) == 0:
  7242. self.inform.emit('[WARNING_NOTCL]%s' %
  7243. _(" Open Excellon cancelled."))
  7244. else:
  7245. for filename in filenames:
  7246. if filename != '':
  7247. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  7248. def on_fileopengcode(self, checked=None, name=None):
  7249. """
  7250. File menu call back for opening gcode.
  7251. :return: None
  7252. """
  7253. self.report_usage("on_fileopengcode")
  7254. App.log.debug("on_fileopengcode()")
  7255. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  7256. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  7257. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  7258. "All Files (*.*)"
  7259. if name is None:
  7260. try:
  7261. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  7262. directory=self.get_last_folder(),
  7263. filter=_filter_)
  7264. except TypeError:
  7265. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  7266. filenames = [str(filename) for filename in filenames]
  7267. else:
  7268. filenames = [name]
  7269. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7270. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7271. _("Opening G-Code file.")),
  7272. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7273. color=QtGui.QColor("gray"))
  7274. if len(filenames) == 0:
  7275. self.inform.emit('[WARNING_NOTCL] %s' %
  7276. _("Open G-Code cancelled."))
  7277. else:
  7278. for filename in filenames:
  7279. if filename != '':
  7280. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename]})
  7281. def on_file_openproject(self, checked=None):
  7282. """
  7283. File menu callback for opening a project.
  7284. :return: None
  7285. """
  7286. self.report_usage("on_file_openproject")
  7287. App.log.debug("on_file_openproject()")
  7288. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  7289. try:
  7290. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  7291. directory=self.get_last_folder(), filter=_filter_)
  7292. except TypeError:
  7293. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  7294. # The Qt methods above will return a QString which can cause problems later.
  7295. # So far json.dump() will fail to serialize it.
  7296. # TODO: Improve the serialization methods and remove this fix.
  7297. filename = str(filename)
  7298. if filename == "":
  7299. self.inform.emit('[WARNING_NOTCL] %s' %
  7300. _("Open Project cancelled."))
  7301. else:
  7302. # self.worker_task.emit({'fcn': self.open_project,
  7303. # 'params': [filename]})
  7304. # The above was failing because open_project() is not
  7305. # thread safe. The new_project()
  7306. self.open_project(filename)
  7307. def on_file_openconfig(self, checked=None):
  7308. """
  7309. File menu callback for opening a config file.
  7310. :return: None
  7311. """
  7312. self.report_usage("on_file_openconfig")
  7313. App.log.debug("on_file_openconfig()")
  7314. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  7315. try:
  7316. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7317. directory=self.data_path, filter=_filter_)
  7318. except TypeError:
  7319. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7320. filter=_filter_)
  7321. if filename == "":
  7322. self.inform.emit('[WARNING_NOTCL] %s' %
  7323. _("Open Config cancelled."))
  7324. else:
  7325. self.open_config_file(filename)
  7326. def on_file_exportsvg(self):
  7327. """
  7328. Callback for menu item File->Export SVG.
  7329. :return: None
  7330. """
  7331. self.report_usage("on_file_exportsvg")
  7332. App.log.debug("on_file_exportsvg()")
  7333. obj = self.collection.get_active()
  7334. if obj is None:
  7335. self.inform.emit('[WARNING_NOTCL] %s' %
  7336. _("No object selected."))
  7337. msg = _("Please Select a Geometry object to export")
  7338. msgbox = QtWidgets.QMessageBox()
  7339. msgbox.setInformativeText(msg)
  7340. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7341. msgbox.setDefaultButton(bt_ok)
  7342. msgbox.exec_()
  7343. return
  7344. # Check for more compatible types and add as required
  7345. if (not isinstance(obj, FlatCAMGeometry)
  7346. and not isinstance(obj, FlatCAMGerber)
  7347. and not isinstance(obj, FlatCAMCNCjob)
  7348. and not isinstance(obj, FlatCAMExcellon)):
  7349. msg = '[ERROR_NOTCL] %s' % \
  7350. _("Only Geometry, Gerber and CNCJob objects can be used.")
  7351. msgbox = QtWidgets.QMessageBox()
  7352. msgbox.setInformativeText(msg)
  7353. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7354. msgbox.setDefaultButton(bt_ok)
  7355. msgbox.exec_()
  7356. return
  7357. name = obj.options["name"]
  7358. _filter = "SVG File (*.svg);;All Files (*.*)"
  7359. try:
  7360. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7361. caption=_("Export SVG"),
  7362. directory=self.get_last_save_folder() + '/' + str(name),
  7363. filter=_filter)
  7364. except TypeError:
  7365. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  7366. filename = str(filename)
  7367. if filename == "":
  7368. self.inform.emit('[WARNING_NOTCL]%s' %
  7369. _(" Export SVG cancelled."))
  7370. return
  7371. else:
  7372. self.export_svg(name, filename)
  7373. if self.defaults["global_open_style"] is False:
  7374. self.file_opened.emit("SVG", filename)
  7375. self.file_saved.emit("SVG", filename)
  7376. def on_file_exportpng(self):
  7377. self.report_usage("on_file_exportpng")
  7378. App.log.debug("on_file_exportpng()")
  7379. self.date = str(datetime.today()).rpartition('.')[0]
  7380. self.date = ''.join(c for c in self.date if c not in ':-')
  7381. self.date = self.date.replace(' ', '_')
  7382. image = _screenshot()
  7383. data = np.asarray(image)
  7384. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  7385. self.inform.emit('[[WARNING_NOTCL]] %s' %
  7386. _('Data must be a 3D array with last dimension 3 or 4'))
  7387. return
  7388. filter_ = "PNG File (*.png);;All Files (*.*)"
  7389. try:
  7390. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7391. caption=_("Export PNG Image"),
  7392. directory=self.get_last_save_folder() + '/png_' + self.date,
  7393. filter=filter_)
  7394. except TypeError:
  7395. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  7396. filename = str(filename)
  7397. if filename == "":
  7398. self.inform.emit(_("Export PNG cancelled."))
  7399. return
  7400. else:
  7401. write_png(filename, data)
  7402. if self.defaults["global_open_style"] is False:
  7403. self.file_opened.emit("png", filename)
  7404. self.file_saved.emit("png", filename)
  7405. def on_file_savegerber(self):
  7406. """
  7407. Callback for menu item in Project context menu.
  7408. :return: None
  7409. """
  7410. self.report_usage("on_file_savegerber")
  7411. App.log.debug("on_file_savegerber()")
  7412. obj = self.collection.get_active()
  7413. if obj is None:
  7414. self.inform.emit('[WARNING_NOTCL] %s' %
  7415. _("No object selected. Please select an Gerber object to export."))
  7416. return
  7417. # Check for more compatible types and add as required
  7418. if not isinstance(obj, FlatCAMGerber):
  7419. self.inform.emit('[ERROR_NOTCL] %s' %
  7420. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7421. return
  7422. name = self.collection.get_active().options["name"]
  7423. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  7424. try:
  7425. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7426. caption="Save Gerber source file",
  7427. directory=self.get_last_save_folder() + '/' + name,
  7428. filter=_filter)
  7429. except TypeError:
  7430. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  7431. filename = str(filename)
  7432. if filename == "":
  7433. self.inform.emit('[WARNING_NOTCL] %s' %
  7434. _("Save Gerber source file cancelled."))
  7435. return
  7436. else:
  7437. self.save_source_file(name, filename)
  7438. if self.defaults["global_open_style"] is False:
  7439. self.file_opened.emit("Gerber", filename)
  7440. self.file_saved.emit("Gerber", filename)
  7441. def on_file_savescript(self):
  7442. """
  7443. Callback for menu item in Project context menu.
  7444. :return: None
  7445. """
  7446. self.report_usage("on_file_savescript")
  7447. App.log.debug("on_file_savescript()")
  7448. obj = self.collection.get_active()
  7449. if obj is None:
  7450. self.inform.emit('[WARNING_NOTCL] %s' %
  7451. _("No object selected. Please select an Script object to export."))
  7452. return
  7453. # Check for more compatible types and add as required
  7454. if not isinstance(obj, FlatCAMScript):
  7455. self.inform.emit('[ERROR_NOTCL] %s' %
  7456. _("Failed. Only Script objects can be saved as TCL Script files..."))
  7457. return
  7458. name = self.collection.get_active().options["name"]
  7459. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  7460. try:
  7461. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7462. caption="Save Script source file",
  7463. directory=self.get_last_save_folder() + '/' + name,
  7464. filter=_filter)
  7465. except TypeError:
  7466. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Script source file"), filter=_filter)
  7467. filename = str(filename)
  7468. if filename == "":
  7469. self.inform.emit('[WARNING_NOTCL] %s' %
  7470. _("Save Script source file cancelled."))
  7471. return
  7472. else:
  7473. self.save_source_file(name, filename)
  7474. if self.defaults["global_open_style"] is False:
  7475. self.file_opened.emit("Script", filename)
  7476. self.file_saved.emit("Script", filename)
  7477. def on_file_savedocument(self):
  7478. """
  7479. Callback for menu item in Project context menu.
  7480. :return: None
  7481. """
  7482. self.report_usage("on_file_savedocument")
  7483. App.log.debug("on_file_savedocument()")
  7484. obj = self.collection.get_active()
  7485. if obj is None:
  7486. self.inform.emit('[WARNING_NOTCL] %s' %
  7487. _("No object selected. Please select an Document object to export."))
  7488. return
  7489. # Check for more compatible types and add as required
  7490. if not isinstance(obj, FlatCAMScript):
  7491. self.inform.emit('[ERROR_NOTCL] %s' %
  7492. _("Failed. Only Document objects can be saved as Document files..."))
  7493. return
  7494. name = self.collection.get_active().options["name"]
  7495. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  7496. try:
  7497. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7498. caption="Save Document source file",
  7499. directory=self.get_last_save_folder() + '/' + name,
  7500. filter=_filter)
  7501. except TypeError:
  7502. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Document source file"), filter=_filter)
  7503. filename = str(filename)
  7504. if filename == "":
  7505. self.inform.emit('[WARNING_NOTCL] %s' %
  7506. _("Save Document source file cancelled."))
  7507. return
  7508. else:
  7509. self.save_source_file(name, filename)
  7510. if self.defaults["global_open_style"] is False:
  7511. self.file_opened.emit("Document", filename)
  7512. self.file_saved.emit("Document", filename)
  7513. def on_file_saveexcellon(self):
  7514. """
  7515. Callback for menu item in project context menu.
  7516. :return: None
  7517. """
  7518. self.report_usage("on_file_saveexcellon")
  7519. App.log.debug("on_file_saveexcellon()")
  7520. obj = self.collection.get_active()
  7521. if obj is None:
  7522. self.inform.emit('[WARNING_NOTCL] %s' %
  7523. _("No object selected. Please select an Excellon object to export."))
  7524. return
  7525. # Check for more compatible types and add as required
  7526. if not isinstance(obj, FlatCAMExcellon):
  7527. self.inform.emit('[ERROR_NOTCL] %s' %
  7528. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7529. return
  7530. name = self.collection.get_active().options["name"]
  7531. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7532. try:
  7533. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7534. caption=_("Save Excellon source file"),
  7535. directory=self.get_last_save_folder() + '/' + name,
  7536. filter=_filter)
  7537. except TypeError:
  7538. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  7539. filename = str(filename)
  7540. if filename == "":
  7541. self.inform.emit('[WARNING_NOTCL] %s' %
  7542. _("Saving Excellon source file cancelled."))
  7543. return
  7544. else:
  7545. self.save_source_file(name, filename)
  7546. if self.defaults["global_open_style"] is False:
  7547. self.file_opened.emit("Excellon", filename)
  7548. self.file_saved.emit("Excellon", filename)
  7549. def on_file_exportexcellon(self):
  7550. """
  7551. Callback for menu item File->Export->Excellon.
  7552. :return: None
  7553. """
  7554. self.report_usage("on_file_exportexcellon")
  7555. App.log.debug("on_file_exportexcellon()")
  7556. obj = self.collection.get_active()
  7557. if obj is None:
  7558. self.inform.emit('[WARNING_NOTCL] %s' %
  7559. _("No object selected. Please Select an Excellon object to export."))
  7560. return
  7561. # Check for more compatible types and add as required
  7562. if not isinstance(obj, FlatCAMExcellon):
  7563. self.inform.emit('[ERROR_NOTCL] %s' %
  7564. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7565. return
  7566. name = self.collection.get_active().options["name"]
  7567. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7568. try:
  7569. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7570. caption=_("Export Excellon"),
  7571. directory=self.get_last_save_folder() + '/' + name,
  7572. filter=_filter)
  7573. except TypeError:
  7574. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  7575. filename = str(filename)
  7576. if filename == "":
  7577. self.inform.emit('[WARNING_NOTCL] %s' %
  7578. _("Export Excellon cancelled."))
  7579. return
  7580. else:
  7581. self.export_excellon(name, filename)
  7582. if self.defaults["global_open_style"] is False:
  7583. self.file_opened.emit("Excellon", filename)
  7584. self.file_saved.emit("Excellon", filename)
  7585. def on_file_exportgerber(self):
  7586. """
  7587. Callback for menu item File->Export->Gerber.
  7588. :return: None
  7589. """
  7590. self.report_usage("on_file_exportgerber")
  7591. App.log.debug("on_file_exportgerber()")
  7592. obj = self.collection.get_active()
  7593. if obj is None:
  7594. self.inform.emit('[WARNING_NOTCL] %s' %
  7595. _("No object selected. Please Select an Gerber object to export."))
  7596. return
  7597. # Check for more compatible types and add as required
  7598. if not isinstance(obj, FlatCAMGerber):
  7599. self.inform.emit('[ERROR_NOTCL] %s' %
  7600. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7601. return
  7602. name = self.collection.get_active().options["name"]
  7603. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  7604. try:
  7605. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7606. caption=_("Export Gerber"),
  7607. directory=self.get_last_save_folder() + '/' + name,
  7608. filter=_filter_)
  7609. except TypeError:
  7610. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  7611. filename = str(filename)
  7612. if filename == "":
  7613. self.inform.emit('[WARNING_NOTCL] %s' %
  7614. _("Export Gerber cancelled."))
  7615. return
  7616. else:
  7617. self.export_gerber(name, filename)
  7618. if self.defaults["global_open_style"] is False:
  7619. self.file_opened.emit("Gerber", filename)
  7620. self.file_saved.emit("Gerber", filename)
  7621. def on_file_exportdxf(self):
  7622. """
  7623. Callback for menu item File->Export DXF.
  7624. :return: None
  7625. """
  7626. self.report_usage("on_file_exportdxf")
  7627. App.log.debug("on_file_exportdxf()")
  7628. obj = self.collection.get_active()
  7629. if obj is None:
  7630. self.inform.emit('[WARNING_NOTCL] %s' %
  7631. _("No object selected."))
  7632. msg = _("Please Select a Geometry object to export")
  7633. msgbox = QtWidgets.QMessageBox()
  7634. msgbox.setInformativeText(msg)
  7635. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7636. msgbox.setDefaultButton(bt_ok)
  7637. msgbox.exec_()
  7638. return
  7639. # Check for more compatible types and add as required
  7640. if not isinstance(obj, FlatCAMGeometry):
  7641. msg = '[ERROR_NOTCL] %s' % \
  7642. _("Only Geometry objects can be used.")
  7643. msgbox = QtWidgets.QMessageBox()
  7644. msgbox.setInformativeText(msg)
  7645. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7646. msgbox.setDefaultButton(bt_ok)
  7647. msgbox.exec_()
  7648. return
  7649. name = self.collection.get_active().options["name"]
  7650. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7651. try:
  7652. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7653. caption=_("Export DXF"),
  7654. directory=self.get_last_save_folder() + '/' + name,
  7655. filter=_filter_)
  7656. except TypeError:
  7657. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  7658. filter=_filter_)
  7659. filename = str(filename)
  7660. if filename == "":
  7661. self.inform.emit('[WARNING_NOTCL] %s' %
  7662. _("Export DXF cancelled."))
  7663. return
  7664. else:
  7665. self.export_dxf(name, filename)
  7666. if self.defaults["global_open_style"] is False:
  7667. self.file_opened.emit("DXF", filename)
  7668. self.file_saved.emit("DXF", filename)
  7669. def on_file_importsvg(self, type_of_obj):
  7670. """
  7671. Callback for menu item File->Import SVG.
  7672. :param type_of_obj: to import the SVG as Geometry or as Gerber
  7673. :type type_of_obj: str
  7674. :return: None
  7675. """
  7676. self.report_usage("on_file_importsvg")
  7677. App.log.debug("on_file_importsvg()")
  7678. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  7679. try:
  7680. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7681. directory=self.get_last_folder(), filter=_filter_)
  7682. except TypeError:
  7683. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7684. filter=_filter_)
  7685. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7686. type_of_obj = "geometry"
  7687. filenames = [str(filename) for filename in filenames]
  7688. if len(filenames) == 0:
  7689. self.inform.emit('[WARNING_NOTCL] %s' %
  7690. _("Open SVG cancelled."))
  7691. else:
  7692. for filename in filenames:
  7693. if filename != '':
  7694. self.worker_task.emit({'fcn': self.import_svg,
  7695. 'params': [filename, type_of_obj]})
  7696. def on_file_importdxf(self, type_of_obj):
  7697. """
  7698. Callback for menu item File->Import DXF.
  7699. :param type_of_obj: to import the DXF as Geometry or as Gerber
  7700. :type type_of_obj: str
  7701. :return: None
  7702. """
  7703. self.report_usage("on_file_importdxf")
  7704. App.log.debug("on_file_importdxf()")
  7705. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7706. try:
  7707. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7708. directory=self.get_last_folder(),
  7709. filter=_filter_)
  7710. except TypeError:
  7711. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7712. filter=_filter_)
  7713. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7714. type_of_obj = "geometry"
  7715. filenames = [str(filename) for filename in filenames]
  7716. if len(filenames) == 0:
  7717. self.inform.emit('[WARNING_NOTCL] %s' %
  7718. _("Open DXF cancelled."))
  7719. else:
  7720. for filename in filenames:
  7721. if filename != '':
  7722. self.worker_task.emit({'fcn': self.import_dxf,
  7723. 'params': [filename, type_of_obj]})
  7724. # ###############################################################################################################
  7725. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  7726. # ###############################################################################################################
  7727. def init_code_editor(self, name):
  7728. self.ui.text_editor_tab = TextEditor(app=self)
  7729. # add the tab if it was closed
  7730. self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, '%s' % name)
  7731. self.ui.text_editor_tab.setObjectName('text_editor_tab')
  7732. # delete the absolute and relative position and messages in the infobar
  7733. self.ui.position_label.setText("")
  7734. self.ui.rel_position_label.setText("")
  7735. # first clear previous text in text editor (if any)
  7736. self.ui.text_editor_tab.code_editor.clear()
  7737. self.ui.text_editor_tab.code_editor.setReadOnly(False)
  7738. self.toggle_codeeditor = True
  7739. self.ui.text_editor_tab.code_editor.completer_enable = False
  7740. self.ui.text_editor_tab.buttonRun.hide()
  7741. # make sure to keep a reference to the code editor
  7742. self.reference_code_editor = self.ui.text_editor_tab.code_editor
  7743. # Switch plot_area to CNCJob tab
  7744. self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7745. def on_view_source(self):
  7746. self.inform.emit('%s' %
  7747. _("Viewing the source code of the selected object."))
  7748. self.proc_container.view.set_busy(_("Loading..."))
  7749. try:
  7750. obj = self.collection.get_active()
  7751. except Exception as e:
  7752. log.debug("App.on_view_source() --> %s" % str(e))
  7753. self.inform.emit('[WARNING_NOTCL] %s' %
  7754. _("Select an Gerber or Excellon file to view it's source file."))
  7755. return 'fail'
  7756. if obj.kind == 'gerber':
  7757. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  7758. elif obj.kind == 'excellon':
  7759. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  7760. elif obj.kind == 'cncjob':
  7761. "GCode Files (*.NC);;All Files (*.*)"
  7762. else:
  7763. flt = "All Files (*.*)"
  7764. self.source_editor_tab = TextEditor(app=self)
  7765. # add the tab if it was closed
  7766. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  7767. self.source_editor_tab.setObjectName('source_editor_tab')
  7768. # delete the absolute and relative position and messages in the infobar
  7769. self.ui.position_label.setText("")
  7770. self.ui.rel_position_label.setText("")
  7771. # first clear previous text in text editor (if any)
  7772. self.source_editor_tab.code_editor.clear()
  7773. self.source_editor_tab.code_editor.setReadOnly(False)
  7774. self.source_editor_tab.code_editor.completer_enable = False
  7775. self.source_editor_tab.buttonRun.hide()
  7776. # Switch plot_area to CNCJob tab
  7777. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  7778. self.source_editor_tab.buttonOpen.clicked.disconnect()
  7779. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  7780. self.source_editor_tab.buttonSave.clicked.disconnect()
  7781. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  7782. # then append the text from GCode to the text editor
  7783. if obj.kind == 'cncjob':
  7784. try:
  7785. file = obj.export_gcode(
  7786. preamble=self.defaults["cncjob_prepend"],
  7787. postamble=self.defaults["cncjob_append"],
  7788. to_file=True)
  7789. if file == 'fail':
  7790. return 'fail'
  7791. except AttributeError:
  7792. self.inform.emit('[WARNING_NOTCL] %s' %
  7793. _("There is no selected object for which to see it's source file code."))
  7794. return 'fail'
  7795. else:
  7796. try:
  7797. file = StringIO(obj.source_file)
  7798. except AttributeError:
  7799. self.inform.emit('[WARNING_NOTCL] %s' %
  7800. _("There is no selected object for which to see it's source file code."))
  7801. return 'fail'
  7802. self.source_editor_tab.t_frame.hide()
  7803. try:
  7804. for line in file:
  7805. QtWidgets.QApplication.processEvents()
  7806. proc_line = str(line).strip('\n')
  7807. self.source_editor_tab.code_editor.append(proc_line)
  7808. except Exception as e:
  7809. log.debug('App.on_view_source() -->%s' % str(e))
  7810. self.inform.emit('[ERROR] %s: %s' %
  7811. (_('Failed to load the source code for the selected object'), str(e)))
  7812. return
  7813. self.source_editor_tab.handleTextChanged()
  7814. self.source_editor_tab.t_frame.show()
  7815. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7816. self.proc_container.view.set_idle()
  7817. # self.ui.show()
  7818. def on_toggle_code_editor(self):
  7819. self.report_usage("on_toggle_code_editor()")
  7820. if self.toggle_codeeditor is False:
  7821. self.init_code_editor(name=_("Code Editor"))
  7822. self.ui.text_editor_tab.buttonOpen.clicked.disconnect()
  7823. self.ui.text_editor_tab.buttonOpen.clicked.connect(lambda: self.ui.text_editor_tab.handleOpen())
  7824. self.ui.text_editor_tab.buttonSave.clicked.disconnect()
  7825. self.ui.text_editor_tab.buttonSave.clicked.connect(lambda: self.ui.text_editor_tab.handleSaveGCode())
  7826. else:
  7827. for idx in range(self.ui.plot_tab_area.count()):
  7828. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  7829. self.ui.plot_tab_area.closeTab(idx)
  7830. break
  7831. self.toggle_codeeditor = False
  7832. def on_filenewscript(self, silent=False, name=None, text=None):
  7833. """
  7834. Will create a new script file and open it in the Code Editor
  7835. :param silent: if True will not display status messages
  7836. :return: None
  7837. """
  7838. if silent is False:
  7839. self.inform.emit('[success] %s' %
  7840. _("New TCL script file created in Code Editor."))
  7841. # delete the absolute and relative position and messages in the infobar
  7842. self.ui.position_label.setText("")
  7843. self.ui.rel_position_label.setText("")
  7844. if name is not None:
  7845. self.new_script_object(name=name, text=text)
  7846. else:
  7847. self.new_script_object(text=text)
  7848. # script_text = script_obj.source_file
  7849. #
  7850. # self.proc_container.view.set_busy(_("Loading..."))
  7851. # script_obj.script_editor_tab.t_frame.hide()
  7852. #
  7853. # script_obj.script_editor_tab.t_frame.show()
  7854. # self.proc_container.view.set_idle()
  7855. def on_fileopenscript(self, name=None, silent=False):
  7856. """
  7857. Will open a Tcl script file into the Code Editor
  7858. :param silent: if True will not display status messages
  7859. :param name: name of a Tcl script file to open
  7860. :return:
  7861. """
  7862. self.report_usage("on_fileopenscript")
  7863. App.log.debug("on_fileopenscript()")
  7864. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7865. if name:
  7866. filenames = [name]
  7867. else:
  7868. try:
  7869. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  7870. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  7871. except TypeError:
  7872. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  7873. if len(filenames) == 0:
  7874. if silent is False:
  7875. self.inform.emit('[WARNING_NOTCL] %s' % _("Open TCL script cancelled."))
  7876. else:
  7877. for filename in filenames:
  7878. if filename != '':
  7879. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  7880. def on_filerunscript(self, name=None, silent=False):
  7881. """
  7882. File menu callback for loading and running a TCL script.
  7883. :param silent: if True will not display status messages
  7884. :param name: name of a Tcl script file to be run by FlatCAM
  7885. :return: None
  7886. """
  7887. self.report_usage("on_filerunscript")
  7888. App.log.debug("on_file_runscript()")
  7889. if name:
  7890. filename = name
  7891. if self.cmd_line_headless != 1:
  7892. self.splash.showMessage('%s: %ssec\n%s' %
  7893. (_("Canvas initialization started.\n"
  7894. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7895. _("Executing FlatCAMScript file.")
  7896. ),
  7897. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7898. color=QtGui.QColor("gray"))
  7899. else:
  7900. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7901. try:
  7902. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  7903. directory=self.get_last_folder(), filter=_filter_)
  7904. except TypeError:
  7905. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  7906. # The Qt methods above will return a QString which can cause problems later.
  7907. # So far json.dump() will fail to serialize it.
  7908. # TODO: Improve the serialization methods and remove this fix.
  7909. filename = str(filename)
  7910. if filename == "":
  7911. if silent is False:
  7912. self.inform.emit('[WARNING_NOTCL] %s' %
  7913. _("Run TCL script cancelled."))
  7914. else:
  7915. if self.cmd_line_headless != 1:
  7916. if self.ui.shell_dock.isHidden():
  7917. self.ui.shell_dock.show()
  7918. try:
  7919. with open(filename, "r") as tcl_script:
  7920. cmd_line_shellfile_content = tcl_script.read()
  7921. if self.cmd_line_headless != 1:
  7922. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  7923. else:
  7924. self.shell._sysShell.exec_command(cmd_line_shellfile_content, no_echo=True)
  7925. if silent is False:
  7926. self.inform.emit('[success] %s' %
  7927. _("TCL script file opened in Code Editor and executed."))
  7928. except Exception as e:
  7929. log.debug("App.on_filerunscript() -> %s" % str(e))
  7930. sys.exit(2)
  7931. def on_file_saveproject(self, silent=False):
  7932. """
  7933. Callback for menu item File->Save Project. Saves the project to
  7934. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7935. if set to None. The project is saved by calling ``self.save_project()``.
  7936. :param silent: if True will not display status messages
  7937. :return: None
  7938. """
  7939. self.report_usage("on_file_saveproject")
  7940. if self.project_filename is None:
  7941. self.on_file_saveprojectas()
  7942. else:
  7943. self.worker_task.emit({'fcn': self.save_project,
  7944. 'params': [self.project_filename, silent]})
  7945. if self.defaults["global_open_style"] is False:
  7946. self.file_opened.emit("project", self.project_filename)
  7947. self.file_saved.emit("project", self.project_filename)
  7948. self.set_ui_title(name=self.project_filename)
  7949. self.should_we_save = False
  7950. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7951. """
  7952. Callback for menu item File->Save Project As... Opens a file
  7953. chooser and saves the project to the given file via
  7954. ``self.save_project()``.
  7955. :param make_copy if to be create a copy of the project; boolean
  7956. :param use_thread: if to be run in a separate thread; boolean
  7957. :param quit_action: if to be followed by quiting the application; boolean
  7958. :return: None
  7959. """
  7960. self.report_usage("on_file_saveprojectas")
  7961. self.date = str(datetime.today()).rpartition('.')[0]
  7962. self.date = ''.join(c for c in self.date if c not in ':-')
  7963. self.date = self.date.replace(' ', '_')
  7964. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  7965. try:
  7966. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7967. caption=_("Save Project As ..."),
  7968. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  7969. filter=filter_)
  7970. except TypeError:
  7971. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  7972. filename = str(filename)
  7973. if filename == '':
  7974. self.inform.emit('[WARNING_NOTCL] %s' %
  7975. _("Save Project cancelled."))
  7976. return
  7977. try:
  7978. f = open(filename, 'r')
  7979. f.close()
  7980. except IOError:
  7981. pass
  7982. if use_thread is True:
  7983. self.worker_task.emit({'fcn': self.save_project,
  7984. 'params': [filename, quit_action]})
  7985. else:
  7986. self.save_project(filename, quit_action)
  7987. # self.save_project(filename)
  7988. if self.defaults["global_open_style"] is False:
  7989. self.file_opened.emit("project", filename)
  7990. self.file_saved.emit("project", filename)
  7991. if not make_copy:
  7992. self.project_filename = filename
  7993. self.set_ui_title(name=self.project_filename)
  7994. self.should_we_save = False
  7995. def export_svg(self, obj_name, filename, scale_factor=0.00):
  7996. """
  7997. Exports a Geometry Object to an SVG file.
  7998. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7999. :param filename: Path to the SVG file to save to.
  8000. :param scale_factor: factor by which to change/scale the thickness of the features
  8001. :return:
  8002. """
  8003. self.report_usage("export_svg()")
  8004. if filename is None:
  8005. filename = self.defaults["global_last_save_folder"]
  8006. self.log.debug("export_svg()")
  8007. try:
  8008. obj = self.collection.get_by_name(str(obj_name))
  8009. except:
  8010. # TODO: The return behavior has not been established... should raise exception?
  8011. return "Could not retrieve object: %s" % obj_name
  8012. with self.proc_container.new(_("Exporting SVG")) as proc:
  8013. exported_svg = obj.export_svg(scale_factor=scale_factor)
  8014. # Determine bounding area for svg export
  8015. bounds = obj.bounds()
  8016. size = obj.size()
  8017. # Convert everything to strings for use in the xml doc
  8018. svgwidth = str(size[0])
  8019. svgheight = str(size[1])
  8020. minx = str(bounds[0])
  8021. miny = str(bounds[1] - size[1])
  8022. uom = obj.units.lower()
  8023. # Add a SVG Header and footer to the svg output from shapely
  8024. # The transform flips the Y Axis so that everything renders
  8025. # properly within svg apps such as inkscape
  8026. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8027. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8028. svg_header += 'width="' + svgwidth + uom + '" '
  8029. svg_header += 'height="' + svgheight + uom + '" '
  8030. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  8031. svg_header += '<g transform="scale(1,-1)">'
  8032. svg_footer = '</g> </svg>'
  8033. svg_elem = svg_header + exported_svg + svg_footer
  8034. # Parse the xml through a xml parser just to add line feeds
  8035. # and to make it look more pretty for the output
  8036. svgcode = parse_xml_string(svg_elem)
  8037. try:
  8038. with open(filename, 'w') as fp:
  8039. fp.write(svgcode.toprettyxml())
  8040. except PermissionError:
  8041. self.inform.emit('[WARNING] %s' %
  8042. _("Permission denied, saving not possible.\n"
  8043. "Most likely another app is holding the file open and not accessible."))
  8044. return 'fail'
  8045. if self.defaults["global_open_style"] is False:
  8046. self.file_opened.emit("SVG", filename)
  8047. self.file_saved.emit("SVG", filename)
  8048. self.inform.emit('[success] %s: %s' %
  8049. (_("SVG file exported to"), filename))
  8050. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  8051. """
  8052. Exports a Geometry Object to an SVG file in negative.
  8053. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8054. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  8055. :param filename: Path to the SVG file to save to.
  8056. :param boundary: thickness of a black border to surround all the features
  8057. :param scale_factor: factor by which to change/scale the thickness of the features
  8058. :param use_thread: if to be run in a separate thread; boolean
  8059. :return:
  8060. """
  8061. self.report_usage("export_negative()")
  8062. if filename is None:
  8063. filename = self.defaults["global_last_save_folder"]
  8064. self.log.debug("export_svg() negative")
  8065. try:
  8066. obj = self.collection.get_by_name(str(obj_name))
  8067. except:
  8068. # TODO: The return behavior has not been established... should raise exception?
  8069. return "Could not retrieve object: %s" % obj_name
  8070. try:
  8071. box = self.collection.get_by_name(str(box_name))
  8072. except:
  8073. # TODO: The return behavior has not been established... should raise exception?
  8074. return "Could not retrieve object: %s" % box_name
  8075. if box is None:
  8076. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  8077. (_("No object Box. Using instead"), obj))
  8078. box = obj
  8079. def make_negative_film():
  8080. exported_svg = obj.export_svg(scale_factor=scale_factor)
  8081. # Determine bounding area for svg export
  8082. bounds = box.bounds()
  8083. size = box.size()
  8084. uom = obj.units.lower()
  8085. # Convert everything to strings for use in the xml doc
  8086. svgwidth = str(size[0] + (2 * boundary))
  8087. svgheight = str(size[1] + (2 * boundary))
  8088. minx = str(bounds[0] - boundary)
  8089. miny = str(bounds[1] + boundary + size[1])
  8090. miny_rect = str(bounds[1] - boundary)
  8091. # Add a SVG Header and footer to the svg output from shapely
  8092. # The transform flips the Y Axis so that everything renders
  8093. # properly within svg apps such as inkscape
  8094. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8095. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8096. svg_header += 'width="' + svgwidth + uom + '" '
  8097. svg_header += 'height="' + svgheight + uom + '" '
  8098. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  8099. svg_header += '>'
  8100. svg_header += '<g transform="scale(1,-1)">'
  8101. svg_footer = '</g> </svg>'
  8102. # Change the attributes of the exported SVG
  8103. # We don't need stroke-width - wrong, we do when we have lines with certain width
  8104. # We set opacity to maximum
  8105. # We set the color to WHITE
  8106. root = ET.fromstring(exported_svg)
  8107. for child in root:
  8108. child.set('fill', '#FFFFFF')
  8109. child.set('opacity', '1.0')
  8110. child.set('stroke', '#FFFFFF')
  8111. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  8112. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  8113. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  8114. first_svg_elem_tag = 'rect'
  8115. first_svg_elem_attribs = {
  8116. 'x': minx,
  8117. 'y': miny_rect,
  8118. 'width': svgwidth,
  8119. 'height': svgheight,
  8120. 'id': 'neg_rect',
  8121. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  8122. }
  8123. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  8124. exported_svg = ET.tostring(root)
  8125. svg_elem = svg_header + str(exported_svg) + svg_footer
  8126. # Parse the xml through a xml parser just to add line feeds
  8127. # and to make it look more pretty for the output
  8128. doc = parse_xml_string(svg_elem)
  8129. try:
  8130. with open(filename, 'w') as fp:
  8131. fp.write(doc.toprettyxml())
  8132. except PermissionError:
  8133. self.inform.emit('[WARNING] %s' %
  8134. _("Permission denied, saving not possible.\n"
  8135. "Most likely another app is holding the file open and not accessible."))
  8136. return 'fail'
  8137. if self.defaults["global_open_style"] is False:
  8138. self.file_opened.emit("SVG", filename)
  8139. self.file_saved.emit("SVG", filename)
  8140. self.inform.emit('[success] %s: %s' %
  8141. (_("SVG file exported to"), filename))
  8142. if use_thread is True:
  8143. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  8144. def job_thread_film(app_obj):
  8145. try:
  8146. make_negative_film()
  8147. except Exception as e:
  8148. proc.done()
  8149. return
  8150. proc.done()
  8151. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  8152. else:
  8153. make_negative_film()
  8154. def export_svg_positive(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  8155. """
  8156. Exports a Geometry Object to an SVG file in positive black.
  8157. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8158. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  8159. :param filename: Path to the SVG file to save to.
  8160. :param scale_factor: factor by which to change/scale the thickness of the features
  8161. :param use_thread: if to be run in a separate thread; boolean
  8162. :return:
  8163. """
  8164. self.report_usage("export_svg_positive()")
  8165. if filename is None:
  8166. filename = self.defaults["global_last_save_folder"]
  8167. self.log.debug("export_svg() black")
  8168. try:
  8169. obj = self.collection.get_by_name(str(obj_name))
  8170. except:
  8171. # TODO: The return behavior has not been established... should raise exception?
  8172. return "Could not retrieve object: %s" % obj_name
  8173. try:
  8174. box = self.collection.get_by_name(str(box_name))
  8175. except:
  8176. # TODO: The return behavior has not been established... should raise exception?
  8177. return "Could not retrieve object: %s" % box_name
  8178. if box is None:
  8179. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  8180. (_("No object Box. Using instead"), obj))
  8181. box = obj
  8182. def make_positive_film():
  8183. exported_svg = obj.export_svg(scale_factor=scale_factor)
  8184. self.progress.emit(40)
  8185. # Change the attributes of the exported SVG
  8186. # We don't need stroke-width
  8187. # We set opacity to maximum
  8188. # We set the colour to WHITE
  8189. root = ET.fromstring(exported_svg)
  8190. for child in root:
  8191. child.set('fill', str(self.defaults['tools_film_color']))
  8192. child.set('opacity', '1.0')
  8193. child.set('stroke', str(self.defaults['tools_film_color']))
  8194. exported_svg = ET.tostring(root)
  8195. # Determine bounding area for svg export
  8196. bounds = box.bounds()
  8197. size = box.size()
  8198. # This contain the measure units
  8199. uom = obj.units.lower()
  8200. # Define a boundary around SVG of about 1.0mm (~39mils)
  8201. if uom in "mm":
  8202. boundary = 1.0
  8203. else:
  8204. boundary = 0.0393701
  8205. self.progress.emit(80)
  8206. # Convert everything to strings for use in the xml doc
  8207. svgwidth = str(size[0] + (2 * boundary))
  8208. svgheight = str(size[1] + (2 * boundary))
  8209. minx = str(bounds[0] - boundary)
  8210. miny = str(bounds[1] + boundary + size[1])
  8211. self.log.debug(minx)
  8212. self.log.debug(miny)
  8213. # Add a SVG Header and footer to the svg output from shapely
  8214. # The transform flips the Y Axis so that everything renders
  8215. # properly within svg apps such as inkscape
  8216. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8217. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8218. svg_header += 'width="' + svgwidth + uom + '" '
  8219. svg_header += 'height="' + svgheight + uom + '" '
  8220. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  8221. svg_header += '>'
  8222. svg_header += '<g transform="scale(1,-1)">'
  8223. svg_footer = '</g> </svg>'
  8224. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  8225. self.progress.emit(90)
  8226. # Parse the xml through a xml parser just to add line feeds
  8227. # and to make it look more pretty for the output
  8228. doc = parse_xml_string(svg_elem)
  8229. try:
  8230. with open(filename, 'w') as fp:
  8231. fp.write(doc.toprettyxml())
  8232. except PermissionError:
  8233. self.inform.emit('[WARNING] %s' %
  8234. _("Permission denied, saving not possible.\n"
  8235. "Most likely another app is holding the file open and not accessible."))
  8236. return 'fail'
  8237. self.progress.emit(100)
  8238. if self.defaults["global_open_style"] is False:
  8239. self.file_opened.emit("SVG", filename)
  8240. self.file_saved.emit("SVG", filename)
  8241. self.inform.emit('[success] %s: %s' %
  8242. (_("SVG file exported to"), filename))
  8243. if use_thread is True:
  8244. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  8245. def job_thread_film(app_obj):
  8246. try:
  8247. make_positive_film()
  8248. except Exception as e:
  8249. proc.done()
  8250. return
  8251. proc.done()
  8252. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  8253. else:
  8254. make_positive_film()
  8255. def save_source_file(self, obj_name, filename, use_thread=True):
  8256. """
  8257. Exports a FlatCAM Object to an Gerber/Excellon file.
  8258. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8259. :param filename: Path to the Gerber file to save to.
  8260. :param use_thread: if to be run in a separate thread
  8261. :return:
  8262. """
  8263. self.report_usage("save source file()")
  8264. if filename is None:
  8265. filename = self.defaults["global_last_save_folder"]
  8266. self.log.debug("save source file()")
  8267. obj = self.collection.get_by_name(obj_name)
  8268. file_string = StringIO(obj.source_file)
  8269. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8270. try:
  8271. with open(filename, 'w') as file:
  8272. file.writelines('G04*\n')
  8273. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8274. (obj.kind.upper(), str(self.version), str(self.version_date)))
  8275. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8276. file.writelines('G04 Created on : %s*\n' % time_string)
  8277. for line in file_string:
  8278. file.writelines(line)
  8279. except PermissionError:
  8280. self.inform.emit('[WARNING] %s' %
  8281. _("Permission denied, saving not possible.\n"
  8282. "Most likely another app is holding the file open and not accessible."))
  8283. return 'fail'
  8284. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  8285. """
  8286. Exports a Excellon Object to an Excellon file.
  8287. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  8288. :param filename: Path to the Excellon file to save to.
  8289. :param use_thread: if to be run in a separate thread
  8290. :return:
  8291. """
  8292. self.report_usage("export_excellon()")
  8293. if filename is None:
  8294. filename = self.defaults["global_last_save_folder"]
  8295. self.log.debug("export_excellon()")
  8296. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  8297. self.defaults["excellon_exp_decimals"]
  8298. )
  8299. if local_use is None:
  8300. try:
  8301. obj = self.collection.get_by_name(str(obj_name))
  8302. except:
  8303. # TODO: The return behavior has not been established... should raise exception?
  8304. return "Could not retrieve object: %s" % obj_name
  8305. else:
  8306. obj = local_use
  8307. # updated units
  8308. eunits = self.defaults["excellon_exp_units"]
  8309. ewhole = self.defaults["excellon_exp_integer"]
  8310. efract = self.defaults["excellon_exp_decimals"]
  8311. ezeros = self.defaults["excellon_exp_zeros"]
  8312. eformat = self.defaults["excellon_exp_format"]
  8313. slot_type = self.defaults["excellon_exp_slot_type"]
  8314. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8315. if fc_units == 'MM':
  8316. factor = 1 if eunits == 'METRIC' else 0.03937
  8317. else:
  8318. factor = 25.4 if eunits == 'METRIC' else 1
  8319. def make_excellon():
  8320. try:
  8321. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8322. header = 'M48\n'
  8323. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  8324. (str(self.version), str(self.version_date))
  8325. header += ';Filename: %s' % str(obj_name) + '\n'
  8326. header += ';Created on : %s' % time_str + '\n'
  8327. if eformat == 'dec':
  8328. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  8329. header += eunits + '\n'
  8330. for tool in obj.tools:
  8331. if eunits == 'METRIC':
  8332. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8333. tool=str(tool),
  8334. dec=2)
  8335. else:
  8336. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8337. tool=str(tool),
  8338. dec=4)
  8339. else:
  8340. if ezeros == 'LZ':
  8341. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8342. form='ndec', e_zeros='LZ', factor=factor,
  8343. slot_type=slot_type)
  8344. header += '%s,%s\n' % (eunits, 'LZ')
  8345. header += format_exc
  8346. for tool in obj.tools:
  8347. if eunits == 'METRIC':
  8348. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8349. tool=str(tool),
  8350. dec=2)
  8351. else:
  8352. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8353. tool=str(tool),
  8354. dec=4)
  8355. else:
  8356. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8357. form='ndec', e_zeros='TZ', factor=factor,
  8358. slot_type=slot_type)
  8359. header += '%s,%s\n' % (eunits, 'TZ')
  8360. header += format_exc
  8361. for tool in obj.tools:
  8362. if eunits == 'METRIC':
  8363. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8364. tool=str(tool),
  8365. dec=2)
  8366. else:
  8367. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8368. tool=str(tool),
  8369. dec=4)
  8370. header += '%\n'
  8371. footer = 'M30\n'
  8372. exported_excellon = header
  8373. exported_excellon += excellon_code
  8374. exported_excellon += footer
  8375. if local_use is None:
  8376. try:
  8377. with open(filename, 'w') as fp:
  8378. fp.write(exported_excellon)
  8379. except PermissionError:
  8380. self.inform.emit('[WARNING] %s' %
  8381. _("Permission denied, saving not possible.\n"
  8382. "Most likely another app is holding the file open and not accessible."))
  8383. return 'fail'
  8384. if self.defaults["global_open_style"] is False:
  8385. self.file_opened.emit("Excellon", filename)
  8386. self.file_saved.emit("Excellon", filename)
  8387. self.inform.emit('[success] %s: %s' %
  8388. (_("Excellon file exported to"), filename))
  8389. else:
  8390. return exported_excellon
  8391. except Exception as e:
  8392. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  8393. return 'fail'
  8394. if use_thread is True:
  8395. with self.proc_container.new(_("Exporting Excellon")) as proc:
  8396. def job_thread_exc(app_obj):
  8397. ret = make_excellon()
  8398. if ret == 'fail':
  8399. self.inform.emit('[ERROR_NOTCL] %s' %
  8400. _('Could not export Excellon file.'))
  8401. return
  8402. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8403. else:
  8404. ret = make_excellon()
  8405. if ret == 'fail':
  8406. self.inform.emit('[ERROR_NOTCL] %s' %
  8407. _('Could not export Excellon file.'))
  8408. return 'fail'
  8409. if local_use is not None:
  8410. return ret
  8411. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  8412. """
  8413. Exports a Gerber Object to an Gerber file.
  8414. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  8415. :param filename: Path to the Gerber file to save to.
  8416. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8417. When not None, the value will be the actual Gerber object for which to create the Gerber code
  8418. :param use_thread: if to be run in a separate thread
  8419. :return:
  8420. """
  8421. self.report_usage("export_gerber()")
  8422. if filename is None:
  8423. filename = self.defaults["global_last_save_folder"]
  8424. self.log.debug("export_gerber()")
  8425. if local_use is None:
  8426. try:
  8427. obj = self.collection.get_by_name(str(obj_name))
  8428. except:
  8429. # TODO: The return behavior has not been established... should raise exception?
  8430. return "Could not retrieve object: %s" % obj_name
  8431. else:
  8432. obj = local_use
  8433. # updated units
  8434. gunits = self.defaults["gerber_exp_units"]
  8435. gwhole = self.defaults["gerber_exp_integer"]
  8436. gfract = self.defaults["gerber_exp_decimals"]
  8437. gzeros = self.defaults["gerber_exp_zeros"]
  8438. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8439. if fc_units == 'MM':
  8440. factor = 1 if gunits == 'MM' else 0.03937
  8441. else:
  8442. factor = 25.4 if gunits == 'MM' else 1
  8443. def make_gerber():
  8444. try:
  8445. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8446. header = 'G04*\n'
  8447. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  8448. (str(self.version), str(self.version_date))
  8449. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  8450. header += 'G04 Created on : %s*' % time_str + '\n'
  8451. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  8452. header += "%MO{units}*%\n".format(units=gunits)
  8453. for apid in obj.apertures:
  8454. if obj.apertures[apid]['type'] == 'C':
  8455. header += "%ADD{apid}{type},{size}*%\n".format(
  8456. apid=str(apid),
  8457. type='C',
  8458. size=(factor * obj.apertures[apid]['size'])
  8459. )
  8460. elif obj.apertures[apid]['type'] == 'R':
  8461. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8462. apid=str(apid),
  8463. type='R',
  8464. width=(factor * obj.apertures[apid]['width']),
  8465. height=(factor * obj.apertures[apid]['height'])
  8466. )
  8467. elif obj.apertures[apid]['type'] == 'O':
  8468. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8469. apid=str(apid),
  8470. type='O',
  8471. width=(factor * obj.apertures[apid]['width']),
  8472. height=(factor * obj.apertures[apid]['height'])
  8473. )
  8474. header += '\n'
  8475. # obsolete units but some software may need it
  8476. if gunits == 'IN':
  8477. header += 'G70*\n'
  8478. else:
  8479. header += 'G71*\n'
  8480. # Absolute Mode
  8481. header += 'G90*\n'
  8482. header += 'G01*\n'
  8483. # positive polarity
  8484. header += '%LPD*%\n'
  8485. footer = 'M02*\n'
  8486. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8487. exported_gerber = header
  8488. exported_gerber += gerber_code
  8489. exported_gerber += footer
  8490. if local_use is None:
  8491. try:
  8492. with open(filename, 'w') as fp:
  8493. fp.write(exported_gerber)
  8494. except PermissionError:
  8495. self.inform.emit('[WARNING] %s' %
  8496. _("Permission denied, saving not possible.\n"
  8497. "Most likely another app is holding the file open and not accessible."))
  8498. return 'fail'
  8499. if self.defaults["global_open_style"] is False:
  8500. self.file_opened.emit("Gerber", filename)
  8501. self.file_saved.emit("Gerber", filename)
  8502. self.inform.emit('[success] %s: %s' %
  8503. (_("Gerber file exported to"), filename))
  8504. else:
  8505. return exported_gerber
  8506. except Exception as e:
  8507. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8508. return 'fail'
  8509. if use_thread is True:
  8510. with self.proc_container.new(_("Exporting Gerber")) as proc:
  8511. def job_thread_grb(app_obj):
  8512. ret = make_gerber()
  8513. if ret == 'fail':
  8514. self.inform.emit('[ERROR_NOTCL] %s' %
  8515. _('Could not export Gerber file.'))
  8516. return
  8517. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8518. else:
  8519. ret = make_gerber()
  8520. if ret == 'fail':
  8521. self.inform.emit('[ERROR_NOTCL] %s' %
  8522. _('Could not export Gerber file.'))
  8523. return 'fail'
  8524. if local_use is not None:
  8525. return ret
  8526. def export_dxf(self, obj_name, filename, use_thread=True):
  8527. """
  8528. Exports a Geometry Object to an DXF file.
  8529. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8530. :param filename: Path to the DXF file to save to.
  8531. :param use_thread: if to be run in a separate thread
  8532. :return:
  8533. """
  8534. self.report_usage("export_dxf()")
  8535. if filename is None:
  8536. filename = self.defaults["global_last_save_folder"]
  8537. self.log.debug("export_dxf()")
  8538. format_exc = ''
  8539. units = ''
  8540. try:
  8541. obj = self.collection.get_by_name(str(obj_name))
  8542. except:
  8543. # TODO: The return behavior has not been established... should raise exception?
  8544. return "Could not retrieve object: %s" % obj_name
  8545. # updated units
  8546. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8547. if units == 'IN' or units == 'INCH':
  8548. units = 'INCH'
  8549. elif units == 'MM' or units == 'METIRC':
  8550. units ='METRIC'
  8551. def make_dxf():
  8552. try:
  8553. dxf_code = obj.export_dxf()
  8554. dxf_code.saveas(filename)
  8555. if self.defaults["global_open_style"] is False:
  8556. self.file_opened.emit("DXF", filename)
  8557. self.file_saved.emit("DXF", filename)
  8558. self.inform.emit('[success] %s: %s' %
  8559. (_("DXF file exported to"), filename))
  8560. except:
  8561. return 'fail'
  8562. if use_thread is True:
  8563. with self.proc_container.new(_("Exporting DXF")) as proc:
  8564. def job_thread_exc(app_obj):
  8565. ret = make_dxf()
  8566. if ret == 'fail':
  8567. app_obj.inform.emit('[WARNING_NOTCL] %s' %
  8568. _('Could not export DXF file.'))
  8569. return
  8570. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8571. else:
  8572. ret = make_dxf()
  8573. if ret == 'fail':
  8574. self.inform.emit('[WARNING_NOTCL] %s' %
  8575. _('Could not export DXF file.'))
  8576. return
  8577. def import_svg(self, filename, geo_type='geometry', outname=None):
  8578. """
  8579. Adds a new Geometry Object to the projects and populates
  8580. it with shapes extracted from the SVG file.
  8581. :param filename: Path to the SVG file.
  8582. :param geo_type: Type of FlatCAM object that will be created from SVG
  8583. :param outname:
  8584. :return:
  8585. """
  8586. self.report_usage("import_svg()")
  8587. obj_type = ""
  8588. if geo_type is None or geo_type == "geometry":
  8589. obj_type = "geometry"
  8590. elif geo_type == "gerber":
  8591. obj_type = geo_type
  8592. else:
  8593. self.inform.emit('[ERROR_NOTCL] %s' %
  8594. _("Not supported type is picked as parameter. "
  8595. "Only Geometry and Gerber are supported"))
  8596. return
  8597. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8598. def obj_init(geo_obj, app_obj):
  8599. geo_obj.import_svg(filename, obj_type, units=units)
  8600. geo_obj.multigeo = False
  8601. with self.proc_container.new(_("Importing SVG")) as proc:
  8602. # Object name
  8603. name = outname or filename.split('/')[-1].split('\\')[-1]
  8604. self.new_object(obj_type, name, obj_init, autoselected=False)
  8605. self.progress.emit(20)
  8606. # Register recent file
  8607. self.file_opened.emit("svg", filename)
  8608. # GUI feedback
  8609. self.inform.emit('[success] %s: %s' %
  8610. (_("Opened"), filename))
  8611. self.progress.emit(100)
  8612. def import_dxf(self, filename, geo_type='geometry', outname=None):
  8613. """
  8614. Adds a new Geometry Object to the projects and populates
  8615. it with shapes extracted from the DXF file.
  8616. :param filename: Path to the DXF file.
  8617. :param geo_type: Type of FlatCAM object that will be created from DXF
  8618. :param outname:
  8619. :type putname: str
  8620. :return:
  8621. """
  8622. self.report_usage("import_dxf()")
  8623. obj_type = ""
  8624. if geo_type is None or geo_type == "geometry":
  8625. obj_type = "geometry"
  8626. elif geo_type == "gerber":
  8627. obj_type = geo_type
  8628. else:
  8629. self.inform.emit('[ERROR_NOTCL] %s' %
  8630. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8631. return
  8632. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8633. def obj_init(geo_obj, app_obj):
  8634. geo_obj.import_dxf(filename, obj_type, units=units)
  8635. geo_obj.multigeo = False
  8636. with self.proc_container.new(_("Importing DXF")) as proc:
  8637. # Object name
  8638. name = outname or filename.split('/')[-1].split('\\')[-1]
  8639. self.new_object(obj_type, name, obj_init, autoselected=False)
  8640. self.progress.emit(20)
  8641. # Register recent file
  8642. self.file_opened.emit("dxf", filename)
  8643. # GUI feedback
  8644. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8645. self.progress.emit(100)
  8646. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  8647. """
  8648. Adds a new Geometry Object to the projects and populates
  8649. it with shapes extracted from the SVG file.
  8650. :param filename: Path to the SVG file.
  8651. :param o_type: type of FlatCAM objeect
  8652. :param dpi: dot per inch
  8653. :param mode: black or color
  8654. :param mask: dictate the level of detail
  8655. :param outname: name for the resulting file
  8656. :return:
  8657. """
  8658. self.report_usage("import_image()")
  8659. if o_type is None or o_type == "geometry":
  8660. obj_type = "geometry"
  8661. elif o_type == "gerber":
  8662. obj_type = o_type
  8663. else:
  8664. self.inform.emit('[ERROR_NOTCL] %s' %
  8665. _("Not supported type is picked as parameter. "
  8666. "Only Geometry and Gerber are supported"))
  8667. return
  8668. def obj_init(geo_obj, app_obj):
  8669. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  8670. geo_obj.multigeo = False
  8671. with self.proc_container.new(_("Importing Image")) as proc:
  8672. # Object name
  8673. name = outname or filename.split('/')[-1].split('\\')[-1]
  8674. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  8675. self.new_object(obj_type, name, obj_init)
  8676. self.progress.emit(20)
  8677. # Register recent file
  8678. self.file_opened.emit("image", filename)
  8679. # GUI feedback
  8680. self.inform.emit('[success] %s: %s' %
  8681. (_("Opened"), filename))
  8682. self.progress.emit(100)
  8683. def open_gerber(self, filename, outname=None):
  8684. """
  8685. Opens a Gerber file, parses it and creates a new object for
  8686. it in the program. Thread-safe.
  8687. :param outname: Name of the resulting object. None causes the
  8688. name to be that of the file.
  8689. :param filename: Gerber file filename
  8690. :type filename: str
  8691. :param follow: If true, the parser will not create polygons, just lines
  8692. following the gerber path.
  8693. :type follow: bool
  8694. :return: None
  8695. """
  8696. # How the object should be initialized
  8697. def obj_init(gerber_obj, app_obj):
  8698. assert isinstance(gerber_obj, FlatCAMGerber), \
  8699. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  8700. # Opening the file happens here
  8701. self.progress.emit(30)
  8702. try:
  8703. gerber_obj.parse_file(filename)
  8704. except IOError:
  8705. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8706. (_("Failed to open file"), filename))
  8707. app_obj.progress.emit(0)
  8708. return "fail"
  8709. except ParseError as err:
  8710. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' %
  8711. (_("Failed to parse file"), filename, str(err)))
  8712. app_obj.progress.emit(0)
  8713. self.log.error(str(err))
  8714. return "fail"
  8715. except Exception as e:
  8716. log.debug("App.open_gerber() --> %s" % str(e))
  8717. msg = '[ERROR] %s' % \
  8718. _("An internal error has occurred. See shell.\n")
  8719. msg += traceback.format_exc()
  8720. app_obj.inform.emit(msg)
  8721. return "fail"
  8722. if gerber_obj.is_empty():
  8723. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  8724. # self.collection.set_active(gerber_obj.options["name"])
  8725. # self.collection.delete_active()
  8726. self.inform.emit('[ERROR_NOTCL] %s' %
  8727. _("Object is not Gerber file or empty. Aborting object creation."))
  8728. return "fail"
  8729. # Further parsing
  8730. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  8731. App.log.debug("open_gerber()")
  8732. with self.proc_container.new(_("Opening Gerber")) as proc:
  8733. self.progress.emit(10)
  8734. # Object name
  8735. name = outname or filename.split('/')[-1].split('\\')[-1]
  8736. # # ## Object creation # ##
  8737. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  8738. if ret == 'fail':
  8739. self.inform.emit('[ERROR_NOTCL]%s' %
  8740. _(' Open Gerber failed. Probable not a Gerber file.'))
  8741. return
  8742. # Register recent file
  8743. self.file_opened.emit("gerber", filename)
  8744. self.progress.emit(100)
  8745. # GUI feedback
  8746. self.inform.emit('[success] %s: %s' %
  8747. (_("Opened"), filename))
  8748. def open_excellon(self, filename, outname=None, plot=True):
  8749. """
  8750. Opens an Excellon file, parses it and creates a new object for
  8751. it in the program. Thread-safe.
  8752. :param outname: Name of the resulting object. None causes the
  8753. name to be that of the file.
  8754. :param filename: Excellon file filename
  8755. :type filename: str
  8756. :return: None
  8757. """
  8758. App.log.debug("open_excellon()")
  8759. # How the object should be initialized
  8760. def obj_init(excellon_obj, app_obj):
  8761. # self.progress.emit(20)
  8762. try:
  8763. ret = excellon_obj.parse_file(filename=filename)
  8764. if ret == "fail":
  8765. log.debug("Excellon parsing failed.")
  8766. self.inform.emit('[ERROR_NOTCL] %s' %
  8767. _("This is not Excellon file."))
  8768. return "fail"
  8769. except IOError:
  8770. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8771. (_("Cannot open file"), filename))
  8772. log.debug("Could not open Excellon object.")
  8773. self.progress.emit(0) # TODO: self and app_bjj mixed
  8774. return "fail"
  8775. except:
  8776. msg = '[ERROR_NOTCL] %s' % \
  8777. _("An internal error has occurred. See shell.\n")
  8778. msg += traceback.format_exc()
  8779. app_obj.inform.emit(msg)
  8780. return "fail"
  8781. ret = excellon_obj.create_geometry()
  8782. if ret == 'fail':
  8783. log.debug("Could not create geometry for Excellon object.")
  8784. return "fail"
  8785. for tool in excellon_obj.tools:
  8786. if excellon_obj.tools[tool]['solid_geometry']:
  8787. return
  8788. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8789. (_("No geometry found in file"), filename))
  8790. return "fail"
  8791. with self.proc_container.new(_("Opening Excellon.")):
  8792. # Object name
  8793. name = outname or filename.split('/')[-1].split('\\')[-1]
  8794. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8795. if ret_val == 'fail':
  8796. self.inform.emit('[ERROR_NOTCL] %s' %
  8797. _('Open Excellon file failed. Probable not an Excellon file.'))
  8798. return
  8799. # Register recent file
  8800. self.file_opened.emit("excellon", filename)
  8801. # GUI feedback
  8802. self.inform.emit('[success] %s: %s' %
  8803. (_("Opened"), filename))
  8804. def open_gcode(self, filename, outname=None, plot=True):
  8805. """
  8806. Opens a G-gcode file, parses it and creates a new object for
  8807. it in the program. Thread-safe.
  8808. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8809. :param filename: G-code file filename
  8810. :type filename: str
  8811. :return: None
  8812. """
  8813. App.log.debug("open_gcode()")
  8814. # How the object should be initialized
  8815. def obj_init(job_obj, app_obj_):
  8816. """
  8817. :param job_obj: the resulting object
  8818. :type app_obj_: App
  8819. """
  8820. assert isinstance(app_obj_, App), \
  8821. "Initializer expected App, got %s" % type(app_obj_)
  8822. try:
  8823. f = open(filename)
  8824. gcode = f.read()
  8825. f.close()
  8826. except IOError:
  8827. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  8828. (_("Failed to open"), filename))
  8829. return "fail"
  8830. job_obj.gcode = gcode
  8831. ret = job_obj.gcode_parse()
  8832. if ret == "fail":
  8833. self.inform.emit('[ERROR_NOTCL] %s' %
  8834. _("This is not GCODE"))
  8835. return "fail"
  8836. job_obj.create_geometry()
  8837. with self.proc_container.new(_("Opening G-Code.")):
  8838. # Object name
  8839. name = outname or filename.split('/')[-1].split('\\')[-1]
  8840. # New object creation and file processing
  8841. ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8842. if ret == 'fail':
  8843. self.inform.emit('[ERROR_NOTCL] %s' %
  8844. _("Failed to create CNCJob Object. Probable not a GCode file.\n "
  8845. "Attempting to create a FlatCAM CNCJob Object from "
  8846. "G-Code file failed during processing"))
  8847. return "fail"
  8848. # Register recent file
  8849. self.file_opened.emit("cncjob", filename)
  8850. # GUI feedback
  8851. self.inform.emit('[success] %s: %s' %
  8852. (_("Opened"), filename))
  8853. def open_script(self, filename, outname=None, silent=False):
  8854. """
  8855. Opens a Script file, parses it and creates a new object for
  8856. it in the program. Thread-safe.
  8857. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8858. :param filename: Script file filename
  8859. :type filename: str
  8860. :return: None
  8861. """
  8862. App.log.debug("open_script()")
  8863. with self.proc_container.new(_("Opening TCL Script...")):
  8864. try:
  8865. with open(filename, "r") as opened_script:
  8866. script_content = opened_script.readlines()
  8867. script_content = ''.join(script_content)
  8868. if silent is False:
  8869. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  8870. except Exception as e:
  8871. log.debug("App.open_script() -> %s" % str(e))
  8872. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to open TCL Script."))
  8873. return
  8874. # Object name
  8875. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  8876. # New object creation and file processing
  8877. self.on_filenewscript(name=script_name, text=script_content)
  8878. # Register recent file
  8879. self.file_opened.emit("script", filename)
  8880. # GUI feedback
  8881. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8882. def open_config_file(self, filename, run_from_arg=None):
  8883. """
  8884. Loads a config file from the specified file.
  8885. :param filename: Name of the file from which to load.
  8886. :type filename: str
  8887. :return: None
  8888. """
  8889. App.log.debug("Opening config file: " + filename)
  8890. if run_from_arg:
  8891. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8892. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8893. _("Opening FlatCAM Config file.")),
  8894. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8895. color=QtGui.QColor("gray"))
  8896. # add the tab if it was closed
  8897. self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  8898. # first clear previous text in text editor (if any)
  8899. self.ui.text_editor_tab.code_editor.clear()
  8900. # Switch plot_area to CNCJob tab
  8901. self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  8902. try:
  8903. if filename:
  8904. f = QtCore.QFile(filename)
  8905. if f.open(QtCore.QIODevice.ReadOnly):
  8906. stream = QtCore.QTextStream(f)
  8907. gcode_edited = stream.readAll()
  8908. self.ui.text_editor_tab.code_editor.setPlainText(gcode_edited)
  8909. f.close()
  8910. except IOError:
  8911. App.log.error("Failed to open config file: %s" % filename)
  8912. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8913. (_("Failed to open config file"), filename))
  8914. return
  8915. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  8916. """
  8917. Loads a project from the specified file.
  8918. 1) Loads and parses file
  8919. 2) Registers the file as recently opened.
  8920. 3) Calls on_file_new()
  8921. 4) Updates options
  8922. 5) Calls new_object() with the object's from_dict() as init method.
  8923. 6) Calls plot_all() if plot=True
  8924. :param filename: Name of the file from which to load.
  8925. :type filename: str
  8926. :param run_from_arg: True if run for arguments
  8927. :param plot: If True plot all objects in the project
  8928. :param cli: run from command line
  8929. :return: None
  8930. """
  8931. App.log.debug("Opening project: " + filename)
  8932. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8933. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8934. if cli is None:
  8935. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8936. if run_from_arg:
  8937. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8938. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8939. _("Opening FlatCAM Project file.")),
  8940. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8941. color=QtGui.QColor("gray"))
  8942. # Open and parse an uncompressed Project file
  8943. try:
  8944. f = open(filename, 'r')
  8945. except IOError:
  8946. App.log.error("Failed to open project file: %s" % filename)
  8947. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8948. (_("Failed to open project file"), filename))
  8949. return
  8950. try:
  8951. d = json.load(f, object_hook=dict2obj)
  8952. except Exception as e:
  8953. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8954. (filename, str(e)))
  8955. f.close()
  8956. # Open and parse a compressed Project file
  8957. try:
  8958. with lzma.open(filename) as f:
  8959. file_content = f.read().decode('utf-8')
  8960. d = json.loads(file_content, object_hook=dict2obj)
  8961. except Exception as e:
  8962. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8963. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8964. (_("Failed to open project file"), filename))
  8965. return
  8966. # Clear the current project
  8967. # # NOT THREAD SAFE # ##
  8968. if run_from_arg is True:
  8969. pass
  8970. elif cli is True:
  8971. self.delete_selection_shape()
  8972. else:
  8973. self.on_file_new()
  8974. # Project options
  8975. self.options.update(d['options'])
  8976. self.project_filename = filename
  8977. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8978. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8979. if cli is None:
  8980. self.set_screen_units(self.options["units"])
  8981. # Re create objects
  8982. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8983. for obj in d['objs']:
  8984. def obj_init(obj_inst, app_inst):
  8985. obj_inst.from_dict(obj)
  8986. App.log.debug("Recreating from opened project an %s object: %s" %
  8987. (obj['kind'].capitalize(), obj['options']['name']))
  8988. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8989. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8990. if cli is None:
  8991. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8992. obj['kind'].upper(),
  8993. obj['options']['name']
  8994. )
  8995. )
  8996. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  8997. self.inform.emit('[success] %s: %s' %
  8998. (_("Project loaded from"), filename))
  8999. self.should_we_save = False
  9000. self.file_opened.emit("project", filename)
  9001. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9002. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9003. if cli is None:
  9004. self.set_ui_title(name=self.project_filename)
  9005. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  9006. def propagate_defaults(self, silent=False):
  9007. """
  9008. This method is used to set default values in classes. It's
  9009. an alternative to project options but allows the use
  9010. of values invisible to the user.
  9011. :return: None
  9012. """
  9013. if silent is False:
  9014. self.log.debug("propagate_defaults()")
  9015. # Which objects to update the given parameters.
  9016. routes = {
  9017. "global_zdownrate": CNCjob,
  9018. "excellon_zeros": Excellon,
  9019. "excellon_format_upper_in": Excellon,
  9020. "excellon_format_lower_in": Excellon,
  9021. "excellon_format_upper_mm": Excellon,
  9022. "excellon_format_lower_mm": Excellon,
  9023. "excellon_units": Excellon,
  9024. "gerber_use_buffer_for_union": Gerber,
  9025. "geometry_multidepth": Geometry
  9026. }
  9027. for param in routes:
  9028. if param in routes[param].defaults:
  9029. try:
  9030. routes[param].defaults[param] = self.defaults[param]
  9031. if silent is False:
  9032. self.log.debug(" " + param + " OK")
  9033. except KeyError:
  9034. if silent is False:
  9035. self.log.debug(" ERROR: " + param + " not in defaults.")
  9036. else:
  9037. # Try extracting the name:
  9038. # classname_param here is param in the object
  9039. if param.find(routes[param].__name__.lower() + "_") == 0:
  9040. p = param[len(routes[param].__name__) + 1:]
  9041. if p in routes[param].defaults:
  9042. routes[param].defaults[p] = self.defaults[param]
  9043. if silent is False:
  9044. self.log.debug(" " + param + " OK!")
  9045. def plot_all(self, zoom=True):
  9046. """
  9047. Re-generates all plots from all objects.
  9048. :return: None
  9049. """
  9050. self.log.debug("Plot_all()")
  9051. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  9052. for obj in self.collection.get_list():
  9053. def worker_task(obj):
  9054. with self.proc_container.new("Plotting"):
  9055. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  9056. if zoom:
  9057. self.object_plotted.emit(obj)
  9058. # Send to worker
  9059. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  9060. def register_folder(self, filename):
  9061. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  9062. def register_save_folder(self, filename):
  9063. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  9064. def set_progress_bar(self, percentage, text=""):
  9065. self.ui.progress_bar.setValue(int(percentage))
  9066. def setup_shell(self):
  9067. """
  9068. Creates shell functions. Runs once at startup.
  9069. :return: None
  9070. """
  9071. self.log.debug("setup_shell()")
  9072. def shelp(p=None):
  9073. if not p:
  9074. return _("Available commands:\n") + \
  9075. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  9076. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  9077. if p not in commands:
  9078. return "Unknown command: %s" % p
  9079. return commands[p]["help"]
  9080. # --- Migrated to new architecture ---
  9081. # def options(name):
  9082. # ops = self.collection.get_by_name(str(name)).options
  9083. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  9084. def h(*args):
  9085. """
  9086. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  9087. and standalone parameters into list.
  9088. """
  9089. kwa = {}
  9090. a = []
  9091. n = len(args)
  9092. name = None
  9093. for i in range(n):
  9094. match = re.search(r'^-([a-zA-Z].*)', args[i])
  9095. if match:
  9096. assert name is None
  9097. name = match.group(1)
  9098. continue
  9099. if name is None:
  9100. a.append(args[i])
  9101. else:
  9102. kwa[name] = args[i]
  9103. name = None
  9104. return a, kwa
  9105. @contextmanager
  9106. def wait_signal(signal, timeout=10000):
  9107. """
  9108. Block loop until signal emitted, timeout (ms) elapses
  9109. or unhandled exception happens in a thread.
  9110. :param timeout: time after which the loop is exited
  9111. :param signal: Signal to wait for.
  9112. """
  9113. loop = QtCore.QEventLoop()
  9114. # Normal termination
  9115. signal.connect(loop.quit)
  9116. # Termination by exception in thread
  9117. self.thread_exception.connect(loop.quit)
  9118. status = {'timed_out': False}
  9119. def report_quit():
  9120. status['timed_out'] = True
  9121. loop.quit()
  9122. yield
  9123. # Temporarily change how exceptions are managed.
  9124. oeh = sys.excepthook
  9125. ex = []
  9126. def except_hook(type_, value, traceback_):
  9127. ex.append(value)
  9128. oeh(type_, value, traceback_)
  9129. sys.excepthook = except_hook
  9130. # Terminate on timeout
  9131. if timeout is not None:
  9132. QtCore.QTimer.singleShot(timeout, report_quit)
  9133. # # ## Block ## ##
  9134. loop.exec_()
  9135. # Restore exception management
  9136. sys.excepthook = oeh
  9137. if ex:
  9138. self.raiseTclError(str(ex[0]))
  9139. if status['timed_out']:
  9140. raise Exception('Timed out!')
  9141. def make_docs():
  9142. output = ''
  9143. import collections
  9144. od = collections.OrderedDict(sorted(commands.items()))
  9145. for cmd_, val in od.items():
  9146. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  9147. t = val['help']
  9148. usage_i = t.find('>')
  9149. if usage_i < 0:
  9150. expl = t
  9151. output += expl + '\n\n'
  9152. continue
  9153. expl = t[:usage_i - 1]
  9154. output += expl + '\n\n'
  9155. end_usage_i = t[usage_i:].find('\n')
  9156. if end_usage_i < 0:
  9157. end_usage_i = len(t[usage_i:])
  9158. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  9159. else:
  9160. extras = t[usage_i+end_usage_i+1:]
  9161. parts = [s.strip() for s in extras.split('\n')]
  9162. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  9163. for p in parts:
  9164. output += ' ' + p + '\n\n'
  9165. return output
  9166. '''
  9167. Howto implement TCL shell commands:
  9168. All parameters passed to command should be possible to set as None and test it afterwards.
  9169. This is because we need to see error caused in tcl,
  9170. if None value as default parameter is not allowed TCL will return empty error.
  9171. Use:
  9172. def mycommand(name=None,...):
  9173. Test it like this:
  9174. if name is None:
  9175. self.raise_tcl_error('Argument name is missing.')
  9176. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  9177. otherwise we will miss it and processing will silently continue.
  9178. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  9179. which is catched in exec_command and displayed in TCL shell console with red background.
  9180. Error in console is displayed with TCL trace.
  9181. This behavior works only within main thread,
  9182. errors with promissed tasks can be catched and detected only with log.
  9183. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  9184. TCL shell.
  9185. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  9186. '''
  9187. commands = {
  9188. 'help': {
  9189. 'fcn': shelp,
  9190. 'help': _("Shows list of commands.")
  9191. },
  9192. }
  9193. # Import/overwrite tcl commands as objects of TclCommand descendants
  9194. # This modifies the variable 'commands'.
  9195. tclCommands.register_all_commands(self, commands)
  9196. # Add commands to the tcl interpreter
  9197. for cmd in commands:
  9198. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  9199. # Make the tcl puts function return instead of print to stdout
  9200. self.tcl.eval('''
  9201. rename puts original_puts
  9202. proc puts {args} {
  9203. if {[llength $args] == 1} {
  9204. return "[lindex $args 0]"
  9205. } else {
  9206. eval original_puts $args
  9207. }
  9208. }
  9209. ''')
  9210. def setup_recent_items(self):
  9211. # TODO: Move this to constructor
  9212. icons = {
  9213. "gerber": "share/flatcam_icon16.png",
  9214. "excellon": "share/drill16.png",
  9215. 'geometry': "share/geometry16.png",
  9216. "cncjob": "share/cnc16.png",
  9217. "script": "share/script_new24.png",
  9218. "document": "share/notes16_1.png",
  9219. "project": "share/project16.png",
  9220. "svg": "share/geometry16.png",
  9221. "dxf": "share/dxf16.png",
  9222. "pdf": "share/pdf32.png",
  9223. "image": "share/image16.png"
  9224. }
  9225. openers = {
  9226. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  9227. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  9228. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  9229. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  9230. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  9231. "document": None,
  9232. 'project': self.open_project,
  9233. 'svg': self.import_svg,
  9234. 'dxf': self.import_dxf,
  9235. 'image': self.import_image,
  9236. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  9237. }
  9238. # Open recent file for files
  9239. try:
  9240. f = open(self.data_path + '/recent.json')
  9241. except IOError:
  9242. App.log.error("Failed to load recent item list.")
  9243. self.inform.emit('[ERROR_NOTCL] %s' %
  9244. _("Failed to load recent item list."))
  9245. return
  9246. try:
  9247. self.recent = json.load(f)
  9248. except json.scanner.JSONDecodeError:
  9249. App.log.error("Failed to parse recent item list.")
  9250. self.inform.emit('[ERROR_NOTCL] %s' %
  9251. _("Failed to parse recent item list."))
  9252. f.close()
  9253. return
  9254. f.close()
  9255. # Open recent file for projects
  9256. try:
  9257. fp = open(self.data_path + '/recent_projects.json')
  9258. except IOError:
  9259. App.log.error("Failed to load recent project item list.")
  9260. self.inform.emit('[ERROR_NOTCL] %s' %
  9261. _("Failed to load recent projects item list."))
  9262. return
  9263. try:
  9264. self.recent_projects = json.load(fp)
  9265. except json.scanner.JSONDecodeError:
  9266. App.log.error("Failed to parse recent project item list.")
  9267. self.inform.emit('[ERROR_NOTCL] %s' %
  9268. _("Failed to parse recent project item list."))
  9269. fp.close()
  9270. return
  9271. fp.close()
  9272. # Closure needed to create callbacks in a loop.
  9273. # Otherwise late binding occurs.
  9274. def make_callback(func, fname):
  9275. def opener():
  9276. func(fname)
  9277. return opener
  9278. def reset_recent_files():
  9279. # Reset menu
  9280. self.ui.recent.clear()
  9281. self.recent = []
  9282. try:
  9283. f = open(self.data_path + '/recent.json', 'w')
  9284. except IOError:
  9285. App.log.error("Failed to open recent items file for writing.")
  9286. return
  9287. json.dump(self.recent, f)
  9288. def reset_recent_projects():
  9289. # Reset menu
  9290. self.ui.recent_projects.clear()
  9291. self.recent_projects = []
  9292. try:
  9293. fp = open(self.data_path + '/recent_projects.json', 'w')
  9294. except IOError:
  9295. App.log.error("Failed to open recent projects items file for writing.")
  9296. return
  9297. json.dump(self.recent, fp)
  9298. # Reset menu
  9299. self.ui.recent.clear()
  9300. self.ui.recent_projects.clear()
  9301. # Create menu items for projects
  9302. for recent in self.recent_projects:
  9303. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9304. if recent['kind'] == 'project':
  9305. try:
  9306. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9307. # Attach callback
  9308. o = make_callback(openers[recent["kind"]], recent['filename'])
  9309. action.triggered.connect(o)
  9310. self.ui.recent_projects.addAction(action)
  9311. except KeyError:
  9312. App.log.error("Unsupported file type: %s" % recent["kind"])
  9313. # Last action in Recent Files menu is one that Clear the content
  9314. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  9315. clear_action_proj.triggered.connect(reset_recent_projects)
  9316. self.ui.recent_projects.addSeparator()
  9317. self.ui.recent_projects.addAction(clear_action_proj)
  9318. # Create menu items for files
  9319. for recent in self.recent:
  9320. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9321. if recent['kind'] != 'project':
  9322. try:
  9323. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9324. # Attach callback
  9325. o = make_callback(openers[recent["kind"]], recent['filename'])
  9326. action.triggered.connect(o)
  9327. self.ui.recent.addAction(action)
  9328. except KeyError:
  9329. App.log.error("Unsupported file type: %s" % recent["kind"])
  9330. # Last action in Recent Files menu is one that Clear the content
  9331. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  9332. clear_action.triggered.connect(reset_recent_files)
  9333. self.ui.recent.addSeparator()
  9334. self.ui.recent.addAction(clear_action)
  9335. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  9336. # self.ui.menufilerecent.set_submenu(recent_menu)
  9337. # recent_menu.show_all()
  9338. # self.ui.recent.show()
  9339. self.log.debug("Recent items list has been populated.")
  9340. def setup_component_editor(self):
  9341. # label = QtWidgets.QLabel("Choose an item from Project")
  9342. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  9343. sel_title = QtWidgets.QTextEdit(
  9344. _('<b>Shortcut Key List</b>'))
  9345. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  9346. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  9347. settings = QSettings("Open Source", "FlatCAM")
  9348. if settings.contains("notebook_font_size"):
  9349. fsize = settings.value('notebook_font_size', type=int)
  9350. else:
  9351. fsize = 12
  9352. tsize = fsize + int(fsize / 2)
  9353. # selected_text = (_('''
  9354. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  9355. #
  9356. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  9357. # The normal flow when working in FlatCAM is the following:</span></p>
  9358. #
  9359. # <ol>
  9360. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  9361. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  9362. # even dragging and dropping the files on the GUI.<br />
  9363. # <br />
  9364. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  9365. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  9366. # &nbsp;</li>
  9367. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  9368. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  9369. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  9370. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  9371. # <br />
  9372. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  9373. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  9374. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  9375. # it even if it was out of focus.<br />
  9376. # <br />
  9377. # You can change the parameters in this screen and the flow direction is like this:<br />
  9378. # <br />
  9379. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  9380. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  9381. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  9382. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  9383. # </ol>
  9384. #
  9385. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  9386. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  9387. # <strong>F3</strong>.</span></p>
  9388. #
  9389. # ''').format(fsize=fsize, tsize=tsize))
  9390. selected_text = '''
  9391. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  9392. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  9393. {s1}</span></p>
  9394. <ol>
  9395. <li><span style="font-size:{fsize}px">{s2}<br />
  9396. <br />
  9397. {s3}</span><br />
  9398. &nbsp;</li>
  9399. <li><span style="font-size:{fsize}px">{s4}<br />
  9400. &nbsp;</li>
  9401. <br />
  9402. <li><span style="font-size:{fsize}px">{s5}<br />
  9403. &nbsp;</li>
  9404. <br />
  9405. <li><span style="font-size:{fsize}px">{s6}<br />
  9406. <br />
  9407. {s7}</span></li>
  9408. </ol>
  9409. <p><span style="font-size:{fsize}px">{s8}</span></p>
  9410. '''.format(
  9411. title=_("Selected Tab - Choose an Item from Project Tab"),
  9412. subtitle=_("Details"),
  9413. s1=_("The normal flow when working in FlatCAM is the following:"),
  9414. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  9415. "using either the toolbars, key shortcuts or even dragging and dropping the "
  9416. "files on the GUI."),
  9417. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  9418. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  9419. "actions offered within the app."),
  9420. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  9421. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  9422. "SELECTED TAB will be updated with the object properties according to its kind: "
  9423. "Gerber, Excellon, Geometry or CNCJob object."),
  9424. s5=_("If the selection of the object is done on the canvas by single click instead, "
  9425. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  9426. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  9427. "the SELECTED TAB and populate it even if it was out of focus."),
  9428. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  9429. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  9430. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  9431. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  9432. "(again, done in SELECTED TAB) --> Save GCode."),
  9433. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  9434. "or through its own key shortcut: <b>F3</b>."),
  9435. tsize=tsize,
  9436. fsize=fsize
  9437. )
  9438. sel_title.setText(selected_text)
  9439. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  9440. self.ui.selected_scroll_area.setWidget(sel_title)
  9441. def setup_obj_classes(self):
  9442. """
  9443. Sets up application specifics on the FlatCAMObj class.
  9444. :return: None
  9445. """
  9446. FlatCAMObj.app = self
  9447. ObjectCollection.app = self
  9448. Gerber.app = self
  9449. Excellon.app = self
  9450. Geometry.app = self
  9451. CNCjob.app = self
  9452. FCProcess.app = self
  9453. FCProcessContainer.app = self
  9454. def version_check(self):
  9455. """
  9456. Checks for the latest version of the program. Alerts the
  9457. user if theirs is outdated. This method is meant to be run
  9458. in a separate thread.
  9459. :return: None
  9460. """
  9461. self.log.debug("version_check()")
  9462. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  9463. full_url = App.version_url + \
  9464. "?s=" + str(self.defaults['global_serial']) + \
  9465. "&v=" + str(self.version) + \
  9466. "&os=" + str(self.os) + \
  9467. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  9468. else:
  9469. # no_stats dict; just so it won't break things on website
  9470. no_ststs_dict = {}
  9471. no_ststs_dict["global_ststs"] = {}
  9472. full_url = App.version_url + \
  9473. "?s=" + str(self.defaults['global_serial']) + \
  9474. "&v=" + str(self.version) + \
  9475. "&os=" + str(self.os) + \
  9476. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  9477. App.log.debug("Checking for updates @ %s" % full_url)
  9478. # ## Get the data
  9479. try:
  9480. f = urllib.request.urlopen(full_url)
  9481. except:
  9482. # App.log.warning("Failed checking for latest version. Could not connect.")
  9483. self.log.warning("Failed checking for latest version. Could not connect.")
  9484. self.inform.emit('[WARNING_NOTCL] %s' %
  9485. _("Failed checking for latest version. Could not connect."))
  9486. return
  9487. try:
  9488. data = json.load(f)
  9489. except Exception as e:
  9490. App.log.error("Could not parse information about latest version.")
  9491. self.inform.emit('[ERROR_NOTCL] %s' %
  9492. _("Could not parse information about latest version."))
  9493. App.log.debug("json.load(): %s" % str(e))
  9494. f.close()
  9495. return
  9496. f.close()
  9497. # ## Latest version?
  9498. if self.version >= data["version"]:
  9499. App.log.debug("FlatCAM is up to date!")
  9500. self.inform.emit('[success] %s' %
  9501. _("FlatCAM is up to date!"))
  9502. return
  9503. App.log.debug("Newer version available.")
  9504. self.message.emit(
  9505. _("Newer Version Available"),
  9506. _("There is a newer version of FlatCAM available for download:\n\n") +
  9507. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  9508. _("info")
  9509. )
  9510. def on_plotcanvas_setup(self, container=None):
  9511. """
  9512. This is doing the setup for the plot area (VisPy canvas)
  9513. :param container: widget where to install the canvas
  9514. :return: None
  9515. """
  9516. if container:
  9517. plot_container = container
  9518. else:
  9519. plot_container = self.ui.right_layout
  9520. if self.is_legacy is False:
  9521. self.plotcanvas = PlotCanvas(plot_container, self)
  9522. else:
  9523. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  9524. # So it can receive key presses
  9525. self.plotcanvas.native.setFocus()
  9526. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  9527. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  9528. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  9529. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_double_click_over_plot)
  9530. # Keys over plot enabled
  9531. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  9532. if self.defaults['global_cursor_type'] == 'small':
  9533. self.app_cursor = self.plotcanvas.new_cursor()
  9534. else:
  9535. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  9536. if self.ui.grid_snap_btn.isChecked():
  9537. self.app_cursor.enabled = True
  9538. else:
  9539. self.app_cursor.enabled = False
  9540. if self.is_legacy is False:
  9541. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  9542. else:
  9543. # will use the default Matplotlib axes
  9544. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  9545. def on_zoom_fit(self, event):
  9546. """
  9547. Callback for zoom-out request. This can be either from the corresponding
  9548. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  9549. with axes limits from the geometry bounds of all objects.
  9550. :param event: Ignored.
  9551. :return: None
  9552. """
  9553. if self.is_legacy is False:
  9554. self.plotcanvas.fit_view()
  9555. else:
  9556. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  9557. width = xmax - xmin
  9558. height = ymax - ymin
  9559. xmin -= 0.05 * width
  9560. xmax += 0.05 * width
  9561. ymin -= 0.05 * height
  9562. ymax += 0.05 * height
  9563. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  9564. def on_zoom_in(self):
  9565. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  9566. def on_zoom_out(self):
  9567. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  9568. def disable_all_plots(self):
  9569. self.report_usage("disable_all_plots()")
  9570. self.disable_plots(self.collection.get_list())
  9571. self.inform.emit('[success] %s' %
  9572. _("All plots disabled."))
  9573. def disable_other_plots(self):
  9574. self.report_usage("disable_other_plots()")
  9575. self.disable_plots(self.collection.get_non_selected())
  9576. self.inform.emit('[success] %s' %
  9577. _("All non selected plots disabled."))
  9578. def enable_all_plots(self):
  9579. self.report_usage("enable_all_plots()")
  9580. self.enable_plots(self.collection.get_list())
  9581. self.inform.emit('[success] %s' %
  9582. _("All plots enabled."))
  9583. def on_enable_sel_plots(self):
  9584. log.debug("App.on_enable_sel_plot()")
  9585. object_list = self.collection.get_selected()
  9586. self.enable_plots(objects=object_list)
  9587. self.inform.emit('[success] %s' %
  9588. _("Selected plots enabled..."))
  9589. def on_disable_sel_plots(self):
  9590. log.debug("App.on_disable_sel_plot()")
  9591. # self.inform.emit(_("Disabling plots ..."))
  9592. object_list = self.collection.get_selected()
  9593. self.disable_plots(objects=object_list)
  9594. self.inform.emit('[success] %s' %
  9595. _("Selected plots disabled..."))
  9596. def enable_plots(self, objects):
  9597. """
  9598. Disables plots
  9599. :param objects: list of Objects to be enabled
  9600. :return:
  9601. """
  9602. log.debug("Enabling plots ...")
  9603. # self.inform.emit(_("Working ..."))
  9604. for obj in objects:
  9605. if obj.options['plot'] is False:
  9606. obj.options.set_change_callback(lambda x: None)
  9607. obj.options['plot'] = True
  9608. obj.options.set_change_callback(obj.on_options_change)
  9609. def worker_task(objects):
  9610. with self.proc_container.new(_("Enabling plots ...")):
  9611. for obj in objects:
  9612. # obj.options['plot'] = True
  9613. if isinstance(obj, FlatCAMCNCjob):
  9614. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  9615. else:
  9616. obj.plot(visible=True)
  9617. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9618. # self.plots_updated.emit()
  9619. def disable_plots(self, objects):
  9620. """
  9621. Disables plots
  9622. :param objects: list of Objects to be disabled
  9623. :return:
  9624. """
  9625. # if no objects selected then do nothing
  9626. if not self.collection.get_selected():
  9627. return
  9628. log.debug("Disabling plots ...")
  9629. # self.inform.emit(_("Working ..."))
  9630. for obj in objects:
  9631. if obj.options['plot'] is True:
  9632. obj.options.set_change_callback(lambda x: None)
  9633. obj.options['plot'] = False
  9634. obj.options.set_change_callback(obj.on_options_change)
  9635. try:
  9636. self.delete_selection_shape()
  9637. except Exception as e:
  9638. log.debug("App.disable_plots() --> %s" % str(e))
  9639. # self.plots_updated.emit()
  9640. def worker_task(objects):
  9641. with self.proc_container.new(_("Disabling plots ...")):
  9642. for obj in objects:
  9643. # obj.options['plot'] = True
  9644. if isinstance(obj, FlatCAMCNCjob):
  9645. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  9646. else:
  9647. obj.plot(visible=False)
  9648. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9649. def toggle_plots(self, objects):
  9650. """
  9651. Toggle plots visibility
  9652. :param objects: list of Objects for which to be toggled the visibility
  9653. :return:
  9654. """
  9655. # if no objects selected then do nothing
  9656. if not self.collection.get_selected():
  9657. return
  9658. log.debug("Toggling plots ...")
  9659. self.inform.emit(_("Working ..."))
  9660. for obj in objects:
  9661. if obj.options['plot'] is False:
  9662. obj.options['plot'] = True
  9663. else:
  9664. obj.options['plot'] = False
  9665. self.plots_updated.emit()
  9666. def clear_plots(self):
  9667. objects = self.collection.get_list()
  9668. for obj in objects:
  9669. obj.clear(obj == objects[-1])
  9670. # Clear pool to free memory
  9671. self.clear_pool()
  9672. def generate_cnc_job(self, objects):
  9673. self.report_usage("generate_cnc_job()")
  9674. # for obj in objects:
  9675. # obj.generatecncjob()
  9676. for obj in objects:
  9677. obj.on_generatecnc_button_click()
  9678. def save_project(self, filename, quit_action=False, silent=False):
  9679. """
  9680. Saves the current project to the specified file.
  9681. :param filename: Name of the file in which to save.
  9682. :type filename: str
  9683. :param quit_action: if the project saving will be followed by an app quit; boolean
  9684. :param silent: if True will not display status messages
  9685. :return: None
  9686. """
  9687. self.log.debug("save_project()")
  9688. self.save_in_progress = True
  9689. with self.proc_container.new(_("Saving FlatCAM Project")):
  9690. # Capture the latest changes
  9691. # Current object
  9692. try:
  9693. self.collection.get_active().read_form()
  9694. except:
  9695. self.log.debug("There was no active object")
  9696. pass
  9697. # Project options
  9698. self.options_read_form()
  9699. # Serialize the whole project
  9700. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  9701. "options": self.options,
  9702. "version": self.version}
  9703. if self.defaults["global_save_compressed"] is True:
  9704. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  9705. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  9706. # # Write
  9707. f.write(g)
  9708. self.inform.emit('[success] %s: %s' %
  9709. (_("Project saved to"), filename))
  9710. else:
  9711. # Open file
  9712. try:
  9713. f = open(filename, 'w')
  9714. except IOError:
  9715. App.log.error("Failed to open file for saving: %s", filename)
  9716. return
  9717. # Write
  9718. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  9719. f.close()
  9720. # verification of the saved project
  9721. # Open and parse
  9722. try:
  9723. saved_f = open(filename, 'r')
  9724. except IOError:
  9725. if silent is False:
  9726. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9727. (_("Failed to verify project file"), filename, _("Retry to save it."))
  9728. )
  9729. return
  9730. try:
  9731. saved_d = json.load(saved_f, object_hook=dict2obj)
  9732. except:
  9733. if silent is False:
  9734. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9735. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9736. )
  9737. f.close()
  9738. return
  9739. saved_f.close()
  9740. if silent is False:
  9741. if 'version' in saved_d:
  9742. self.inform.emit('[success] %s: %s' %
  9743. (_("Project saved to"), filename))
  9744. else:
  9745. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9746. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9747. )
  9748. settings = QSettings("Open Source", "FlatCAM")
  9749. lock_state = self.ui.lock_action.isChecked()
  9750. settings.setValue('toolbar_lock', lock_state)
  9751. # This will write the setting to the platform specific storage.
  9752. del settings
  9753. # if quit:
  9754. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  9755. # t.start()
  9756. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  9757. def start_delayed_quit(self, delay, filename, should_quit=None):
  9758. """
  9759. :param delay: period of checking if project file size is more than zero; in seconds
  9760. :param filename: the name of the project file to be checked periodically for size more than zero
  9761. :param should_quit: if the task finished will be followed by an app quit; boolean
  9762. :return:
  9763. """
  9764. to_quit = should_quit
  9765. self.save_timer = QtCore.QTimer()
  9766. self.save_timer.setInterval(delay)
  9767. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  9768. self.save_timer.start()
  9769. def check_project_file_size(self, filename, should_quit=None):
  9770. """
  9771. :param filename: the name of the project file to be checked periodically for size more than zero
  9772. :param should_quit: will quit the app if True; boolean
  9773. :return:
  9774. """
  9775. try:
  9776. if os.stat(filename).st_size > 0:
  9777. self.save_in_progress = False
  9778. self.save_timer.stop()
  9779. if should_quit:
  9780. self.app_quit.emit()
  9781. except Exception as e:
  9782. traceback.print_exc()
  9783. def on_options_app2project(self):
  9784. """
  9785. Callback for Options->Transfer Options->App=>Project. Copies options
  9786. from application defaults to project defaults.
  9787. :return: None
  9788. """
  9789. self.report_usage("on_options_app2project")
  9790. self.defaults_read_form()
  9791. self.options.update(self.defaults)
  9792. self.options_write_form()
  9793. def on_options_project2app(self):
  9794. """
  9795. Callback for Options->Transfer Options->Project=>App. Copies options
  9796. from project defaults to application defaults.
  9797. :return: None
  9798. """
  9799. self.report_usage("on_options_project2app")
  9800. self.options_read_form()
  9801. self.defaults.update(self.options)
  9802. self.defaults_write_form()
  9803. def on_options_project2object(self):
  9804. """
  9805. Callback for Options->Transfer Options->Project=>Object. Copies options
  9806. from project defaults to the currently selected object.
  9807. :return: None
  9808. """
  9809. self.report_usage("on_options_project2object")
  9810. self.options_read_form()
  9811. obj = self.collection.get_active()
  9812. if obj is None:
  9813. self.inform.emit('[WARNING_NOTCL] %s' %
  9814. _("No object selected."))
  9815. return
  9816. for option in self.options:
  9817. if option.find(obj.kind + "_") == 0:
  9818. oname = option[len(obj.kind) + 1:]
  9819. obj.options[oname] = self.options[option]
  9820. obj.to_form() # Update UI
  9821. def on_options_object2project(self):
  9822. """
  9823. Callback for Options->Transfer Options->Object=>Project. Copies options
  9824. from the currently selected object to project defaults.
  9825. :return: None
  9826. """
  9827. self.report_usage("on_options_object2project")
  9828. obj = self.collection.get_active()
  9829. if obj is None:
  9830. self.inform.emit('[WARNING_NOTCL] %s' %
  9831. _("No object selected."))
  9832. return
  9833. obj.read_form()
  9834. for option in obj.options:
  9835. if option in ['name']: # TODO: Handle this better...
  9836. continue
  9837. self.options[obj.kind + "_" + option] = obj.options[option]
  9838. self.options_write_form()
  9839. def on_options_object2app(self):
  9840. """
  9841. Callback for Options->Transfer Options->Object=>App. Copies options
  9842. from the currently selected object to application defaults.
  9843. :return: None
  9844. """
  9845. self.report_usage("on_options_object2app")
  9846. obj = self.collection.get_active()
  9847. if obj is None:
  9848. self.inform.emit('[WARNING_NOTCL] %s' %
  9849. _("No object selected."))
  9850. return
  9851. obj.read_form()
  9852. for option in obj.options:
  9853. if option in ['name']: # TODO: Handle this better...
  9854. continue
  9855. self.defaults[obj.kind + "_" + option] = obj.options[option]
  9856. self.defaults_write_form()
  9857. def on_options_app2object(self):
  9858. """
  9859. Callback for Options->Transfer Options->App=>Object. Copies options
  9860. from application defaults to the currently selected object.
  9861. :return: None
  9862. """
  9863. self.report_usage("on_options_app2object")
  9864. self.defaults_read_form()
  9865. obj = self.collection.get_active()
  9866. if obj is None:
  9867. self.inform.emit('[WARNING_NOTCL] %s' %
  9868. _("No object selected."))
  9869. return
  9870. for option in self.defaults:
  9871. if option.find(obj.kind + "_") == 0:
  9872. oname = option[len(obj.kind) + 1:]
  9873. obj.options[oname] = self.defaults[option]
  9874. obj.to_form() # Update UI
  9875. class ArgsThread(QtCore.QObject):
  9876. open_signal = pyqtSignal(list)
  9877. start = pyqtSignal()
  9878. if sys.platform == 'win32':
  9879. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  9880. else:
  9881. address = ('/tmp/testipc', 'AF_UNIX')
  9882. def __init__(self):
  9883. super(ArgsThread, self).__init__()
  9884. self.start.connect(self.run)
  9885. def my_loop(self, address):
  9886. try:
  9887. listener = Listener(*address)
  9888. while True:
  9889. conn = listener.accept()
  9890. self.serve(conn)
  9891. except socket.error as e:
  9892. conn = Client(*address)
  9893. conn.send(sys.argv)
  9894. conn.send('close')
  9895. # close the current instance only if there are args
  9896. if len(sys.argv) > 1:
  9897. sys.exit()
  9898. def serve(self, conn):
  9899. while True:
  9900. msg = conn.recv()
  9901. if msg == 'close':
  9902. break
  9903. self.open_signal.emit(msg)
  9904. conn.close()
  9905. # the decorator is a must; without it this technique will not work unless the start signal is connected
  9906. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  9907. @pyqtSlot()
  9908. def run(self):
  9909. self.my_loop(self.address)
  9910. class GracefulException(Exception):
  9911. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  9912. def __init__(self):
  9913. super().__init__()
  9914. def __str__(self):
  9915. return '\n\n%s' % _("The user requested a graceful exit of the current task.")
  9916. # end of file